code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class __lowerCamelCase ( _a , unittest.TestCase ): a : Dict =BlenderbotSmallTokenizer a : Tuple =False def SCREAMING_SNAKE_CASE__ ( self ) -> str: super().setUp() UpperCamelCase__ = ['__start__', 'adapt', 'act', 'ap@@', 'te', '__end__', '__unk__'] UpperCamelCase__ = dict(zip(snake_case_ , range(len(snake_case_ ) ) ) ) UpperCamelCase__ = ['#version: 0.2', 'a p', 't e</w>', 'ap t</w>', 'a d', 'ad apt</w>', 'a c', 'ac t</w>', ''] UpperCamelCase__ = {'unk_token': '__unk__', 'bos_token': '__start__', 'eos_token': '__end__'} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(snake_case_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( self , **snake_case_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Dict: UpperCamelCase__ = 'adapt act apte' UpperCamelCase__ = 'adapt act apte' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = 'adapt act apte' UpperCamelCase__ = ['adapt', 'act', 'ap@@', 'te'] UpperCamelCase__ = tokenizer.tokenize(snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) UpperCamelCase__ = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] UpperCamelCase__ = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case_ ) , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) assert tok('sam' ).input_ids == [1384] UpperCamelCase__ = 'I am a small frog.' UpperCamelCase__ = tok([src_text] , padding=snake_case_ , truncation=snake_case_ )['input_ids'] UpperCamelCase__ = tok.batch_decode(snake_case_ , skip_special_tokens=snake_case_ , clean_up_tokenization_spaces=snake_case_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) UpperCamelCase__ = 'I am a small frog .' UpperCamelCase__ = '.' UpperCamelCase__ = tok(snake_case_ )['input_ids'] UpperCamelCase__ = tok(snake_case_ )['input_ids'] assert encoded[-1] == encoded_dot[0]
20
"""simple docstring""" import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("""9.1.0"""): A__ : str= { """linear""": PIL.Image.Resampling.BILINEAR, """bilinear""": PIL.Image.Resampling.BILINEAR, """bicubic""": PIL.Image.Resampling.BICUBIC, """lanczos""": PIL.Image.Resampling.LANCZOS, """nearest""": PIL.Image.Resampling.NEAREST, } else: A__ : str= { """linear""": PIL.Image.LINEAR, """bilinear""": PIL.Image.BILINEAR, """bicubic""": PIL.Image.BICUBIC, """lanczos""": PIL.Image.LANCZOS, """nearest""": PIL.Image.NEAREST, } def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = (images / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() UpperCamelCase__ = numpy_to_pil(SCREAMING_SNAKE_CASE ) return images def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if images.ndim == 3: UpperCamelCase__ = images[None, ...] UpperCamelCase__ = (images * 2_55).round().astype('uint8' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images UpperCamelCase__ = [Image.fromarray(image.squeeze() , mode='L' ) for image in images] else: UpperCamelCase__ = [Image.fromarray(SCREAMING_SNAKE_CASE ) for image in images] return pil_images
20
1
"""simple docstring""" from maths.prime_factors import prime_factors def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = F'Input value of [number={number}] must be an integer' raise TypeError(SCREAMING_SNAKE_CASE ) if number < 1: raise ValueError('Input must be a positive integer' ) return -1 if len(prime_factors(SCREAMING_SNAKE_CASE ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
20
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging A__ : Dict= logging.get_logger(__name__) A__ : str= {"""vocab_file""": """spiece.model"""} A__ : Union[str, Any]= { """vocab_file""": { """t5-small""": """https://huggingface.co/t5-small/resolve/main/spiece.model""", """t5-base""": """https://huggingface.co/t5-base/resolve/main/spiece.model""", """t5-large""": """https://huggingface.co/t5-large/resolve/main/spiece.model""", """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/spiece.model""", """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/spiece.model""", } } # TODO(PVP) - this should be removed in Transformers v5 A__ : Union[str, Any]= { """t5-small""": 5_12, """t5-base""": 5_12, """t5-large""": 5_12, """t5-3b""": 5_12, """t5-11b""": 5_12, } A__ : Optional[Any]= """▁""" class __lowerCamelCase ( _a ): a : Dict =VOCAB_FILES_NAMES a : str =PRETRAINED_VOCAB_FILES_MAP a : Union[str, Any] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : List[str] =["""input_ids""", """attention_mask"""] def __init__( self , snake_case_ , snake_case_="</s>" , snake_case_="<unk>" , snake_case_="<pad>" , snake_case_=100 , snake_case_=None , snake_case_ = None , snake_case_=True , **snake_case_ , ) -> None: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: UpperCamelCase__ = [F'<extra_id_{i}>' for i in range(snake_case_ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens UpperCamelCase__ = len(set(filter(lambda snake_case_ : bool('extra_id' in str(snake_case_ ) ) , snake_case_ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' ' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids' ' tokens' ) if legacy: logger.warning_once( F'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to' ' read the related pull request available at https://github.com/huggingface/transformers/pull/24565' ) UpperCamelCase__ = legacy UpperCamelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=snake_case_ , unk_token=snake_case_ , pad_token=snake_case_ , extra_ids=snake_case_ , additional_special_tokens=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , legacy=snake_case_ , **snake_case_ , ) UpperCamelCase__ = vocab_file UpperCamelCase__ = extra_ids UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: UpperCamelCase__ = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( 'This tokenizer was incorrectly instantiated with a model max length of' F' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' ' behavior is kept to avoid breaking backwards compatibility when padding/encoding with' ' `truncation is True`.\n- Be aware that you SHOULD NOT rely on' F' {pretrained_model_name_or_path} automatically truncating your input to' F' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' F' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' ' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please' ' instantiate this tokenizer with `model_max_length` set to your preferred value.' , snake_case_ , ) return max_model_length @property def SCREAMING_SNAKE_CASE__ ( self ) -> Any: return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = {self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case_ , token_ids_a=snake_case_ , already_has_special_tokens=snake_case_ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(snake_case_ )) + [1] return ([0] * len(snake_case_ )) + [1] + ([0] * len(snake_case_ )) + [1] def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return list( set(filter(lambda snake_case_ : bool(re.search(r'<extra_id_\d+>' , snake_case_ ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: return [self._convert_token_to_id(snake_case_ ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[int]: if len(snake_case_ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' ' eos tokens being added.' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = self._add_eos_if_not_present(snake_case_ ) if token_ids_a is None: return token_ids_a else: UpperCamelCase__ = self._add_eos_if_not_present(snake_case_ ) return token_ids_a + token_ids_a def __getstate__( self ) -> str: UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = None return state def __setstate__( self , snake_case_ ) -> Any: UpperCamelCase__ = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): UpperCamelCase__ = {} UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , **snake_case_ ) -> List[str]: # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: UpperCamelCase__ = SPIECE_UNDERLINE + text.replace(snake_case_ , ' ' ) return super().tokenize(snake_case_ , **snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , **snake_case_ ) -> List[Any]: if not self.legacy: UpperCamelCase__ = text.startswith(snake_case_ ) if is_first: UpperCamelCase__ = text[1:] UpperCamelCase__ = self.sp_model.encode(snake_case_ , out_type=snake_case_ ) if not self.legacy and not is_first and not text.startswith(' ' ) and tokens[0].startswith(snake_case_ ): UpperCamelCase__ = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: if token.startswith('<extra_id_' ): UpperCamelCase__ = re.match(r'<extra_id_(\d+)>' , snake_case_ ) UpperCamelCase__ = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Optional[int]: if index < self.sp_model.get_piece_size(): UpperCamelCase__ = self.sp_model.IdToPiece(snake_case_ ) else: UpperCamelCase__ = F'<extra_id_{self.vocab_size - 1 - index}>' return token def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: UpperCamelCase__ = [] UpperCamelCase__ = '' UpperCamelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(snake_case_ ) + token UpperCamelCase__ = True UpperCamelCase__ = [] else: current_sub_tokens.append(snake_case_ ) UpperCamelCase__ = False out_string += self.sp_model.decode(snake_case_ ) return out_string.strip() def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> Tuple[str]: if not os.path.isdir(snake_case_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase__ = os.path.join( snake_case_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case_ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case_ , 'wb' ) as fi: UpperCamelCase__ = self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,)
20
1
"""simple docstring""" from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class __lowerCamelCase : def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=2 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> Tuple: UpperCamelCase__ = parent UpperCamelCase__ = 13 UpperCamelCase__ = 7 UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = 99 UpperCamelCase__ = 384 UpperCamelCase__ = 2 UpperCamelCase__ = 4 UpperCamelCase__ = 37 UpperCamelCase__ = 'gelu' UpperCamelCase__ = 0.1 UpperCamelCase__ = 0.1 UpperCamelCase__ = 512 UpperCamelCase__ = 16 UpperCamelCase__ = 2 UpperCamelCase__ = 0.02 UpperCamelCase__ = 3 UpperCamelCase__ = 4 UpperCamelCase__ = 128 UpperCamelCase__ = 2 UpperCamelCase__ = 9 UpperCamelCase__ = 1 UpperCamelCase__ = None def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=snake_case_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertModel(config=snake_case_ ) UpperCamelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} UpperCamelCase__ = [input_ids, input_mask] UpperCamelCase__ = model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertForMaskedLM(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForSequenceClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = self.num_choices UpperCamelCase__ = TFConvBertForMultipleChoice(config=snake_case_ ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForTokenClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = TFConvBertForQuestionAnswering(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class __lowerCamelCase ( _a , _a , unittest.TestCase ): a : Any =( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) a : str =( { """feature-extraction""": TFConvBertModel, """fill-mask""": TFConvBertForMaskedLM, """question-answering""": TFConvBertForQuestionAnswering, """text-classification""": TFConvBertForSequenceClassification, """token-classification""": TFConvBertForTokenClassification, """zero-shot""": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) a : Any =False a : Dict =False a : str =False def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = TFConvBertModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = True if hasattr(snake_case_ , 'use_cache' ): UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) for model_class in self.all_model_classes: UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ ) UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = len(model(snake_case_ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(snake_case_ , saved_model=snake_case_ ) UpperCamelCase__ = os.path.join(snake_case_ , 'saved_model' , '1' ) UpperCamelCase__ = tf.keras.models.load_model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = outputs['encoder_hidden_states'] UpperCamelCase__ = outputs['encoder_attentions'] else: UpperCamelCase__ = outputs['hidden_states'] UpperCamelCase__ = outputs['attentions'] self.assertEqual(len(snake_case_ ) , snake_case_ ) UpperCamelCase__ = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(snake_case_ ) , snake_case_ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) def check_decoder_attentions_output(snake_case_ ): UpperCamelCase__ = len(snake_case_ ) self.assertEqual(out_len % 2 , 0 ) UpperCamelCase__ = outputs.decoder_attentions self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(snake_case_ ): UpperCamelCase__ = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: UpperCamelCase__ = True UpperCamelCase__ = False UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) UpperCamelCase__ = len(snake_case_ ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_decoder_attentions_output(snake_case_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) # Check attention is always last and order is fine UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(snake_case_ ) ) self.assertEqual(model.config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) @require_tf class __lowerCamelCase ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) UpperCamelCase__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase__ = model(snake_case_ )[0] UpperCamelCase__ = [1, 6, 768] self.assertEqual(output.shape , snake_case_ ) UpperCamelCase__ = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , snake_case_ , atol=1E-4 )
20
"""simple docstring""" from __future__ import annotations from typing import Generic, TypeVar A__ : Any= TypeVar("""T""") class __lowerCamelCase ( Generic[T] ): def __init__( self , snake_case_ ) -> None: UpperCamelCase__ = data UpperCamelCase__ = self UpperCamelCase__ = 0 class __lowerCamelCase ( Generic[T] ): def __init__( self ) -> None: # map from node name to the node object UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: # create a new set with x as its member UpperCamelCase__ = DisjointSetTreeNode(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> DisjointSetTreeNode[T]: # find the set x belongs to (with path-compression) UpperCamelCase__ = self.map[data] if elem_ref != elem_ref.parent: UpperCamelCase__ = self.find_set(elem_ref.parent.data ) return elem_ref.parent def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: # helper function for union operation if nodea.rank > nodea.rank: UpperCamelCase__ = nodea else: UpperCamelCase__ = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: # merge 2 disjoint sets self.link(self.find_set(snake_case_ ) , self.find_set(snake_case_ ) ) class __lowerCamelCase ( Generic[T] ): def __init__( self ) -> None: # connections: map from the node to the neighbouring nodes (with weights) UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: # add a node ONLY if its not present in the graph if node not in self.connections: UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> None: # add an edge with the given weight self.add_node(snake_case_ ) self.add_node(snake_case_ ) UpperCamelCase__ = weight UpperCamelCase__ = weight def SCREAMING_SNAKE_CASE__ ( self ) -> GraphUndirectedWeighted[T]: UpperCamelCase__ = [] UpperCamelCase__ = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda snake_case_ : x[2] ) # creating the disjoint set UpperCamelCase__ = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(snake_case_ ) # MST generation UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = edges[index] index += 1 UpperCamelCase__ = disjoint_set.find_set(snake_case_ ) UpperCamelCase__ = disjoint_set.find_set(snake_case_ ) if parent_u != parent_v: num_edges += 1 graph.add_edge(snake_case_ , snake_case_ , snake_case_ ) disjoint_set.union(snake_case_ , snake_case_ ) return graph
20
1
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path A__ : str= ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) A__ : list[int]= [ord(letter) for letter in string.ascii_lowercase] A__ : set[int]= {ord(char) for char in VALID_CHARS} A__ : list[str]= ["the", "be", "to", "of", "and", "in", "that", "have"] def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str | None: """simple docstring""" UpperCamelCase__ = "" UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = 42 for keychar, cipherchar in zip(cycle(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(SCREAMING_SNAKE_CASE ) return decoded def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> list[str]: """simple docstring""" UpperCamelCase__ = [] for key in product(SCREAMING_SNAKE_CASE , repeat=3 ): UpperCamelCase__ = try_key(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if encoded is not None: possibles.append(SCREAMING_SNAKE_CASE ) return possibles def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> list[str]: """simple docstring""" return [possible for possible in possibles if common_word in possible.lower()] def lowerCAmelCase_( SCREAMING_SNAKE_CASE = "p059_cipher.txt" ) -> int: """simple docstring""" UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = Path(SCREAMING_SNAKE_CASE ).parent.joinpath(SCREAMING_SNAKE_CASE ).read_text(encoding='utf-8' ) UpperCamelCase__ = [int(SCREAMING_SNAKE_CASE ) for number in data.strip().split(',' )] UpperCamelCase__ = filter_valid_chars(SCREAMING_SNAKE_CASE ) for common_word in COMMON_WORDS: UpperCamelCase__ = filter_common_word(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) == 1: break UpperCamelCase__ = possibles[0] return sum(ord(SCREAMING_SNAKE_CASE ) for char in decoded_text ) if __name__ == "__main__": print(F"""{solution() = }""")
20
"""simple docstring""" A__ : Tuple= """Alexander Joslin""" import operator as op from .stack import Stack def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} UpperCamelCase__ = Stack() UpperCamelCase__ = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(SCREAMING_SNAKE_CASE ) ) elif i in operators: # RULE 2 operator_stack.push(SCREAMING_SNAKE_CASE ) elif i == ")": # RULE 4 UpperCamelCase__ = operator_stack.peek() operator_stack.pop() UpperCamelCase__ = operand_stack.peek() operand_stack.pop() UpperCamelCase__ = operand_stack.peek() operand_stack.pop() UpperCamelCase__ = operators[opr](SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) operand_stack.push(SCREAMING_SNAKE_CASE ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": A__ : int= """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
20
1
"""simple docstring""" import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder A__ : Tuple= """__DUMMY_TRANSFORMERS_USER__""" A__ : Dict= """Dummy User""" A__ : Union[str, Any]= """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""" A__ : Union[str, Any]= """https://hub-ci.huggingface.co""" A__ : List[Any]= CI_HUB_ENDPOINT + """/datasets/{repo_id}/resolve/{revision}/{path}""" A__ : Union[str, Any]= CI_HUB_ENDPOINT + """/{repo_id}/resolve/{revision}/{filename}""" A__ : List[Any]= Path("""~/.huggingface/hub_ci_token""").expanduser() @pytest.fixture def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" monkeypatch.setattr( 'huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE' , SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" monkeypatch.setattr('datasets.config.HF_ENDPOINT' , SCREAMING_SNAKE_CASE ) monkeypatch.setattr('datasets.config.HUB_DATASETS_URL' , SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" monkeypatch.setattr('huggingface_hub.hf_api.HfFolder.path_token' , SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" HfFolder.save_token(SCREAMING_SNAKE_CASE ) yield HfFolder.delete_token() @pytest.fixture(scope='session' ) def lowerCAmelCase_( ) -> Optional[Any]: """simple docstring""" return HfApi(endpoint=SCREAMING_SNAKE_CASE ) @pytest.fixture(scope='session' ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = HfFolder.get_token() HfFolder.save_token(SCREAMING_SNAKE_CASE ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" def _cleanup_repo(SCREAMING_SNAKE_CASE ): hf_api.delete_repo(SCREAMING_SNAKE_CASE , token=SCREAMING_SNAKE_CASE , repo_type='dataset' ) return _cleanup_repo @pytest.fixture def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" @contextmanager def _temporary_repo(SCREAMING_SNAKE_CASE ): try: yield repo_id finally: cleanup_repo(SCREAMING_SNAKE_CASE ) return _temporary_repo @pytest.fixture(scope='session' ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" UpperCamelCase__ = F'repo_txt_data-{int(time.time() * 10E3 )}' UpperCamelCase__ = F'{CI_HUB_USER}/{repo_name}' hf_api.create_repo(SCREAMING_SNAKE_CASE , token=SCREAMING_SNAKE_CASE , repo_type='dataset' , private=SCREAMING_SNAKE_CASE ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE , path_or_fileobj=str(SCREAMING_SNAKE_CASE ) , path_in_repo='data/text_data.txt' , repo_id=SCREAMING_SNAKE_CASE , repo_type='dataset' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE , token=SCREAMING_SNAKE_CASE , repo_type='dataset' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope='session' ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" UpperCamelCase__ = F'repo_zipped_txt_data-{int(time.time() * 10E3 )}' UpperCamelCase__ = F'{CI_HUB_USER}/{repo_name}' hf_api.create_repo(SCREAMING_SNAKE_CASE , token=SCREAMING_SNAKE_CASE , repo_type='dataset' , private=SCREAMING_SNAKE_CASE ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE , path_or_fileobj=str(SCREAMING_SNAKE_CASE ) , path_in_repo='data.zip' , repo_id=SCREAMING_SNAKE_CASE , repo_type='dataset' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE , token=SCREAMING_SNAKE_CASE , repo_type='dataset' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope='session' ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = F'repo_zipped_img_data-{int(time.time() * 10E3 )}' UpperCamelCase__ = F'{CI_HUB_USER}/{repo_name}' hf_api.create_repo(SCREAMING_SNAKE_CASE , token=SCREAMING_SNAKE_CASE , repo_type='dataset' , private=SCREAMING_SNAKE_CASE ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE , path_or_fileobj=str(SCREAMING_SNAKE_CASE ) , path_in_repo='data.zip' , repo_id=SCREAMING_SNAKE_CASE , repo_type='dataset' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE , token=SCREAMING_SNAKE_CASE , repo_type='dataset' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return hf_private_dataset_repo_zipped_img_data_
20
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py A__ : Any= """src/diffusers""" # Matches is_xxx_available() A__ : Tuple= re.compile(r"""is\_([a-z_]*)_available\(\)""") # Matches from xxx import bla A__ : Any= re.compile(r"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""") A__ : Optional[Any]= """ {0} = None """ A__ : List[Any]= """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) """ A__ : Dict= """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ = _re_backend.findall(SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) == 0: return None return "_and_".join(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( ) -> str: """simple docstring""" with open(os.path.join(SCREAMING_SNAKE_CASE , '__init__.py' ) , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.readlines() # Get to the point we do the actual imports for type checking UpperCamelCase__ = 0 UpperCamelCase__ = {} # Go through the end of the file while line_index < len(SCREAMING_SNAKE_CASE ): # If the line contains is_backend_available, we grab all objects associated with the `else` block UpperCamelCase__ = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('else:' ): line_index += 1 line_index += 1 UpperCamelCase__ = [] # Until we unindent, add backend objects to the list while line_index < len(SCREAMING_SNAKE_CASE ) and len(lines[line_index] ) > 1: UpperCamelCase__ = lines[line_index] UpperCamelCase__ = _re_single_line_import.search(SCREAMING_SNAKE_CASE ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(SCREAMING_SNAKE_CASE ) > 0: UpperCamelCase__ = objects else: line_index += 1 return backend_specific_objects def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if name.isupper(): return DUMMY_CONSTANT.format(SCREAMING_SNAKE_CASE ) elif name.islower(): return DUMMY_FUNCTION.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: return DUMMY_CLASS.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" if backend_specific_objects is None: UpperCamelCase__ = read_init() # For special correspondence backend to module name as used in the function requires_modulename UpperCamelCase__ = {} for backend, objects in backend_specific_objects.items(): UpperCamelCase__ = '[' + ', '.join(F'"{b}"' for b in backend.split('_and_' ) ) + ']' UpperCamelCase__ = '# This file is autogenerated by the command `make fix-copies`, do not edit.\n' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for o in objects] ) UpperCamelCase__ = dummy_file return dummy_files def lowerCAmelCase_( SCREAMING_SNAKE_CASE=False ) -> int: """simple docstring""" UpperCamelCase__ = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py UpperCamelCase__ = {'torch': 'pt'} # Locate actual dummy modules and read their content. UpperCamelCase__ = os.path.join(SCREAMING_SNAKE_CASE , 'utils' ) UpperCamelCase__ = { backend: os.path.join(SCREAMING_SNAKE_CASE , F'dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py' ) for backend in dummy_files.keys() } UpperCamelCase__ = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(SCREAMING_SNAKE_CASE ): with open(SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.read() else: UpperCamelCase__ = '' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( F'Updating diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py as the main ' '__init__ has new objects.' ) with open(dummy_file_paths[backend] , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( 'The main __init__ has objects that are not present in ' F'diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py. Run `make fix-copies` ' 'to fix this.' ) if __name__ == "__main__": A__ : Any= argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") A__ : Optional[int]= parser.parse_args() check_dummies(args.fix_and_overwrite)
20
1
"""simple docstring""" import os from collections.abc import Iterator def lowerCAmelCase_( SCREAMING_SNAKE_CASE = "." ) -> Iterator[str]: """simple docstring""" for dir_path, dir_names, filenames in os.walk(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = [d for d in dir_names if d != 'scripts' and d[0] not in '._'] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(SCREAMING_SNAKE_CASE )[1] in (".py", ".ipynb"): yield os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).lstrip('./' ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" return F'{i * " "}*' if i else "\n##" def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" UpperCamelCase__ = old_path.split(os.sep ) for i, new_part in enumerate(new_path.split(os.sep ) ): if (i + 1 > len(SCREAMING_SNAKE_CASE ) or old_parts[i] != new_part) and new_part: print(F'{md_prefix(SCREAMING_SNAKE_CASE )} {new_part.replace("_" , " " ).title()}' ) return new_path def lowerCAmelCase_( SCREAMING_SNAKE_CASE = "." ) -> None: """simple docstring""" UpperCamelCase__ = '' for filepath in sorted(good_file_paths(SCREAMING_SNAKE_CASE ) ): UpperCamelCase__ , UpperCamelCase__ = os.path.split(SCREAMING_SNAKE_CASE ) if filepath != old_path: UpperCamelCase__ = print_path(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ = (filepath.count(os.sep ) + 1) if filepath else 0 UpperCamelCase__ = F'{filepath}/{filename}'.replace(' ' , '%20' ) UpperCamelCase__ = os.path.splitext(filename.replace('_' , ' ' ).title() )[0] print(F'{md_prefix(SCREAMING_SNAKE_CASE )} [{filename}]({url})' ) if __name__ == "__main__": print_directory_md(""".""")
20
"""simple docstring""" # Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file A__ : Optional[Any]= """Run commands across TPU VMs for initial setup before running `accelerate launch`.""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> Dict: """simple docstring""" if subparsers is not None: UpperCamelCase__ = subparsers.add_parser('tpu-config' , description=_description ) else: UpperCamelCase__ = argparse.ArgumentParser('Accelerate tpu-config command' , description=_description ) # Core arguments UpperCamelCase__ = parser.add_argument_group( 'Config Arguments' , 'Arguments that can be configured through `accelerate config`.' ) config_args.add_argument( '--config_file' , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , help='Path to the config file to use for accelerate.' , ) config_args.add_argument( '--tpu_name' , default=SCREAMING_SNAKE_CASE , help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.' , ) config_args.add_argument( '--tpu_zone' , default=SCREAMING_SNAKE_CASE , help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.' , ) UpperCamelCase__ = parser.add_argument_group('TPU Arguments' , 'Arguments for options ran inside the TPU.' ) pod_args.add_argument( '--use_alpha' , action='store_true' , help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.' , ) pod_args.add_argument( '--command_file' , default=SCREAMING_SNAKE_CASE , help='The path to the file containing the commands to run on the pod on startup.' , ) pod_args.add_argument( '--command' , action='append' , nargs='+' , help='A command to run on the pod. Can be passed multiple times.' , ) pod_args.add_argument( '--install_accelerate' , action='store_true' , help='Whether to install accelerate on the pod. Defaults to False.' , ) pod_args.add_argument( '--accelerate_version' , default='latest' , help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.' , ) pod_args.add_argument( '--debug' , action='store_true' , help='If set, will print the command that would be run instead of running it.' ) if subparsers is not None: parser.set_defaults(func=SCREAMING_SNAKE_CASE ) return parser def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase__ = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: UpperCamelCase__ = defaults.command_file if not args.command and defaults.commands is not None: UpperCamelCase__ = defaults.commands if not args.tpu_name: UpperCamelCase__ = defaults.tpu_name if not args.tpu_zone: UpperCamelCase__ = defaults.tpu_zone if args.accelerate_version == "dev": UpperCamelCase__ = 'git+https://github.com/huggingface/accelerate.git' elif args.accelerate_version == "latest": UpperCamelCase__ = 'accelerate -U' elif isinstance(parse(args.accelerate_version ) , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = F'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError('You must specify either a command file or a command to run on the pod.' ) if args.command_file: with open(args.command_file , 'r' ) as f: UpperCamelCase__ = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate UpperCamelCase__ = ['cd /usr/share'] if args.install_accelerate: new_cmd += [F'pip install {args.accelerate_version}'] new_cmd += args.command UpperCamelCase__ = '; '.join(SCREAMING_SNAKE_CASE ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess UpperCamelCase__ = ['gcloud'] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'Running {" ".join(SCREAMING_SNAKE_CASE )}' ) return subprocess.run(SCREAMING_SNAKE_CASE ) print('Successfully setup pod.' ) def lowerCAmelCase_( ) -> int: """simple docstring""" UpperCamelCase__ = tpu_command_parser() UpperCamelCase__ = parser.parse_args() tpu_command_launcher(SCREAMING_SNAKE_CASE )
20
1
"""simple docstring""" import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets A__ : List[Any]= datasets.logging.get_logger(__name__) A__ : str= """\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } """ A__ : int= """\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project's README at https://github.com/google-research/bleurt#readme for more information. """ A__ : Dict= """ BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: 'scores': List of scores. Examples: >>> predictions = [\"hello there\", \"general kenobi\"] >>> references = [\"hello there\", \"general kenobi\"] >>> bleurt = datasets.load_metric(\"bleurt\") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results[\"scores\"]]) [1.03, 1.04] """ A__ : Optional[Any]= { """bleurt-tiny-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip""", """bleurt-tiny-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip""", """bleurt-base-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip""", """bleurt-base-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip""", """bleurt-large-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip""", """bleurt-large-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip""", """BLEURT-20-D3""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip""", """BLEURT-20-D6""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip""", """BLEURT-20-D12""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip""", """BLEURT-20""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip""", } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCamelCase ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='https://github.com/google-research/bleurt' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/google-research/bleurt'] , reference_urls=['https://github.com/google-research/bleurt', 'https://arxiv.org/abs/2004.04696'] , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: # check that config name specifies a valid BLEURT model if self.config_name == "default": logger.warning( 'Using default BLEURT-Base checkpoint for sequence maximum length 128. ' 'You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').' ) UpperCamelCase__ = 'bleurt-base-128' if self.config_name.lower() in CHECKPOINT_URLS: UpperCamelCase__ = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: UpperCamelCase__ = self.config_name.upper() else: raise KeyError( F'{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}' ) # download the model checkpoint specified by self.config_name and set up the scorer UpperCamelCase__ = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) UpperCamelCase__ = score.BleurtScorer(os.path.join(snake_case_ , snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = self.scorer.score(references=snake_case_ , candidates=snake_case_ ) return {"scores": scores}
20
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : List[str]= logging.get_logger(__name__) class __lowerCamelCase ( _a ): a : Optional[int] ="""timm_backbone""" def __init__( self , snake_case_=None , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=None , **snake_case_ , ) -> Dict: super().__init__(**snake_case_ ) UpperCamelCase__ = backbone UpperCamelCase__ = num_channels UpperCamelCase__ = features_only UpperCamelCase__ = use_pretrained_backbone UpperCamelCase__ = True UpperCamelCase__ = out_indices if out_indices is not None else (-1,)
20
1
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py A__ : Any= """src/diffusers""" # Matches is_xxx_available() A__ : Tuple= re.compile(r"""is\_([a-z_]*)_available\(\)""") # Matches from xxx import bla A__ : Any= re.compile(r"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""") A__ : Optional[Any]= """ {0} = None """ A__ : List[Any]= """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) """ A__ : Dict= """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ = _re_backend.findall(SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) == 0: return None return "_and_".join(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( ) -> str: """simple docstring""" with open(os.path.join(SCREAMING_SNAKE_CASE , '__init__.py' ) , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.readlines() # Get to the point we do the actual imports for type checking UpperCamelCase__ = 0 UpperCamelCase__ = {} # Go through the end of the file while line_index < len(SCREAMING_SNAKE_CASE ): # If the line contains is_backend_available, we grab all objects associated with the `else` block UpperCamelCase__ = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('else:' ): line_index += 1 line_index += 1 UpperCamelCase__ = [] # Until we unindent, add backend objects to the list while line_index < len(SCREAMING_SNAKE_CASE ) and len(lines[line_index] ) > 1: UpperCamelCase__ = lines[line_index] UpperCamelCase__ = _re_single_line_import.search(SCREAMING_SNAKE_CASE ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(SCREAMING_SNAKE_CASE ) > 0: UpperCamelCase__ = objects else: line_index += 1 return backend_specific_objects def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if name.isupper(): return DUMMY_CONSTANT.format(SCREAMING_SNAKE_CASE ) elif name.islower(): return DUMMY_FUNCTION.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: return DUMMY_CLASS.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" if backend_specific_objects is None: UpperCamelCase__ = read_init() # For special correspondence backend to module name as used in the function requires_modulename UpperCamelCase__ = {} for backend, objects in backend_specific_objects.items(): UpperCamelCase__ = '[' + ', '.join(F'"{b}"' for b in backend.split('_and_' ) ) + ']' UpperCamelCase__ = '# This file is autogenerated by the command `make fix-copies`, do not edit.\n' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for o in objects] ) UpperCamelCase__ = dummy_file return dummy_files def lowerCAmelCase_( SCREAMING_SNAKE_CASE=False ) -> int: """simple docstring""" UpperCamelCase__ = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py UpperCamelCase__ = {'torch': 'pt'} # Locate actual dummy modules and read their content. UpperCamelCase__ = os.path.join(SCREAMING_SNAKE_CASE , 'utils' ) UpperCamelCase__ = { backend: os.path.join(SCREAMING_SNAKE_CASE , F'dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py' ) for backend in dummy_files.keys() } UpperCamelCase__ = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(SCREAMING_SNAKE_CASE ): with open(SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.read() else: UpperCamelCase__ = '' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( F'Updating diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py as the main ' '__init__ has new objects.' ) with open(dummy_file_paths[backend] , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( 'The main __init__ has objects that are not present in ' F'diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py. Run `make fix-copies` ' 'to fix this.' ) if __name__ == "__main__": A__ : Any= argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") A__ : Optional[int]= parser.parse_args() check_dummies(args.fix_and_overwrite)
20
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType A__ : Any= logging.get_logger(__name__) A__ : str= { """microsoft/layoutlmv3-base""": """https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json""", } class __lowerCamelCase ( _a ): a : List[str] ="""layoutlmv3""" def __init__( self , snake_case_=5_0265 , snake_case_=768 , snake_case_=12 , snake_case_=12 , snake_case_=3072 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=2 , snake_case_=0.02 , snake_case_=1E-5 , snake_case_=1 , snake_case_=0 , snake_case_=2 , snake_case_=1024 , snake_case_=128 , snake_case_=128 , snake_case_=True , snake_case_=32 , snake_case_=128 , snake_case_=64 , snake_case_=256 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=224 , snake_case_=3 , snake_case_=16 , snake_case_=None , **snake_case_ , ) -> Union[str, Any]: super().__init__( vocab_size=snake_case_ , hidden_size=snake_case_ , num_hidden_layers=snake_case_ , num_attention_heads=snake_case_ , intermediate_size=snake_case_ , hidden_act=snake_case_ , hidden_dropout_prob=snake_case_ , attention_probs_dropout_prob=snake_case_ , max_position_embeddings=snake_case_ , type_vocab_size=snake_case_ , initializer_range=snake_case_ , layer_norm_eps=snake_case_ , pad_token_id=snake_case_ , bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ , ) UpperCamelCase__ = max_ad_position_embeddings UpperCamelCase__ = coordinate_size UpperCamelCase__ = shape_size UpperCamelCase__ = has_relative_attention_bias UpperCamelCase__ = rel_pos_bins UpperCamelCase__ = max_rel_pos UpperCamelCase__ = has_spatial_attention_bias UpperCamelCase__ = rel_ad_pos_bins UpperCamelCase__ = max_rel_ad_pos UpperCamelCase__ = text_embed UpperCamelCase__ = visual_embed UpperCamelCase__ = input_size UpperCamelCase__ = num_channels UpperCamelCase__ = patch_size UpperCamelCase__ = classifier_dropout class __lowerCamelCase ( _a ): a : Tuple =version.parse("""1.12""" ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) else: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels'}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: return 12 def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , snake_case_ = 3 , snake_case_ = 40 , snake_case_ = 40 , ) -> Mapping[str, Any]: setattr(processor.image_processor , 'apply_ocr' , snake_case_ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase__ = processor.tokenizer.num_special_tokens_to_add(snake_case_ ) UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case_ ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase__ = [[' '.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes UpperCamelCase__ = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) UpperCamelCase__ = self._generate_dummy_images(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) UpperCamelCase__ = dict( processor( snake_case_ , text=snake_case_ , boxes=snake_case_ , return_tensors=snake_case_ , ) ) return inputs
20
1
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" if number < 0 or shift_amount < 0: raise ValueError('both inputs must be positive integers' ) UpperCamelCase__ = str(bin(SCREAMING_SNAKE_CASE ) ) binary_number += "0" * shift_amount return binary_number def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" if number < 0 or shift_amount < 0: raise ValueError('both inputs must be positive integers' ) UpperCamelCase__ = str(bin(SCREAMING_SNAKE_CASE ) )[2:] if shift_amount >= len(SCREAMING_SNAKE_CASE ): return "0b0" UpperCamelCase__ = binary_number[: len(SCREAMING_SNAKE_CASE ) - shift_amount] return "0b" + shifted_binary_number def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" if number >= 0: # Get binary representation of positive number UpperCamelCase__ = '0' + str(bin(SCREAMING_SNAKE_CASE ) ).strip('-' )[2:] else: # Get binary (2's complement) representation of negative number UpperCamelCase__ = len(bin(SCREAMING_SNAKE_CASE )[3:] ) # Find 2's complement of number UpperCamelCase__ = bin(abs(SCREAMING_SNAKE_CASE ) - (1 << binary_number_length) )[3:] UpperCamelCase__ = ( '1' + '0' * (binary_number_length - len(SCREAMING_SNAKE_CASE )) + binary_number ) if shift_amount >= len(SCREAMING_SNAKE_CASE ): return "0b" + binary_number[0] * len(SCREAMING_SNAKE_CASE ) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(SCREAMING_SNAKE_CASE ) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
20
"""simple docstring""" from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class __lowerCamelCase : def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=2 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> Tuple: UpperCamelCase__ = parent UpperCamelCase__ = 13 UpperCamelCase__ = 7 UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = 99 UpperCamelCase__ = 384 UpperCamelCase__ = 2 UpperCamelCase__ = 4 UpperCamelCase__ = 37 UpperCamelCase__ = 'gelu' UpperCamelCase__ = 0.1 UpperCamelCase__ = 0.1 UpperCamelCase__ = 512 UpperCamelCase__ = 16 UpperCamelCase__ = 2 UpperCamelCase__ = 0.02 UpperCamelCase__ = 3 UpperCamelCase__ = 4 UpperCamelCase__ = 128 UpperCamelCase__ = 2 UpperCamelCase__ = 9 UpperCamelCase__ = 1 UpperCamelCase__ = None def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=snake_case_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertModel(config=snake_case_ ) UpperCamelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} UpperCamelCase__ = [input_ids, input_mask] UpperCamelCase__ = model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertForMaskedLM(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForSequenceClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = self.num_choices UpperCamelCase__ = TFConvBertForMultipleChoice(config=snake_case_ ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForTokenClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = TFConvBertForQuestionAnswering(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class __lowerCamelCase ( _a , _a , unittest.TestCase ): a : Any =( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) a : str =( { """feature-extraction""": TFConvBertModel, """fill-mask""": TFConvBertForMaskedLM, """question-answering""": TFConvBertForQuestionAnswering, """text-classification""": TFConvBertForSequenceClassification, """token-classification""": TFConvBertForTokenClassification, """zero-shot""": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) a : Any =False a : Dict =False a : str =False def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = TFConvBertModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = True if hasattr(snake_case_ , 'use_cache' ): UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) for model_class in self.all_model_classes: UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ ) UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = len(model(snake_case_ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(snake_case_ , saved_model=snake_case_ ) UpperCamelCase__ = os.path.join(snake_case_ , 'saved_model' , '1' ) UpperCamelCase__ = tf.keras.models.load_model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = outputs['encoder_hidden_states'] UpperCamelCase__ = outputs['encoder_attentions'] else: UpperCamelCase__ = outputs['hidden_states'] UpperCamelCase__ = outputs['attentions'] self.assertEqual(len(snake_case_ ) , snake_case_ ) UpperCamelCase__ = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(snake_case_ ) , snake_case_ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) def check_decoder_attentions_output(snake_case_ ): UpperCamelCase__ = len(snake_case_ ) self.assertEqual(out_len % 2 , 0 ) UpperCamelCase__ = outputs.decoder_attentions self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(snake_case_ ): UpperCamelCase__ = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: UpperCamelCase__ = True UpperCamelCase__ = False UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) UpperCamelCase__ = len(snake_case_ ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_decoder_attentions_output(snake_case_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) # Check attention is always last and order is fine UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(snake_case_ ) ) self.assertEqual(model.config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) @require_tf class __lowerCamelCase ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) UpperCamelCase__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase__ = model(snake_case_ )[0] UpperCamelCase__ = [1, 6, 768] self.assertEqual(output.shape , snake_case_ ) UpperCamelCase__ = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , snake_case_ , atol=1E-4 )
20
1
"""simple docstring""" from PIL import Image def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Image: """simple docstring""" UpperCamelCase__ , UpperCamelCase__ = image.size UpperCamelCase__ = 0 UpperCamelCase__ = image.load() for i in range(SCREAMING_SNAKE_CASE ): for j in range(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = pixels[j, i] mean += pixel mean //= width * height for j in range(SCREAMING_SNAKE_CASE ): for i in range(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 2_55 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": A__ : List[str]= mean_threshold(Image.open("""path_to_image""").convert("""L""")) image.save("""output_image_path""")
20
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 1_00_00_00 , SCREAMING_SNAKE_CASE = 10 ) -> int: """simple docstring""" UpperCamelCase__ = defaultdict(SCREAMING_SNAKE_CASE ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: UpperCamelCase__ = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: UpperCamelCase__ = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(SCREAMING_SNAKE_CASE , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"""{solution() = }""")
20
1
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( 'files' , [ ['full:README.md', 'dataset_infos.json'], ['empty:README.md', 'dataset_infos.json'], ['dataset_infos.json'], ['full:README.md'], ] , ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" UpperCamelCase__ = tmp_path_factory.mktemp('dset_infos_dir' ) if "full:README.md" in files: with open(dataset_infos_dir / 'README.md' , 'w' ) as f: f.write('---\ndataset_info:\n dataset_size: 42\n---' ) if "empty:README.md" in files: with open(dataset_infos_dir / 'README.md' , 'w' ) as f: f.write('' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / 'dataset_infos.json' , 'w' ) as f: f.write('{"default": {"dataset_size": 42}}' ) UpperCamelCase__ = DatasetInfosDict.from_directory(SCREAMING_SNAKE_CASE ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( 'dataset_info' , [ DatasetInfo(), DatasetInfo( description='foo' , features=Features({'a': Value('int32' )} ) , builder_name='builder' , config_name='config' , version='1.0.0' , splits=[{'name': 'train'}] , download_size=42 , ), ] , ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" UpperCamelCase__ = str(SCREAMING_SNAKE_CASE ) dataset_info.write_to_directory(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = DatasetInfo.from_directory(SCREAMING_SNAKE_CASE ) assert dataset_info == reloaded assert os.path.exists(os.path.join(SCREAMING_SNAKE_CASE , 'dataset_info.json' ) ) def lowerCAmelCase_( ) -> Optional[int]: """simple docstring""" UpperCamelCase__ = DatasetInfo( description='foo' , citation='bar' , homepage='https://foo.bar' , license='CC0' , features=Features({'a': Value('int32' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='builder' , config_name='config' , version='1.0.0' , splits=[{'name': 'train', 'num_examples': 42}] , download_checksums={} , download_size=13_37 , post_processing_size=4_42 , dataset_size=12_34 , size_in_bytes=13_37 + 4_42 + 12_34 , ) UpperCamelCase__ = dataset_info._to_yaml_dict() assert sorted(SCREAMING_SNAKE_CASE ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) UpperCamelCase__ = yaml.safe_dump(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = yaml.safe_load(SCREAMING_SNAKE_CASE ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_( ) -> Dict: """simple docstring""" UpperCamelCase__ = DatasetInfo() UpperCamelCase__ = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( 'dataset_infos_dict' , [ DatasetInfosDict(), DatasetInfosDict({'default': DatasetInfo()} ), DatasetInfosDict({'my_config_name': DatasetInfo()} ), DatasetInfosDict( { 'default': DatasetInfo( description='foo' , features=Features({'a': Value('int32' )} ) , builder_name='builder' , config_name='config' , version='1.0.0' , splits=[{'name': 'train'}] , download_size=42 , ) } ), DatasetInfosDict( { 'v1': DatasetInfo(dataset_size=42 ), 'v2': DatasetInfo(dataset_size=13_37 ), } ), ] , ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" UpperCamelCase__ = str(SCREAMING_SNAKE_CASE ) dataset_infos_dict.write_to_directory(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = DatasetInfosDict.from_directory(SCREAMING_SNAKE_CASE ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): UpperCamelCase__ = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml UpperCamelCase__ = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(SCREAMING_SNAKE_CASE , 'README.md' ) )
20
"""simple docstring""" import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __lowerCamelCase ( unittest.TestCase ): def __init__( self , snake_case_ , snake_case_=100 , snake_case_=13 , snake_case_=30 , snake_case_=2 , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=10 , snake_case_=0.02 , snake_case_=3 , ) -> Optional[int]: UpperCamelCase__ = parent UpperCamelCase__ = vocab_size UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = patch_size UpperCamelCase__ = num_channels UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCamelCase__ = (image_size // patch_size) ** 2 UpperCamelCase__ = num_patches + 1 def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=snake_case_ , initializer_range=self.initializer_range , ) return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = FlaxBeitModel(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = FlaxBeitForMaskedImageModeling(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.type_sequence_label_size UpperCamelCase__ = FlaxBeitForImageClassification(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase__ = 1 UpperCamelCase__ = FlaxBeitForImageClassification(snake_case_ ) UpperCamelCase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase__ = model(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class __lowerCamelCase ( _a , unittest.TestCase ): a : int =( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE__ ( self ) -> None: UpperCamelCase__ = FlaxBeitModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ['pixel_values'] self.assertListEqual(arg_names[:1] , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ ) UpperCamelCase__ = model_class(snake_case_ ) @jax.jit def model_jitted(snake_case_ , **snake_case_ ): return model(pixel_values=snake_case_ , **snake_case_ ) with self.subTest('JIT Enabled' ): UpperCamelCase__ = model_jitted(**snake_case_ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): UpperCamelCase__ = model_jitted(**snake_case_ ).to_tuple() self.assertEqual(len(snake_case_ ) , len(snake_case_ ) ) for jitted_output, output in zip(snake_case_ , snake_case_ ): self.assertEqual(jitted_output.shape , output.shape ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: for model_class_name in self.all_model_classes: UpperCamelCase__ = model_class_name.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase__ = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(snake_case_ ) def lowerCAmelCase_( ) -> Optional[int]: """simple docstring""" UpperCamelCase__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @require_flax class __lowerCamelCase ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = FlaxBeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ).pixel_values # prepare bool_masked_pos UpperCamelCase__ = np.ones((1, 196) , dtype=snake_case_ ) # forward pass UpperCamelCase__ = model(pixel_values=snake_case_ , bool_masked_pos=snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 196, 8192) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , snake_case_ , atol=1E-2 ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ) # forward pass UpperCamelCase__ = model(**snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 1000) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array([-1.2_385, -1.0_987, -1.0_108] ) self.assertTrue(np.allclose(logits[0, :3] , snake_case_ , atol=1E-4 ) ) UpperCamelCase__ = 281 self.assertEqual(logits.argmax(-1 ).item() , snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ) # forward pass UpperCamelCase__ = model(**snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 2_1841) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array([1.6_881, -0.2_787, 0.5_901] ) self.assertTrue(np.allclose(logits[0, :3] , snake_case_ , atol=1E-4 ) ) UpperCamelCase__ = 2396 self.assertEqual(logits.argmax(-1 ).item() , snake_case_ )
20
1
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __lowerCamelCase : @staticmethod def SCREAMING_SNAKE_CASE__ ( *snake_case_ , **snake_case_ ) -> List[Any]: pass @is_pipeline_test @require_vision @require_timm @require_torch class __lowerCamelCase ( unittest.TestCase ): a : List[Any] =MODEL_FOR_OBJECT_DETECTION_MAPPING def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> Dict: UpperCamelCase__ = ObjectDetectionPipeline(model=snake_case_ , image_processor=snake_case_ ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Optional[int]: UpperCamelCase__ = object_detector('./tests/fixtures/tests_samples/COCO/000000039769.png' , threshold=0.0 ) self.assertGreater(len(snake_case_ ) , 0 ) for detected_object in outputs: self.assertEqual( snake_case_ , { 'score': ANY(snake_case_ ), 'label': ANY(snake_case_ ), 'box': {'xmin': ANY(snake_case_ ), 'ymin': ANY(snake_case_ ), 'xmax': ANY(snake_case_ ), 'ymax': ANY(snake_case_ )}, } , ) import datasets UpperCamelCase__ = datasets.load_dataset('hf-internal-testing/fixtures_image_utils' , 'image' , split='test' ) UpperCamelCase__ = [ Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ), 'http://images.cocodataset.org/val2017/000000039769.jpg', # RGBA dataset[0]['file'], # LA dataset[1]['file'], # L dataset[2]['file'], ] UpperCamelCase__ = object_detector(snake_case_ , threshold=0.0 ) self.assertEqual(len(snake_case_ ) , len(snake_case_ ) ) for outputs in batch_outputs: self.assertGreater(len(snake_case_ ) , 0 ) for detected_object in outputs: self.assertEqual( snake_case_ , { 'score': ANY(snake_case_ ), 'label': ANY(snake_case_ ), 'box': {'xmin': ANY(snake_case_ ), 'ymin': ANY(snake_case_ ), 'xmax': ANY(snake_case_ ), 'ymax': ANY(snake_case_ )}, } , ) @require_tf @unittest.skip('Object detection not implemented in TF' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: pass @require_torch def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = 'hf-internal-testing/tiny-detr-mobilenetsv3' UpperCamelCase__ = AutoModelForObjectDetection.from_pretrained(snake_case_ ) UpperCamelCase__ = AutoFeatureExtractor.from_pretrained(snake_case_ ) UpperCamelCase__ = ObjectDetectionPipeline(model=snake_case_ , feature_extractor=snake_case_ ) UpperCamelCase__ = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' , threshold=0.0 ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'score': 0.3_376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3_376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ] , ) UpperCamelCase__ = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] , threshold=0.0 , ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {'score': 0.3_376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3_376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ], [ {'score': 0.3_376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3_376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ], ] , ) @require_torch @slow def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = 'facebook/detr-resnet-50' UpperCamelCase__ = AutoModelForObjectDetection.from_pretrained(snake_case_ ) UpperCamelCase__ = AutoFeatureExtractor.from_pretrained(snake_case_ ) UpperCamelCase__ = ObjectDetectionPipeline(model=snake_case_ , feature_extractor=snake_case_ ) UpperCamelCase__ = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'score': 0.9_982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9_960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9_955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9_988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9_987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] , ) UpperCamelCase__ = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {'score': 0.9_982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9_960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9_955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9_988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9_987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], [ {'score': 0.9_982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9_960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9_955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9_988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9_987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], ] , ) @require_torch @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = 'facebook/detr-resnet-50' UpperCamelCase__ = pipeline('object-detection' , model=snake_case_ ) UpperCamelCase__ = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'score': 0.9_982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9_960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9_955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9_988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9_987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] , ) UpperCamelCase__ = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ [ {'score': 0.9_982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9_960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9_955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9_988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9_987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], [ {'score': 0.9_982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9_960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9_955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9_988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9_987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], ] , ) @require_torch @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = 0.9_985 UpperCamelCase__ = 'facebook/detr-resnet-50' UpperCamelCase__ = pipeline('object-detection' , model=snake_case_ ) UpperCamelCase__ = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' , threshold=snake_case_ ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'score': 0.9_988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9_987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] , ) @require_torch @require_pytesseract @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = 'Narsil/layoutlmv3-finetuned-funsd' UpperCamelCase__ = 0.9_993 UpperCamelCase__ = pipeline('object-detection' , model=snake_case_ , threshold=snake_case_ ) UpperCamelCase__ = object_detector( 'https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png' ) self.assertEqual( nested_simplify(snake_case_ , decimals=4 ) , [ {'score': 0.9_993, 'label': 'I-ANSWER', 'box': {'xmin': 294, 'ymin': 254, 'xmax': 343, 'ymax': 264}}, {'score': 0.9_993, 'label': 'I-ANSWER', 'box': {'xmin': 294, 'ymin': 254, 'xmax': 343, 'ymax': 264}}, ] , )
20
"""simple docstring""" import sys from collections import defaultdict class __lowerCamelCase : def __init__( self ) -> Tuple: UpperCamelCase__ = [] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: return self.node_position[vertex] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Optional[int]: UpperCamelCase__ = pos def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: UpperCamelCase__ = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: UpperCamelCase__ = 2 * start + 1 else: UpperCamelCase__ = 2 * start + 2 if heap[smallest_child] < heap[start]: UpperCamelCase__ , UpperCamelCase__ = heap[smallest_child], positions[smallest_child] UpperCamelCase__ , UpperCamelCase__ = ( heap[start], positions[start], ) UpperCamelCase__ , UpperCamelCase__ = temp, tempa UpperCamelCase__ = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , snake_case_ ) self.top_to_bottom(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Any: UpperCamelCase__ = position[index] while index != 0: UpperCamelCase__ = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: UpperCamelCase__ = heap[parent] UpperCamelCase__ = position[parent] self.set_position(position[parent] , snake_case_ ) else: UpperCamelCase__ = val UpperCamelCase__ = temp self.set_position(snake_case_ , snake_case_ ) break UpperCamelCase__ = parent else: UpperCamelCase__ = val UpperCamelCase__ = temp self.set_position(snake_case_ , 0 ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Any: UpperCamelCase__ = len(snake_case_ ) // 2 - 1 for i in range(snake_case_ , -1 , -1 ): self.top_to_bottom(snake_case_ , snake_case_ , len(snake_case_ ) , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = positions[0] UpperCamelCase__ = sys.maxsize self.top_to_bottom(snake_case_ , 0 , len(snake_case_ ) , snake_case_ ) return temp def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = Heap() UpperCamelCase__ = [0] * len(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = [-1] * len(SCREAMING_SNAKE_CASE ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph UpperCamelCase__ = [] # Heap of Distance of vertices from their neighboring vertex UpperCamelCase__ = [] for vertex in range(len(SCREAMING_SNAKE_CASE ) ): distance_tv.append(sys.maxsize ) positions.append(SCREAMING_SNAKE_CASE ) heap.node_position.append(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = [] UpperCamelCase__ = 1 UpperCamelCase__ = sys.maxsize for neighbor, distance in adjacency_list[0]: UpperCamelCase__ = 0 UpperCamelCase__ = distance heap.heapify(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for _ in range(1 , len(SCREAMING_SNAKE_CASE ) ): UpperCamelCase__ = heap.delete_minimum(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) UpperCamelCase__ = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(SCREAMING_SNAKE_CASE )] ): UpperCamelCase__ = distance heap.bottom_to_top( SCREAMING_SNAKE_CASE , heap.get_position(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A__ : Dict= int(input("""Enter number of edges: """).strip()) A__ : Dict= defaultdict(list) for _ in range(edges_number): A__ : Dict= [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
20
1
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate A__ : Any= trt.Logger(trt.Logger.WARNING) A__ : Any= absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) A__ : Tuple= logging.getLogger(__name__) A__ : Optional[int]= argparse.ArgumentParser() # Required parameters parser.add_argument( """--onnx_model_path""", default=None, type=str, required=True, help="""Path to ONNX model: """, ) parser.add_argument( """--output_dir""", default=None, type=str, required=True, help="""The output directory where the model checkpoints and predictions will be written.""", ) # Other parameters parser.add_argument( """--tokenizer_name""", default="""""", type=str, required=True, help="""Pretrained tokenizer name or path if not the same as model_name""", ) parser.add_argument( """--version_2_with_negative""", action="""store_true""", help="""If true, the SQuAD examples contain some that do not have an answer.""", ) parser.add_argument( """--null_score_diff_threshold""", type=float, default=0.0, help="""If null_score - best_non_null is greater than the threshold predict null.""", ) parser.add_argument( """--max_seq_length""", default=3_84, type=int, help=( """The maximum total input sequence length after WordPiece tokenization. Sequences """ """longer than this will be truncated, and sequences shorter than this will be padded.""" ), ) parser.add_argument( """--doc_stride""", default=1_28, type=int, help="""When splitting up a long document into chunks, how much stride to take between chunks.""", ) parser.add_argument("""--per_device_eval_batch_size""", default=8, type=int, help="""Batch size per GPU/CPU for evaluation.""") parser.add_argument( """--n_best_size""", default=20, type=int, help="""The total number of n-best predictions to generate in the nbest_predictions.json output file.""", ) parser.add_argument( """--max_answer_length""", default=30, type=int, help=( """The maximum length of an answer that can be generated. This is needed because the start """ """and end predictions are not conditioned on one another.""" ), ) parser.add_argument("""--seed""", type=int, default=42, help="""random seed for initialization""") parser.add_argument( """--dataset_name""", type=str, default=None, required=True, help="""The name of the dataset to use (via the datasets library).""", ) parser.add_argument( """--dataset_config_name""", type=str, default=None, help="""The configuration name of the dataset to use (via the datasets library).""", ) parser.add_argument( """--preprocessing_num_workers""", type=int, default=4, help="""A csv or a json file containing the training data.""" ) parser.add_argument("""--overwrite_cache""", action="""store_true""", help="""Overwrite the cached training and evaluation sets""") parser.add_argument( """--fp16""", action="""store_true""", help="""Whether to use 16-bit (mixed) precision instead of 32-bit""", ) parser.add_argument( """--int8""", action="""store_true""", help="""Whether to use INT8""", ) A__ : Tuple= parser.parse_args() if args.tokenizer_name: A__ : Optional[Any]= AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported by this script.""" """You can do it from another script, save it, and load it from here, using --tokenizer_name.""" ) logger.info("""Training/evaluation parameters %s""", args) A__ : Dict= args.per_device_eval_batch_size A__ : Union[str, Any]= (args.eval_batch_size, args.max_seq_length) # TRT Engine properties A__ : List[Any]= True A__ : List[Any]= """temp_engine/bert-fp32.engine""" if args.fpaa: A__ : List[str]= """temp_engine/bert-fp16.engine""" if args.inta: A__ : Union[str, Any]= """temp_engine/bert-int8.engine""" # import ONNX file if not os.path.exists("""temp_engine"""): os.makedirs("""temp_engine""") A__ : Any= 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, """rb""") as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network A__ : Optional[int]= [network.get_input(i) for i in range(network.num_inputs)] A__ : List[str]= [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: A__ : str= 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) A__ : Union[str, Any]= builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) A__ : Optional[Any]= builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, """wb""") as f: f.write(engine.serialize()) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase__ = np.asarray(inputs['input_ids'] , dtype=np.intaa ) UpperCamelCase__ = np.asarray(inputs['attention_mask'] , dtype=np.intaa ) UpperCamelCase__ = np.asarray(inputs['token_type_ids'] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , SCREAMING_SNAKE_CASE ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , SCREAMING_SNAKE_CASE ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , SCREAMING_SNAKE_CASE ) # start time UpperCamelCase__ = time.time() # Run inference context.execute_async( bindings=[int(SCREAMING_SNAKE_CASE ) for d_inp in d_inputs] + [int(SCREAMING_SNAKE_CASE ), int(SCREAMING_SNAKE_CASE )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) cuda.memcpy_dtoh_async(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Synchronize the stream and take time stream.synchronize() # end time UpperCamelCase__ = time.time() UpperCamelCase__ = end_time - start_time UpperCamelCase__ = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. A__ : Optional[Any]= Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. A__ : Union[str, Any]= load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError("""Evaluation requires a dataset name""") # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. A__ : Optional[int]= raw_datasets["""validation"""].column_names A__ : str= """question""" if """question""" in column_names else column_names[0] A__ : List[Any]= """context""" if """context""" in column_names else column_names[1] A__ : Dict= """answers""" if """answers""" in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). A__ : List[str]= tokenizer.padding_side == """right""" if args.max_seq_length > tokenizer.model_max_length: logger.warning( F"""The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the""" F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) A__ : Union[str, Any]= min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase__ = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. UpperCamelCase__ = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='only_second' if pad_on_right else 'only_first' , max_length=SCREAMING_SNAKE_CASE , stride=args.doc_stride , return_overflowing_tokens=SCREAMING_SNAKE_CASE , return_offsets_mapping=SCREAMING_SNAKE_CASE , padding='max_length' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. UpperCamelCase__ = tokenized_examples.pop('overflow_to_sample_mapping' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. UpperCamelCase__ = [] for i in range(len(tokenized_examples['input_ids'] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). UpperCamelCase__ = tokenized_examples.sequence_ids(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. UpperCamelCase__ = sample_mapping[i] tokenized_examples["example_id"].append(examples['id'][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. UpperCamelCase__ = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['offset_mapping'][i] ) ] return tokenized_examples A__ : Optional[int]= raw_datasets["""validation"""] # Validation Feature Creation A__ : Optional[int]= eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc="""Running tokenizer on validation dataset""", ) A__ : List[str]= default_data_collator A__ : Union[str, Any]= eval_dataset.remove_columns(["""example_id""", """offset_mapping"""]) A__ : List[str]= DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE="eval" ) -> List[str]: """simple docstring""" UpperCamelCase__ = postprocess_qa_predictions( examples=SCREAMING_SNAKE_CASE , features=SCREAMING_SNAKE_CASE , predictions=SCREAMING_SNAKE_CASE , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=SCREAMING_SNAKE_CASE , ) # Format the result to the format the metric expects. if args.version_2_with_negative: UpperCamelCase__ = [ {'id': k, 'prediction_text': v, 'no_answer_probability': 0.0} for k, v in predictions.items() ] else: UpperCamelCase__ = [{'id': k, 'prediction_text': v} for k, v in predictions.items()] UpperCamelCase__ = [{'id': ex['id'], 'answers': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) A__ : List[Any]= load_metric("""squad_v2""" if args.version_2_with_negative else """squad""") # Evaluation! logger.info("""Loading ONNX model %s for evaluation""", args.onnx_model_path) with open(engine_name, """rb""") as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return trt.volume(engine.get_binding_shape(SCREAMING_SNAKE_CASE ) ) * engine.get_binding_dtype(SCREAMING_SNAKE_CASE ).itemsize # Allocate device memory for inputs and outputs. A__ : Union[str, Any]= [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer A__ : Union[str, Any]= cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) A__ : Union[str, Any]= cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) A__ : str= cuda.mem_alloc(h_outputa.nbytes) A__ : int= cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. A__ : Optional[int]= cuda.Stream() # Evaluation logger.info("""***** Running Evaluation *****""") logger.info(F""" Num examples = {len(eval_dataset)}""") logger.info(F""" Batch size = {args.per_device_eval_batch_size}""") A__ : str= 0.0 A__ : List[Any]= 0 A__ : Dict= timeit.default_timer() A__ : Union[str, Any]= None for step, batch in enumerate(eval_dataloader): A__, A__ : Dict= model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 A__, A__ : Union[str, Any]= outputs A__ : Union[str, Any]= torch.tensor(start_logits) A__ : Dict= torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered A__ : Any= accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) A__ : int= accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) A__ : int= (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) A__ : Dict= logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: A__ : Any= nested_truncate(all_preds, len(eval_dataset)) A__ : int= timeit.default_timer() - start_time logger.info(""" Evaluation done in total %f secs (%f sec per example)""", evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info("""Average Inference Time = {:.3f} ms""".format(total_time * 10_00 / niter)) logger.info("""Total Inference Time = {:.3f} ms""".format(total_time * 10_00)) logger.info("""Total Number of Inference = %d""", niter) A__ : Optional[int]= post_processing_function(eval_examples, eval_dataset, all_preds) A__ : int= metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(F"""Evaluation metrics: {eval_metric}""")
20
"""simple docstring""" from copy import deepcopy class __lowerCamelCase : def __init__( self , snake_case_ = None , snake_case_ = None ) -> None: if arr is None and size is not None: UpperCamelCase__ = size UpperCamelCase__ = [0] * size elif arr is not None: self.init(snake_case_ ) else: raise ValueError('Either arr or size must be specified' ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: UpperCamelCase__ = len(snake_case_ ) UpperCamelCase__ = deepcopy(snake_case_ ) for i in range(1 , self.size ): UpperCamelCase__ = self.next_(snake_case_ ) if j < self.size: self.tree[j] += self.tree[i] def SCREAMING_SNAKE_CASE__ ( self ) -> list[int]: UpperCamelCase__ = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): UpperCamelCase__ = self.next_(snake_case_ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: return index + (index & (-index)) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: return index - (index & (-index)) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value UpperCamelCase__ = self.next_(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: self.add(snake_case_ , value - self.get(snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: if right == 0: return 0 UpperCamelCase__ = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] UpperCamelCase__ = self.prev(snake_case_ ) return result def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> int: return self.prefix(snake_case_ ) - self.prefix(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: return self.query(snake_case_ , index + 1 ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: value -= self.tree[0] if value < 0: return -1 UpperCamelCase__ = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 UpperCamelCase__ = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
20
1
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 50 ) -> int: """simple docstring""" UpperCamelCase__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
20
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow A__ : Union[str, Any]= logging.getLogger() @unittest.skip("""Temporarily disable the doc tests.""" ) @require_torch @require_tf @slow class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = None , snake_case_ = None , snake_case_ = True , ) -> Tuple: UpperCamelCase__ = [file for file in os.listdir(snake_case_ ) if os.path.isfile(os.path.join(snake_case_ , snake_case_ ) )] if identifier is not None: UpperCamelCase__ = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(snake_case_ , snake_case_ ): for n_ in n_identifier: UpperCamelCase__ = [file for file in files if n_ not in file] else: UpperCamelCase__ = [file for file in files if n_identifier not in file] UpperCamelCase__ = ignore_files or [] ignore_files.append('__init__.py' ) UpperCamelCase__ = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' , snake_case_ ) if only_modules: UpperCamelCase__ = file.split('.' )[0] try: UpperCamelCase__ = getattr(snake_case_ , snake_case_ ) UpperCamelCase__ = doctest.DocTestSuite(snake_case_ ) UpperCamelCase__ = unittest.TextTestRunner().run(snake_case_ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'{module_identifier} is not a module.' ) else: UpperCamelCase__ = doctest.testfile(str('..' / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'modeling' UpperCamelCase__ = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(snake_case_ , identifier=snake_case_ , ignore_files=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'tokenization' self.analyze_directory(snake_case_ , identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'configuration' self.analyze_directory(snake_case_ , identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(snake_case_ , n_identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = Path('docs/source' ) UpperCamelCase__ = ['favicon.ico'] self.analyze_directory(snake_case_ , ignore_files=snake_case_ , only_modules=snake_case_ )
20
1
"""simple docstring""" # Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file A__ : Optional[Any]= """Run commands across TPU VMs for initial setup before running `accelerate launch`.""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> Dict: """simple docstring""" if subparsers is not None: UpperCamelCase__ = subparsers.add_parser('tpu-config' , description=_description ) else: UpperCamelCase__ = argparse.ArgumentParser('Accelerate tpu-config command' , description=_description ) # Core arguments UpperCamelCase__ = parser.add_argument_group( 'Config Arguments' , 'Arguments that can be configured through `accelerate config`.' ) config_args.add_argument( '--config_file' , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , help='Path to the config file to use for accelerate.' , ) config_args.add_argument( '--tpu_name' , default=SCREAMING_SNAKE_CASE , help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.' , ) config_args.add_argument( '--tpu_zone' , default=SCREAMING_SNAKE_CASE , help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.' , ) UpperCamelCase__ = parser.add_argument_group('TPU Arguments' , 'Arguments for options ran inside the TPU.' ) pod_args.add_argument( '--use_alpha' , action='store_true' , help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.' , ) pod_args.add_argument( '--command_file' , default=SCREAMING_SNAKE_CASE , help='The path to the file containing the commands to run on the pod on startup.' , ) pod_args.add_argument( '--command' , action='append' , nargs='+' , help='A command to run on the pod. Can be passed multiple times.' , ) pod_args.add_argument( '--install_accelerate' , action='store_true' , help='Whether to install accelerate on the pod. Defaults to False.' , ) pod_args.add_argument( '--accelerate_version' , default='latest' , help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.' , ) pod_args.add_argument( '--debug' , action='store_true' , help='If set, will print the command that would be run instead of running it.' ) if subparsers is not None: parser.set_defaults(func=SCREAMING_SNAKE_CASE ) return parser def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase__ = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: UpperCamelCase__ = defaults.command_file if not args.command and defaults.commands is not None: UpperCamelCase__ = defaults.commands if not args.tpu_name: UpperCamelCase__ = defaults.tpu_name if not args.tpu_zone: UpperCamelCase__ = defaults.tpu_zone if args.accelerate_version == "dev": UpperCamelCase__ = 'git+https://github.com/huggingface/accelerate.git' elif args.accelerate_version == "latest": UpperCamelCase__ = 'accelerate -U' elif isinstance(parse(args.accelerate_version ) , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = F'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError('You must specify either a command file or a command to run on the pod.' ) if args.command_file: with open(args.command_file , 'r' ) as f: UpperCamelCase__ = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate UpperCamelCase__ = ['cd /usr/share'] if args.install_accelerate: new_cmd += [F'pip install {args.accelerate_version}'] new_cmd += args.command UpperCamelCase__ = '; '.join(SCREAMING_SNAKE_CASE ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess UpperCamelCase__ = ['gcloud'] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'Running {" ".join(SCREAMING_SNAKE_CASE )}' ) return subprocess.run(SCREAMING_SNAKE_CASE ) print('Successfully setup pod.' ) def lowerCAmelCase_( ) -> int: """simple docstring""" UpperCamelCase__ = tpu_command_parser() UpperCamelCase__ = parser.parse_args() tpu_command_launcher(SCREAMING_SNAKE_CASE )
20
"""simple docstring""" import warnings 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 A__ : str= logging.get_logger(__name__) A__ : List[Any]= { """nvidia/segformer-b0-finetuned-ade-512-512""": ( """https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json""" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class __lowerCamelCase ( _a ): a : Any ="""segformer""" def __init__( self , snake_case_=3 , snake_case_=4 , snake_case_=[2, 2, 2, 2] , snake_case_=[8, 4, 2, 1] , snake_case_=[32, 64, 160, 256] , snake_case_=[7, 3, 3, 3] , snake_case_=[4, 2, 2, 2] , snake_case_=[1, 2, 5, 8] , snake_case_=[4, 4, 4, 4] , snake_case_="gelu" , snake_case_=0.0 , snake_case_=0.0 , snake_case_=0.1 , snake_case_=0.02 , snake_case_=0.1 , snake_case_=1E-6 , snake_case_=256 , snake_case_=255 , **snake_case_ , ) -> Tuple: super().__init__(**snake_case_ ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( 'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be' ' removed, as the behaviour will default to that of reshape_last_stage = True.' , snake_case_ , ) UpperCamelCase__ = num_channels UpperCamelCase__ = num_encoder_blocks UpperCamelCase__ = depths UpperCamelCase__ = sr_ratios UpperCamelCase__ = hidden_sizes UpperCamelCase__ = patch_sizes UpperCamelCase__ = strides UpperCamelCase__ = mlp_ratios UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = classifier_dropout_prob UpperCamelCase__ = initializer_range UpperCamelCase__ = drop_path_rate UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = decoder_hidden_size UpperCamelCase__ = kwargs.get('reshape_last_stage' , snake_case_ ) UpperCamelCase__ = semantic_loss_ignore_index class __lowerCamelCase ( _a ): a : Any =version.parse("""1.11""" ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: return 1E-4 @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: return 12
20
1
"""simple docstring""" import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters A__ : Tuple= (7_20, 12_80) # Height, Width A__ : Tuple= (0.4, 0.6) # if height or width lower than this scale, drop it. A__ : str= 1 / 1_00 A__ : int= """""" A__ : List[str]= """""" A__ : Optional[int]= """""" A__ : str= 2_50 def lowerCAmelCase_( ) -> None: """simple docstring""" UpperCamelCase__ , UpperCamelCase__ = get_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for index in range(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = random.sample(range(len(SCREAMING_SNAKE_CASE ) ) , 4 ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = update_image_and_anno( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , filter_scale=SCREAMING_SNAKE_CASE , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' UpperCamelCase__ = random_chars(32 ) UpperCamelCase__ = path.split(os.sep )[-1].rsplit('.' , 1 )[0] UpperCamelCase__ = F'{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}' cva.imwrite(F'{file_root}.jpg' , SCREAMING_SNAKE_CASE , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}' ) UpperCamelCase__ = [] for anno in new_annos: UpperCamelCase__ = anno[3] - anno[1] UpperCamelCase__ = anno[4] - anno[2] UpperCamelCase__ = anno[1] + width / 2 UpperCamelCase__ = anno[2] + height / 2 UpperCamelCase__ = F'{anno[0]} {x_center} {y_center} {width} {height}' annos_list.append(SCREAMING_SNAKE_CASE ) with open(F'{file_root}.txt' , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> tuple[list, list]: """simple docstring""" UpperCamelCase__ = [] UpperCamelCase__ = [] for label_file in glob.glob(os.path.join(SCREAMING_SNAKE_CASE , '*.txt' ) ): UpperCamelCase__ = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(SCREAMING_SNAKE_CASE ) as in_file: UpperCamelCase__ = in_file.readlines() UpperCamelCase__ = os.path.join(SCREAMING_SNAKE_CASE , F'{label_name}.jpg' ) UpperCamelCase__ = [] for obj_list in obj_lists: UpperCamelCase__ = obj_list.rstrip('\n' ).split(' ' ) UpperCamelCase__ = float(obj[1] ) - float(obj[3] ) / 2 UpperCamelCase__ = float(obj[2] ) - float(obj[4] ) / 2 UpperCamelCase__ = float(obj[1] ) + float(obj[3] ) / 2 UpperCamelCase__ = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(SCREAMING_SNAKE_CASE ) labels.append(SCREAMING_SNAKE_CASE ) return img_paths, labels def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 0.0 , ) -> tuple[list, list, str]: """simple docstring""" UpperCamelCase__ = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) UpperCamelCase__ = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) UpperCamelCase__ = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) UpperCamelCase__ = int(scale_x * output_size[1] ) UpperCamelCase__ = int(scale_y * output_size[0] ) UpperCamelCase__ = [] UpperCamelCase__ = [] for i, index in enumerate(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = all_img_list[index] path_list.append(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = all_annos[index] UpperCamelCase__ = cva.imread(SCREAMING_SNAKE_CASE ) if i == 0: # top-left UpperCamelCase__ = cva.resize(SCREAMING_SNAKE_CASE , (divid_point_x, divid_point_y) ) UpperCamelCase__ = img for bbox in img_annos: UpperCamelCase__ = bbox[1] * scale_x UpperCamelCase__ = bbox[2] * scale_y UpperCamelCase__ = bbox[3] * scale_x UpperCamelCase__ = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right UpperCamelCase__ = cva.resize(SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, divid_point_y) ) UpperCamelCase__ = img for bbox in img_annos: UpperCamelCase__ = scale_x + bbox[1] * (1 - scale_x) UpperCamelCase__ = bbox[2] * scale_y UpperCamelCase__ = scale_x + bbox[3] * (1 - scale_x) UpperCamelCase__ = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left UpperCamelCase__ = cva.resize(SCREAMING_SNAKE_CASE , (divid_point_x, output_size[0] - divid_point_y) ) UpperCamelCase__ = img for bbox in img_annos: UpperCamelCase__ = bbox[1] * scale_x UpperCamelCase__ = scale_y + bbox[2] * (1 - scale_y) UpperCamelCase__ = bbox[3] * scale_x UpperCamelCase__ = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right UpperCamelCase__ = cva.resize( SCREAMING_SNAKE_CASE , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) UpperCamelCase__ = img for bbox in img_annos: UpperCamelCase__ = scale_x + bbox[1] * (1 - scale_x) UpperCamelCase__ = scale_y + bbox[2] * (1 - scale_y) UpperCamelCase__ = scale_x + bbox[3] * (1 - scale_x) UpperCamelCase__ = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: UpperCamelCase__ = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" assert number_char > 1, "The number of character should greater than 1" UpperCamelCase__ = ascii_lowercase + digits return "".join(random.choice(SCREAMING_SNAKE_CASE ) for _ in range(SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": main() print("""DONE ✅""")
20
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class __lowerCamelCase ( _a ): @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: UpperCamelCase__ = parser.add_parser('download' ) download_parser.add_argument( '--cache-dir' , type=snake_case_ , default=snake_case_ , help='Path to location to store the models' ) download_parser.add_argument( '--force' , action='store_true' , help='Force the model to be download even if already in cache-dir' ) download_parser.add_argument( '--trust-remote-code' , action='store_true' , help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine' , ) download_parser.add_argument('model' , type=snake_case_ , help='Name of the model to download' ) download_parser.set_defaults(func=snake_case_ ) def __init__( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: UpperCamelCase__ = model UpperCamelCase__ = cache UpperCamelCase__ = force UpperCamelCase__ = trust_remote_code def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
20
1
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = (boundary[1] - boundary[0]) / steps UpperCamelCase__ = boundary[0] UpperCamelCase__ = boundary[1] UpperCamelCase__ = make_points(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ = 0.0 y += (h / 2.0) * f(SCREAMING_SNAKE_CASE ) for i in x_i: # print(i) y += h * f(SCREAMING_SNAKE_CASE ) y += (h / 2.0) * f(SCREAMING_SNAKE_CASE ) return y def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase__ = a + h while x < (b - h): yield x UpperCamelCase__ = x + h def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> str: # enter your function here """simple docstring""" UpperCamelCase__ = (x - 0) * (x - 0) return y def lowerCAmelCase_( ) -> Optional[int]: """simple docstring""" UpperCamelCase__ = 0.0 # Lower bound of integration UpperCamelCase__ = 1.0 # Upper bound of integration UpperCamelCase__ = 10.0 # define number of steps or resolution UpperCamelCase__ = [a, b] # define boundary of integration UpperCamelCase__ = method_a(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print(F'y = {y}' ) if __name__ == "__main__": main()
20
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCamelCase ( _a ): def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=False , snake_case_=True , snake_case_="None" , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> str: UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = relative_attention UpperCamelCase__ = position_biased_input UpperCamelCase__ = pos_att_type UpperCamelCase__ = scope def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Any: self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: UpperCamelCase__ = DebertaVaModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ )[0] UpperCamelCase__ = model(snake_case_ , token_type_ids=snake_case_ )[0] UpperCamelCase__ = model(snake_case_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: UpperCamelCase__ = DebertaVaForMaskedLM(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Dict: UpperCamelCase__ = self.num_labels UpperCamelCase__ = DebertaVaForSequenceClassification(snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[int]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = DebertaVaForTokenClassification(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = DebertaVaForQuestionAnswering(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , start_positions=snake_case_ , end_positions=snake_case_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = DebertaVaForMultipleChoice(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __lowerCamelCase ( _a , _a , unittest.TestCase ): a : Any =( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) a : Dict =( { """feature-extraction""": DebertaVaModel, """fill-mask""": DebertaVaForMaskedLM, """question-answering""": DebertaVaForQuestionAnswering, """text-classification""": DebertaVaForSequenceClassification, """token-classification""": DebertaVaForTokenClassification, """zero-shot""": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) a : Tuple =True a : Union[str, Any] =False a : Tuple =False a : Union[str, Any] =False a : Dict =False def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = DebertaVaModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = DebertaVaModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) @require_torch @require_sentencepiece @require_tokenizers class __lowerCamelCase ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: pass @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) UpperCamelCase__ = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) UpperCamelCase__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ )[0] # compare the actual values for a slice. UpperCamelCase__ = torch.tensor( [[[0.2_356, 0.1_948, 0.0_369], [-0.1_063, 0.3_586, -0.5_152], [-0.6_399, -0.0_259, -0.2_525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , snake_case_ , atol=1E-4 ) , F'{output[:, 1:4, 1:4]}' )
20
1
"""simple docstring""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[str]= logging.get_logger(__name__) A__ : List[str]= { """t5-small""": """https://huggingface.co/t5-small/resolve/main/config.json""", """t5-base""": """https://huggingface.co/t5-base/resolve/main/config.json""", """t5-large""": """https://huggingface.co/t5-large/resolve/main/config.json""", """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/config.json""", """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/config.json""", } class __lowerCamelCase ( _a ): a : Union[str, Any] ="""t5""" a : str =["""past_key_values"""] a : Dict ={"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self , snake_case_=3_2128 , snake_case_=512 , snake_case_=64 , snake_case_=2048 , snake_case_=6 , snake_case_=None , snake_case_=8 , snake_case_=32 , snake_case_=128 , snake_case_=0.1 , snake_case_=1E-6 , snake_case_=1.0 , snake_case_="relu" , snake_case_=True , snake_case_=True , snake_case_=0 , snake_case_=1 , **snake_case_ , ) -> List[str]: UpperCamelCase__ = vocab_size UpperCamelCase__ = d_model UpperCamelCase__ = d_kv UpperCamelCase__ = d_ff UpperCamelCase__ = num_layers UpperCamelCase__ = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry UpperCamelCase__ = num_heads UpperCamelCase__ = relative_attention_num_buckets UpperCamelCase__ = relative_attention_max_distance UpperCamelCase__ = dropout_rate UpperCamelCase__ = layer_norm_epsilon UpperCamelCase__ = initializer_factor UpperCamelCase__ = feed_forward_proj UpperCamelCase__ = use_cache UpperCamelCase__ = self.feed_forward_proj.split('-' ) UpperCamelCase__ = act_info[-1] UpperCamelCase__ = act_info[0] == 'gated' if len(snake_case_ ) > 1 and act_info[0] != "gated" or len(snake_case_ ) > 2: raise ValueError( F'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": UpperCamelCase__ = 'gelu_new' super().__init__( pad_token_id=snake_case_ , eos_token_id=snake_case_ , is_encoder_decoder=snake_case_ , **snake_case_ , ) class __lowerCamelCase ( _a ): @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: UpperCamelCase__ = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: UpperCamelCase__ = 'past_encoder_sequence + sequence' UpperCamelCase__ = {0: 'batch'} UpperCamelCase__ = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: UpperCamelCase__ = {0: 'batch', 1: 'decoder_sequence'} UpperCamelCase__ = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(snake_case_ , direction='inputs' ) return common_inputs @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: return 13
20
"""simple docstring""" 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 lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = SwinConfig() UpperCamelCase__ = swin_name.split('_' ) UpperCamelCase__ = name_split[1] UpperCamelCase__ = int(name_split[4] ) UpperCamelCase__ = int(name_split[3][-1] ) if model_size == "tiny": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 6, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "small": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "base": UpperCamelCase__ = 1_28 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (4, 8, 16, 32) else: UpperCamelCase__ = 1_92 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (6, 12, 24, 48) if "in22k" in swin_name: UpperCamelCase__ = 2_18_41 else: UpperCamelCase__ = 10_00 UpperCamelCase__ = 'huggingface/label-files' UpperCamelCase__ = 'imagenet-1k-id2label.json' UpperCamelCase__ = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) UpperCamelCase__ = {int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} UpperCamelCase__ = idalabel UpperCamelCase__ = {v: k for k, v in idalabel.items()} UpperCamelCase__ = img_size UpperCamelCase__ = num_classes UpperCamelCase__ = embed_dim UpperCamelCase__ = depths UpperCamelCase__ = num_heads UpperCamelCase__ = window_size return config def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" if "patch_embed.proj" in name: UpperCamelCase__ = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: UpperCamelCase__ = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: UpperCamelCase__ = 'encoder.' + name if "attn.proj" in name: UpperCamelCase__ = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: UpperCamelCase__ = name.replace('attn' , 'attention.self' ) if "norm1" in name: UpperCamelCase__ = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: UpperCamelCase__ = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: UpperCamelCase__ = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: UpperCamelCase__ = name.replace('mlp.fc2' , 'output.dense' ) if name == "norm.weight": UpperCamelCase__ = 'layernorm.weight' if name == "norm.bias": UpperCamelCase__ = 'layernorm.bias' if "head" in name: UpperCamelCase__ = name.replace('head' , 'classifier' ) else: UpperCamelCase__ = 'swin.' + name return name def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCamelCase__ = orig_state_dict.pop(SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: UpperCamelCase__ = key.split('.' ) UpperCamelCase__ = int(key_split[1] ) UpperCamelCase__ = int(key_split[3] ) UpperCamelCase__ = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: UpperCamelCase__ = val[:dim, :] UpperCamelCase__ = val[ dim : dim * 2, : ] UpperCamelCase__ = val[-dim:, :] else: UpperCamelCase__ = val[ :dim ] UpperCamelCase__ = val[ dim : dim * 2 ] UpperCamelCase__ = val[ -dim: ] else: UpperCamelCase__ = val return orig_state_dict def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = timm.create_model(SCREAMING_SNAKE_CASE , pretrained=SCREAMING_SNAKE_CASE ) timm_model.eval() UpperCamelCase__ = get_swin_config(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = SwinForImageClassification(SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase__ = convert_state_dict(timm_model.state_dict() , SCREAMING_SNAKE_CASE ) model.load_state_dict(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = 'http://images.cocodataset.org/val2017/000000039769.jpg' UpperCamelCase__ = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swin_name.replace('_' , '-' ) ) ) UpperCamelCase__ = Image.open(requests.get(SCREAMING_SNAKE_CASE , stream=SCREAMING_SNAKE_CASE ).raw ) UpperCamelCase__ = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='pt' ) UpperCamelCase__ = timm_model(inputs['pixel_values'] ) UpperCamelCase__ = 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__": A__ : Optional[Any]= 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.""" ) A__ : Tuple= parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
20
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = { 'task_specific_params': { 'summarization': {'length_penalty': 1.0, 'max_length': 128, 'min_length': 12, 'num_beams': 4}, 'summarization_cnn': {'length_penalty': 2.0, 'max_length': 142, 'min_length': 56, 'num_beams': 4}, 'summarization_xsum': {'length_penalty': 1.0, 'max_length': 62, 'min_length': 11, 'num_beams': 6}, } } UpperCamelCase__ = { 'task_specific_params.summarization.length_penalty': 1.0, 'task_specific_params.summarization.max_length': 128, 'task_specific_params.summarization.min_length': 12, 'task_specific_params.summarization.num_beams': 4, 'task_specific_params.summarization_cnn.length_penalty': 2.0, 'task_specific_params.summarization_cnn.max_length': 142, 'task_specific_params.summarization_cnn.min_length': 56, 'task_specific_params.summarization_cnn.num_beams': 4, 'task_specific_params.summarization_xsum.length_penalty': 1.0, 'task_specific_params.summarization_xsum.max_length': 62, 'task_specific_params.summarization_xsum.min_length': 11, 'task_specific_params.summarization_xsum.num_beams': 6, } self.assertEqual(flatten_dict(snake_case_ ) , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(snake_case_ ) , x.transpose() ) ) UpperCamelCase__ = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(snake_case_ , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = np.random.randn(3 , 4 ) UpperCamelCase__ = torch.tensor(snake_case_ ) self.assertTrue(np.allclose(transpose(snake_case_ ) , transpose(snake_case_ ).numpy() ) ) UpperCamelCase__ = np.random.randn(3 , 4 , 5 ) UpperCamelCase__ = torch.tensor(snake_case_ ) self.assertTrue(np.allclose(transpose(snake_case_ , axes=(1, 2, 0) ) , transpose(snake_case_ , axes=(1, 2, 0) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = np.random.randn(3 , 4 ) UpperCamelCase__ = tf.constant(snake_case_ ) self.assertTrue(np.allclose(transpose(snake_case_ ) , transpose(snake_case_ ).numpy() ) ) UpperCamelCase__ = np.random.randn(3 , 4 , 5 ) UpperCamelCase__ = tf.constant(snake_case_ ) self.assertTrue(np.allclose(transpose(snake_case_ , axes=(1, 2, 0) ) , transpose(snake_case_ , axes=(1, 2, 0) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = np.random.randn(3 , 4 ) UpperCamelCase__ = jnp.array(snake_case_ ) self.assertTrue(np.allclose(transpose(snake_case_ ) , np.asarray(transpose(snake_case_ ) ) ) ) UpperCamelCase__ = np.random.randn(3 , 4 , 5 ) UpperCamelCase__ = jnp.array(snake_case_ ) self.assertTrue(np.allclose(transpose(snake_case_ , axes=(1, 2, 0) ) , np.asarray(transpose(snake_case_ , axes=(1, 2, 0) ) ) ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(snake_case_ , (4, 3) ) , np.reshape(snake_case_ , (4, 3) ) ) ) UpperCamelCase__ = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(snake_case_ , (12, 5) ) , np.reshape(snake_case_ , (12, 5) ) ) ) @require_torch def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = np.random.randn(3 , 4 ) UpperCamelCase__ = torch.tensor(snake_case_ ) self.assertTrue(np.allclose(reshape(snake_case_ , (4, 3) ) , reshape(snake_case_ , (4, 3) ).numpy() ) ) UpperCamelCase__ = np.random.randn(3 , 4 , 5 ) UpperCamelCase__ = torch.tensor(snake_case_ ) self.assertTrue(np.allclose(reshape(snake_case_ , (12, 5) ) , reshape(snake_case_ , (12, 5) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = np.random.randn(3 , 4 ) UpperCamelCase__ = tf.constant(snake_case_ ) self.assertTrue(np.allclose(reshape(snake_case_ , (4, 3) ) , reshape(snake_case_ , (4, 3) ).numpy() ) ) UpperCamelCase__ = np.random.randn(3 , 4 , 5 ) UpperCamelCase__ = tf.constant(snake_case_ ) self.assertTrue(np.allclose(reshape(snake_case_ , (12, 5) ) , reshape(snake_case_ , (12, 5) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = np.random.randn(3 , 4 ) UpperCamelCase__ = jnp.array(snake_case_ ) self.assertTrue(np.allclose(reshape(snake_case_ , (4, 3) ) , np.asarray(reshape(snake_case_ , (4, 3) ) ) ) ) UpperCamelCase__ = np.random.randn(3 , 4 , 5 ) UpperCamelCase__ = jnp.array(snake_case_ ) self.assertTrue(np.allclose(reshape(snake_case_ , (12, 5) ) , np.asarray(reshape(snake_case_ , (12, 5) ) ) ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(snake_case_ ) , np.squeeze(snake_case_ ) ) ) UpperCamelCase__ = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(snake_case_ , axis=2 ) , np.squeeze(snake_case_ , axis=2 ) ) ) @require_torch def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = np.random.randn(1 , 3 , 4 ) UpperCamelCase__ = torch.tensor(snake_case_ ) self.assertTrue(np.allclose(squeeze(snake_case_ ) , squeeze(snake_case_ ).numpy() ) ) UpperCamelCase__ = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase__ = torch.tensor(snake_case_ ) self.assertTrue(np.allclose(squeeze(snake_case_ , axis=2 ) , squeeze(snake_case_ , axis=2 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ = np.random.randn(1 , 3 , 4 ) UpperCamelCase__ = tf.constant(snake_case_ ) self.assertTrue(np.allclose(squeeze(snake_case_ ) , squeeze(snake_case_ ).numpy() ) ) UpperCamelCase__ = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase__ = tf.constant(snake_case_ ) self.assertTrue(np.allclose(squeeze(snake_case_ , axis=2 ) , squeeze(snake_case_ , axis=2 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = np.random.randn(1 , 3 , 4 ) UpperCamelCase__ = jnp.array(snake_case_ ) self.assertTrue(np.allclose(squeeze(snake_case_ ) , np.asarray(squeeze(snake_case_ ) ) ) ) UpperCamelCase__ = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase__ = jnp.array(snake_case_ ) self.assertTrue(np.allclose(squeeze(snake_case_ , axis=2 ) , np.asarray(squeeze(snake_case_ , axis=2 ) ) ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(snake_case_ , axis=1 ) , np.expand_dims(snake_case_ , axis=1 ) ) ) @require_torch def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = np.random.randn(3 , 4 ) UpperCamelCase__ = torch.tensor(snake_case_ ) self.assertTrue(np.allclose(expand_dims(snake_case_ , axis=1 ) , expand_dims(snake_case_ , axis=1 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = np.random.randn(3 , 4 ) UpperCamelCase__ = tf.constant(snake_case_ ) self.assertTrue(np.allclose(expand_dims(snake_case_ , axis=1 ) , expand_dims(snake_case_ , axis=1 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = np.random.randn(3 , 4 ) UpperCamelCase__ = jnp.array(snake_case_ ) self.assertTrue(np.allclose(expand_dims(snake_case_ , axis=1 ) , np.asarray(expand_dims(snake_case_ , axis=1 ) ) ) )
20
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" UpperCamelCase__ = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 50_00 ) -> int: """simple docstring""" UpperCamelCase__ = [(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 ) ): UpperCamelCase__ = pentagonal_nums[j] UpperCamelCase__ = pentagonal_i + pentagonal_j UpperCamelCase__ = 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() = }""")
20
1
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> float: """simple docstring""" _validate_point(SCREAMING_SNAKE_CASE_ ) _validate_point(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError('Both points must be in the same n-dimensional space' ) return float(sum(abs(a - b ) for a, b in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" if point: if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): for item in point: if not isinstance(SCREAMING_SNAKE_CASE_ , (int, float) ): UpperCamelCase__ = ( 'Expected a list of numbers as input, found ' F'{type(SCREAMING_SNAKE_CASE_ ).__name__}' ) raise TypeError(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase__ = F'Expected a list of numbers as input, found {type(SCREAMING_SNAKE_CASE_ ).__name__}' raise TypeError(SCREAMING_SNAKE_CASE_ ) else: raise ValueError('Missing an input' ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> float: """simple docstring""" _validate_point(SCREAMING_SNAKE_CASE_ ) _validate_point(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError('Both points must be in the same n-dimensional space' ) return float(sum(abs(x - y ) for x, y in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
700
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 50_00_00_00 ) -> int: """simple docstring""" UpperCamelCase__ = set() UpperCamelCase__ = int((limit - 24) ** (1 / 2) ) UpperCamelCase__ = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , SCREAMING_SNAKE_CASE ) ) ) for primea in primes: UpperCamelCase__ = primea * primea for primea in primes: UpperCamelCase__ = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: UpperCamelCase__ = primea * primea * primea * primea UpperCamelCase__ = square + cube + tetr if total >= limit: break ret.add(SCREAMING_SNAKE_CASE ) return len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(F"""{solution() = }""")
20
0
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path A__ : Tuple= ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) A__ : Union[str, Any]= [ord(letter) for letter in string.ascii_lowercase] A__ : List[str]= {ord(char) for char in VALID_CHARS} A__ : Dict= ["""the""", """be""", """to""", """of""", """and""", """in""", """that""", """have"""] def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase__ = '' UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = 42 for keychar, cipherchar in zip(cycle(__A ) , __A ): UpperCamelCase__ = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(__A ) return decoded def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" UpperCamelCase__ = [] for key in product(__A , repeat=3 ): UpperCamelCase__ = try_key(__A , __A ) if encoded is not None: possibles.append(__A ) return possibles def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" return [possible for possible in possibles if common_word in possible.lower()] def lowerCAmelCase_( SCREAMING_SNAKE_CASE = "p059_cipher.txt" ) -> Optional[Any]: """simple docstring""" UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = Path(__A ).parent.joinpath(__A ).read_text(encoding='utf-8' ) UpperCamelCase__ = [int(__A ) for number in data.strip().split(',' )] UpperCamelCase__ = filter_valid_chars(__A ) for common_word in COMMON_WORDS: UpperCamelCase__ = filter_common_word(__A , __A ) if len(__A ) == 1: break UpperCamelCase__ = possibles[0] return sum(ord(__A ) for char in decoded_text ) if __name__ == "__main__": print(F"""{solution() = }""")
701
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer A__ : List[Any]= ["""bert-base-uncased""", """bert-base-cased"""] A__ : Optional[int]= """hf-internal-testing/tiny-bert-tf-only""" if is_tf_available(): class __lowerCamelCase ( tf.keras.Model ): def __init__( self , snake_case_ ) -> Optional[int]: super().__init__() UpperCamelCase__ = tokenizer UpperCamelCase__ = AutoConfig.from_pretrained(snake_case_ ) UpperCamelCase__ = TFAutoModel.from_config(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: UpperCamelCase__ = self.tokenizer(snake_case_ ) UpperCamelCase__ = self.bert(**snake_case_ ) return out["pooler_output"] @require_tf @require_tensorflow_text class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ) -> str: super().setUp() UpperCamelCase__ = [ BertTokenizer.from_pretrained(snake_case_ ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false UpperCamelCase__ = [TFBertTokenizer.from_pretrained(snake_case_ ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(snake_case_ , use_fast_bert_tokenizer=snake_case_ ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCamelCase__ = [ 'This is a straightforward English test sentence.', 'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.', 'Now we\'re going to add some Chinese: 一 二 三 一二三', 'And some much more rare Chinese: 齉 堃 齉堃', 'Je vais aussi écrire en français pour tester les accents', 'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ', ] UpperCamelCase__ = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase__ = tokenizer(snake_case_ , return_tensors='tf' , padding='longest' ) UpperCamelCase__ = tf_tokenizer(snake_case_ ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> str: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = tf_tokenizer(self.paired_sentences ) UpperCamelCase__ = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = tf.function(snake_case_ ) for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase__ = tf.constant(snake_case_ ) UpperCamelCase__ = compiled_tokenizer(snake_case_ ) UpperCamelCase__ = tf_tokenizer(snake_case_ ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = ModelToSave(tokenizer=snake_case_ ) UpperCamelCase__ = tf.convert_to_tensor(self.test_sentences ) UpperCamelCase__ = model(snake_case_ ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCamelCase__ = Path(snake_case_ ) / 'saved.model' model.save(snake_case_ ) UpperCamelCase__ = tf.keras.models.load_model(snake_case_ ) UpperCamelCase__ = loaded_model(snake_case_ ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
20
0
"""simple docstring""" import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, 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 ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class __lowerCamelCase ( snake_case__ ): def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=False , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> Any: UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = DistilBertModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase__ = model(UpperCAmelCase_ , UpperCAmelCase_ ) UpperCamelCase__ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = DistilBertForMaskedLM(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase__ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: UpperCamelCase__ = DistilBertForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase__ = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Dict: UpperCamelCase__ = self.num_labels UpperCamelCase__ = DistilBertForSequenceClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase__ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Dict: UpperCamelCase__ = self.num_labels UpperCamelCase__ = DistilBertForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase__ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = self.num_choices UpperCamelCase__ = DistilBertForMultipleChoice(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.prepare_config_and_inputs() ((UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__)) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __lowerCamelCase ( snake_case__ , snake_case__ , unittest.TestCase ): a : str =( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) a : Tuple =( { """feature-extraction""": DistilBertModel, """fill-mask""": DistilBertForMaskedLM, """question-answering""": DistilBertForQuestionAnswering, """text-classification""": DistilBertForSequenceClassification, """token-classification""": DistilBertForTokenClassification, """zero-shot""": DistilBertForSequenceClassification, } if is_torch_available() else {} ) a : List[str] =True a : Tuple =True a : Dict =True a : Union[str, Any] =True def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ = DistilBertModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=UpperCAmelCase_ , dim=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCAmelCase_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = DistilBertModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @slow @require_torch_gpu def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return UpperCamelCase__ = True UpperCamelCase__ = model_class(config=UpperCAmelCase_ ) UpperCamelCase__ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) UpperCamelCase__ = torch.jit.trace( UpperCAmelCase_ , (inputs_dict['input_ids'].to('cpu' ), inputs_dict['attention_mask'].to('cpu' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCAmelCase_ , os.path.join(UpperCAmelCase_ , 'traced_model.pt' ) ) UpperCamelCase__ = torch.jit.load(os.path.join(UpperCAmelCase_ , 'traced_model.pt' ) , map_location=UpperCAmelCase_ ) loaded(inputs_dict['input_ids'].to(UpperCAmelCase_ ) , inputs_dict['attention_mask'].to(UpperCAmelCase_ ) ) @require_torch class __lowerCamelCase ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = DistilBertModel.from_pretrained('distilbert-base-uncased' ) UpperCamelCase__ = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) UpperCamelCase__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCamelCase__ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ )[0] UpperCamelCase__ = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , UpperCAmelCase_ ) UpperCamelCase__ = torch.tensor( [[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase_ , atol=1E-4 ) )
702
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> list[int]: """simple docstring""" UpperCamelCase__ = len(SCREAMING_SNAKE_CASE ) for i in range(SCREAMING_SNAKE_CASE ): for j in range(i + 1 , SCREAMING_SNAKE_CASE ): if numbers[j] < numbers[i]: UpperCamelCase__ , UpperCamelCase__ = numbers[j], numbers[i] return numbers if __name__ == "__main__": A__ : Union[str, Any]= input("""Enter numbers separated by a comma:\n""").strip() A__ : List[Any]= [int(item) for item in user_input.split(""",""")] print(exchange_sort(unsorted))
20
0
"""simple docstring""" A__ : List[Any]= range(2, 20 + 1) A__ : List[str]= [10**k for k in range(ks[-1] + 1)] A__ : dict[int, dict[int, list[list[int]]]]= {} def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" UpperCamelCase__ = sum(a_i[j] for j in range(SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) ) UpperCamelCase__ = sum(a_i[j] * base[j] for j in range(min(len(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) ) ) UpperCamelCase__ , UpperCamelCase__ = 0, 0 UpperCamelCase__ = n - i UpperCamelCase__ = memo.get(SCREAMING_SNAKE_CASE ) if sub_memo is not None: UpperCamelCase__ = sub_memo.get(SCREAMING_SNAKE_CASE ) if jumps is not None and len(SCREAMING_SNAKE_CASE ) > 0: # find and make the largest jump without going over UpperCamelCase__ = -1 for _k in range(len(SCREAMING_SNAKE_CASE ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: UpperCamelCase__ = _k break if max_jump >= 0: UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = jumps[max_jump] # since the difference between jumps is cached, add c UpperCamelCase__ = diff + c for j in range(min(SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) ): UpperCamelCase__ , UpperCamelCase__ = divmod(SCREAMING_SNAKE_CASE , 10 ) if new_c > 0: add(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: UpperCamelCase__ = [] else: UpperCamelCase__ = {c: []} UpperCamelCase__ = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps UpperCamelCase__ , UpperCamelCase__ = next_term(SCREAMING_SNAKE_CASE , k - 1 , i + dn , SCREAMING_SNAKE_CASE ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead UpperCamelCase__ , UpperCamelCase__ = compute(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , i + dn , SCREAMING_SNAKE_CASE ) diff += _diff dn += terms_jumped UpperCamelCase__ = sub_memo[c] # keep jumps sorted by # of terms skipped UpperCamelCase__ = 0 while j < len(SCREAMING_SNAKE_CASE ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(SCREAMING_SNAKE_CASE , (diff, dn, k) ) return (diff, dn) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if i >= n: return 0, i if k > len(SCREAMING_SNAKE_CASE ): a_i.extend([0 for _ in range(k - len(SCREAMING_SNAKE_CASE ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) UpperCamelCase__ = i UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = 0, 0, 0 for j in range(len(SCREAMING_SNAKE_CASE ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 UpperCamelCase__ = ds_c + ds_b diff += addend UpperCamelCase__ = 0 for j in range(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = a_i[j] + addend UpperCamelCase__ , UpperCamelCase__ = divmod(SCREAMING_SNAKE_CASE , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return diff, i - start_i def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" for j in range(SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ): UpperCamelCase__ = digits[j] + addend if s >= 10: UpperCamelCase__ , UpperCamelCase__ = divmod(SCREAMING_SNAKE_CASE , 10 ) UpperCamelCase__ = addend // 10 + quotient else: UpperCamelCase__ = s UpperCamelCase__ = addend // 10 if addend == 0: break while addend > 0: UpperCamelCase__ , UpperCamelCase__ = divmod(SCREAMING_SNAKE_CASE , 10 ) digits.append(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 10**15 ) -> int: """simple docstring""" UpperCamelCase__ = [1] UpperCamelCase__ = 1 UpperCamelCase__ = 0 while True: UpperCamelCase__ , UpperCamelCase__ = next_term(SCREAMING_SNAKE_CASE , 20 , i + dn , SCREAMING_SNAKE_CASE ) dn += terms_jumped if dn == n - i: break UpperCamelCase__ = 0 for j in range(len(SCREAMING_SNAKE_CASE ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(F"""{solution() = }""")
703
"""simple docstring""" import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("""9.1.0"""): A__ : str= { """linear""": PIL.Image.Resampling.BILINEAR, """bilinear""": PIL.Image.Resampling.BILINEAR, """bicubic""": PIL.Image.Resampling.BICUBIC, """lanczos""": PIL.Image.Resampling.LANCZOS, """nearest""": PIL.Image.Resampling.NEAREST, } else: A__ : str= { """linear""": PIL.Image.LINEAR, """bilinear""": PIL.Image.BILINEAR, """bicubic""": PIL.Image.BICUBIC, """lanczos""": PIL.Image.LANCZOS, """nearest""": PIL.Image.NEAREST, } def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = (images / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() UpperCamelCase__ = numpy_to_pil(SCREAMING_SNAKE_CASE ) return images def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if images.ndim == 3: UpperCamelCase__ = images[None, ...] UpperCamelCase__ = (images * 2_55).round().astype('uint8' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images UpperCamelCase__ = [Image.fromarray(image.squeeze() , mode='L' ) for image in images] else: UpperCamelCase__ = [Image.fromarray(SCREAMING_SNAKE_CASE ) for image in images] return pil_images
20
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_lxmert import LxmertTokenizer A__ : str= {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : str= { '''vocab_file''': { '''unc-nlp/lxmert-base-uncased''': '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/vocab.txt''', }, '''tokenizer_file''': { '''unc-nlp/lxmert-base-uncased''': ( '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/tokenizer.json''' ), }, } A__ : Any= { '''unc-nlp/lxmert-base-uncased''': 5_12, } A__ : List[str]= { '''unc-nlp/lxmert-base-uncased''': {'''do_lower_case''': True}, } class __lowerCamelCase ( _a ): a : List[Any] =VOCAB_FILES_NAMES a : Optional[Any] =PRETRAINED_VOCAB_FILES_MAP a : Optional[int] =PRETRAINED_INIT_CONFIGURATION a : Optional[int] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : Union[str, Any] =LxmertTokenizer def __init__( self , snake_case_=None , snake_case_=None , snake_case_=True , snake_case_="[UNK]" , snake_case_="[SEP]" , snake_case_="[PAD]" , snake_case_="[CLS]" , snake_case_="[MASK]" , snake_case_=True , snake_case_=None , **snake_case_ , ) -> Optional[int]: super().__init__( UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , do_lower_case=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , tokenize_chinese_chars=UpperCamelCase_ , strip_accents=UpperCamelCase_ , **UpperCamelCase_ , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , UpperCamelCase_ ) != do_lower_case or normalizer_state.get('strip_accents' , UpperCamelCase_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , UpperCamelCase_ ) != tokenize_chinese_chars ): UpperCamelCase__ = getattr(UpperCamelCase_ , normalizer_state.pop('type' ) ) UpperCamelCase__ = do_lower_case UpperCamelCase__ = strip_accents UpperCamelCase__ = tokenize_chinese_chars UpperCamelCase__ = normalizer_class(**UpperCamelCase_ ) UpperCamelCase__ = do_lower_case def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_=None ) -> Optional[Any]: UpperCamelCase__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [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 , snake_case_ , snake_case_ = None ) -> Tuple[str]: UpperCamelCase__ = self._tokenizer.model.save(UpperCamelCase_ , name=UpperCamelCase_ ) return tuple(UpperCamelCase_ )
704
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging A__ : Dict= logging.get_logger(__name__) A__ : str= {"""vocab_file""": """spiece.model"""} A__ : Union[str, Any]= { """vocab_file""": { """t5-small""": """https://huggingface.co/t5-small/resolve/main/spiece.model""", """t5-base""": """https://huggingface.co/t5-base/resolve/main/spiece.model""", """t5-large""": """https://huggingface.co/t5-large/resolve/main/spiece.model""", """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/spiece.model""", """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/spiece.model""", } } # TODO(PVP) - this should be removed in Transformers v5 A__ : Union[str, Any]= { """t5-small""": 5_12, """t5-base""": 5_12, """t5-large""": 5_12, """t5-3b""": 5_12, """t5-11b""": 5_12, } A__ : Optional[Any]= """▁""" class __lowerCamelCase ( _a ): a : Dict =VOCAB_FILES_NAMES a : str =PRETRAINED_VOCAB_FILES_MAP a : Union[str, Any] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : List[str] =["""input_ids""", """attention_mask"""] def __init__( self , snake_case_ , snake_case_="</s>" , snake_case_="<unk>" , snake_case_="<pad>" , snake_case_=100 , snake_case_=None , snake_case_ = None , snake_case_=True , **snake_case_ , ) -> None: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: UpperCamelCase__ = [F'<extra_id_{i}>' for i in range(snake_case_ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens UpperCamelCase__ = len(set(filter(lambda snake_case_ : bool('extra_id' in str(snake_case_ ) ) , snake_case_ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' ' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids' ' tokens' ) if legacy: logger.warning_once( F'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to' ' read the related pull request available at https://github.com/huggingface/transformers/pull/24565' ) UpperCamelCase__ = legacy UpperCamelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=snake_case_ , unk_token=snake_case_ , pad_token=snake_case_ , extra_ids=snake_case_ , additional_special_tokens=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , legacy=snake_case_ , **snake_case_ , ) UpperCamelCase__ = vocab_file UpperCamelCase__ = extra_ids UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: UpperCamelCase__ = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( 'This tokenizer was incorrectly instantiated with a model max length of' F' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' ' behavior is kept to avoid breaking backwards compatibility when padding/encoding with' ' `truncation is True`.\n- Be aware that you SHOULD NOT rely on' F' {pretrained_model_name_or_path} automatically truncating your input to' F' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' F' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' ' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please' ' instantiate this tokenizer with `model_max_length` set to your preferred value.' , snake_case_ , ) return max_model_length @property def SCREAMING_SNAKE_CASE__ ( self ) -> Any: return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = {self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case_ , token_ids_a=snake_case_ , already_has_special_tokens=snake_case_ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(snake_case_ )) + [1] return ([0] * len(snake_case_ )) + [1] + ([0] * len(snake_case_ )) + [1] def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return list( set(filter(lambda snake_case_ : bool(re.search(r'<extra_id_\d+>' , snake_case_ ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: return [self._convert_token_to_id(snake_case_ ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[int]: if len(snake_case_ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' ' eos tokens being added.' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = self._add_eos_if_not_present(snake_case_ ) if token_ids_a is None: return token_ids_a else: UpperCamelCase__ = self._add_eos_if_not_present(snake_case_ ) return token_ids_a + token_ids_a def __getstate__( self ) -> str: UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = None return state def __setstate__( self , snake_case_ ) -> Any: UpperCamelCase__ = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): UpperCamelCase__ = {} UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , **snake_case_ ) -> List[str]: # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: UpperCamelCase__ = SPIECE_UNDERLINE + text.replace(snake_case_ , ' ' ) return super().tokenize(snake_case_ , **snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , **snake_case_ ) -> List[Any]: if not self.legacy: UpperCamelCase__ = text.startswith(snake_case_ ) if is_first: UpperCamelCase__ = text[1:] UpperCamelCase__ = self.sp_model.encode(snake_case_ , out_type=snake_case_ ) if not self.legacy and not is_first and not text.startswith(' ' ) and tokens[0].startswith(snake_case_ ): UpperCamelCase__ = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: if token.startswith('<extra_id_' ): UpperCamelCase__ = re.match(r'<extra_id_(\d+)>' , snake_case_ ) UpperCamelCase__ = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Optional[int]: if index < self.sp_model.get_piece_size(): UpperCamelCase__ = self.sp_model.IdToPiece(snake_case_ ) else: UpperCamelCase__ = F'<extra_id_{self.vocab_size - 1 - index}>' return token def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: UpperCamelCase__ = [] UpperCamelCase__ = '' UpperCamelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(snake_case_ ) + token UpperCamelCase__ = True UpperCamelCase__ = [] else: current_sub_tokens.append(snake_case_ ) UpperCamelCase__ = False out_string += self.sp_model.decode(snake_case_ ) return out_string.strip() def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> Tuple[str]: if not os.path.isdir(snake_case_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase__ = os.path.join( snake_case_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case_ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case_ , 'wb' ) as fi: UpperCamelCase__ = self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,)
20
0
"""simple docstring""" import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin A__ : Optional[Any]= get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece class __lowerCamelCase ( lowercase__ , unittest.TestCase ): a : Optional[int] =XLMProphetNetTokenizer a : Union[str, Any] =False a : List[str] =True def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing UpperCamelCase__ = XLMProphetNetTokenizer(__lowerCamelCase , keep_accents=__lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = "[PAD]" UpperCamelCase__ = 0 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 ) -> Tuple: UpperCamelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '[PAD]' ) self.assertEqual(vocab_keys[1] , '[CLS]' ) self.assertEqual(vocab_keys[-1] , 'j' ) self.assertEqual(len(__lowerCamelCase ) , 1012 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: self.assertEqual(self.get_tokenizer().vocab_size , 1012 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = XLMProphetNetTokenizer(__lowerCamelCase , keep_accents=__lowerCamelCase ) UpperCamelCase__ = tokenizer.tokenize('This is a test' ) self.assertListEqual(__lowerCamelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) UpperCamelCase__ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __lowerCamelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) UpperCamelCase__ = tokenizer.convert_tokens_to_ids(__lowerCamelCase ) self.assertListEqual( __lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(__lowerCamelCase ) self.assertListEqual( __lowerCamelCase , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '[UNK]', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '[UNK]', '.', ] , ) @cached_property def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: return XLMProphetNetTokenizer.from_pretrained('microsoft/xprophetnet-large-wiki100-cased' ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = "Hello World!" UpperCamelCase__ = [3_5389, 6672, 49, 2] self.assertListEqual(__lowerCamelCase , self.big_tokenizer.encode(__lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = {"input_ids": [[1_1073, 8_2783, 18, 26, 8_2783, 549, 5_1540, 248, 1_7209, 1301, 217, 20, 21_5186, 1325, 147, 1_7209, 1301, 217, 20, 5_6370, 53, 12_2020, 20, 1_6477, 27, 8_7355, 4548, 20, 4728, 7_8392, 17, 15_9969, 18, 26, 2_4491, 629, 15, 538, 2_2704, 5439, 15, 2788, 2_4491, 9885, 15, 4_3534, 605, 15, 814, 1_8403, 3_3200, 29, 15, 4_3534, 2_4458, 1_2410, 111, 2_4966, 8_3669, 9637, 14_4068, 26, 850, 2_2346, 27, 147, 2_4966, 8_3669, 8_3490, 26, 3_9113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 12_2020, 11_5785, 34, 816, 1339, 4_6887, 18, 147, 5_3905, 1951, 4_2238, 4_1170, 1_7732, 834, 436, 15, 2_7523, 9_8733, 217, 147, 5542, 4981, 930, 1_7347, 16, 2], [2_0091, 629, 94, 8_2786, 58, 490, 20, 1528, 84, 5_3905, 344, 8_0592, 11_0128, 1_8822, 5267, 1306, 62, 15_2537, 308, 7997, 401, 12_4427, 549, 3_5442, 225, 109, 1_5055, 2_5748, 147, 7119, 4_3712, 34, 767, 13_5366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 6_3784, 11_9466, 17, 14_7808, 8_8214, 18, 656, 81, 32, 3296, 1_0280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowerCamelCase , model_name='microsoft/xprophetnet-large-wiki100-cased' , revision='1acad1643ddd54a44df6a1b797ada8373685d90e' , )
705
"""simple docstring""" from __future__ import annotations from typing import Generic, TypeVar A__ : Any= TypeVar("""T""") class __lowerCamelCase ( Generic[T] ): def __init__( self , snake_case_ ) -> None: UpperCamelCase__ = data UpperCamelCase__ = self UpperCamelCase__ = 0 class __lowerCamelCase ( Generic[T] ): def __init__( self ) -> None: # map from node name to the node object UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: # create a new set with x as its member UpperCamelCase__ = DisjointSetTreeNode(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> DisjointSetTreeNode[T]: # find the set x belongs to (with path-compression) UpperCamelCase__ = self.map[data] if elem_ref != elem_ref.parent: UpperCamelCase__ = self.find_set(elem_ref.parent.data ) return elem_ref.parent def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: # helper function for union operation if nodea.rank > nodea.rank: UpperCamelCase__ = nodea else: UpperCamelCase__ = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: # merge 2 disjoint sets self.link(self.find_set(snake_case_ ) , self.find_set(snake_case_ ) ) class __lowerCamelCase ( Generic[T] ): def __init__( self ) -> None: # connections: map from the node to the neighbouring nodes (with weights) UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: # add a node ONLY if its not present in the graph if node not in self.connections: UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> None: # add an edge with the given weight self.add_node(snake_case_ ) self.add_node(snake_case_ ) UpperCamelCase__ = weight UpperCamelCase__ = weight def SCREAMING_SNAKE_CASE__ ( self ) -> GraphUndirectedWeighted[T]: UpperCamelCase__ = [] UpperCamelCase__ = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda snake_case_ : x[2] ) # creating the disjoint set UpperCamelCase__ = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(snake_case_ ) # MST generation UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = edges[index] index += 1 UpperCamelCase__ = disjoint_set.find_set(snake_case_ ) UpperCamelCase__ = disjoint_set.find_set(snake_case_ ) if parent_u != parent_v: num_edges += 1 graph.add_edge(snake_case_ , snake_case_ , snake_case_ ) disjoint_set.union(snake_case_ , snake_case_ ) return graph
20
0
"""simple docstring""" import inspect import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed import accelerate from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, require_cuda, require_fsdp, require_multi_gpu, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) A__ : Dict= """bert-base-cased""" A__ : Any= """fp16""" A__ : Union[str, Any]= """bf16""" A__ : List[Any]= [FPaa, BFaa] @require_fsdp @require_cuda class __lowerCamelCase ( __lowerCamelCase ): def SCREAMING_SNAKE_CASE__ ( self ) -> str: '''simple docstring''' super().setUp() UpperCamelCase__ = dict( ACCELERATE_USE_FSDP='true' , MASTER_ADDR='localhost' , MASTER_PORT='10999' , RANK='0' , LOCAL_RANK='0' , WORLD_SIZE='1' , ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy for i, strategy in enumerate(UpperCAmelCase_ ): UpperCamelCase__ = self.dist_env.copy() UpperCamelCase__ = F'{i + 1}' UpperCamelCase__ = strategy with mockenv_context(**UpperCAmelCase_ ): UpperCamelCase__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.sharding_strategy , ShardingStrategy(i + 1 ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(UpperCAmelCase_ ): UpperCamelCase__ = self.dist_env.copy() UpperCamelCase__ = prefetch_policy with mockenv_context(**UpperCAmelCase_ ): UpperCamelCase__ = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": self.assertIsNone(fsdp_plugin.backward_prefetch ) else: self.assertEqual(fsdp_plugin.backward_prefetch , BackwardPrefetch(i + 1 ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(UpperCAmelCase_ ): UpperCamelCase__ = self.dist_env.copy() UpperCamelCase__ = state_dict_type with mockenv_context(**UpperCAmelCase_ ): UpperCamelCase__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.state_dict_type , StateDictType(i + 1 ) ) if state_dict_type == "FULL_STATE_DICT": self.assertTrue(fsdp_plugin.state_dict_config.offload_to_cpu ) self.assertTrue(fsdp_plugin.state_dict_config.ranka_only ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = AutoModel.from_pretrained(UpperCAmelCase_ ) for policy in FSDP_AUTO_WRAP_POLICY: UpperCamelCase__ = self.dist_env.copy() UpperCamelCase__ = policy if policy == "TRANSFORMER_BASED_WRAP": UpperCamelCase__ = 'BertLayer' elif policy == "SIZE_BASED_WRAP": UpperCamelCase__ = '2000' with mockenv_context(**UpperCAmelCase_ ): UpperCamelCase__ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(UpperCAmelCase_ ) if policy == "NO_WRAP": self.assertIsNone(fsdp_plugin.auto_wrap_policy ) else: self.assertIsNotNone(fsdp_plugin.auto_wrap_policy ) UpperCamelCase__ = self.dist_env.copy() UpperCamelCase__ = 'TRANSFORMER_BASED_WRAP' UpperCamelCase__ = 'T5Layer' with mockenv_context(**UpperCAmelCase_ ): UpperCamelCase__ = FullyShardedDataParallelPlugin() with self.assertRaises(UpperCAmelCase_ ) as cm: fsdp_plugin.set_auto_wrap_policy(UpperCAmelCase_ ) self.assertTrue('Could not find the transformer layer class to wrap in the model.' in str(cm.exception ) ) UpperCamelCase__ = self.dist_env.copy() UpperCamelCase__ = 'SIZE_BASED_WRAP' UpperCamelCase__ = '0' with mockenv_context(**UpperCAmelCase_ ): UpperCamelCase__ = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(UpperCAmelCase_ ) self.assertIsNone(fsdp_plugin.auto_wrap_policy ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: UpperCamelCase__ = self.dist_env.copy() UpperCamelCase__ = mp_dtype with mockenv_context(**UpperCAmelCase_ ): UpperCamelCase__ = Accelerator() if mp_dtype == "fp16": UpperCamelCase__ = torch.floataa elif mp_dtype == "bf16": UpperCamelCase__ = torch.bfloataa UpperCamelCase__ = MixedPrecision(param_dtype=UpperCAmelCase_ , reduce_dtype=UpperCAmelCase_ , buffer_dtype=UpperCAmelCase_ ) self.assertEqual(accelerator.state.fsdp_plugin.mixed_precision_policy , UpperCAmelCase_ ) if mp_dtype == FPaa: self.assertTrue(isinstance(accelerator.scaler , UpperCAmelCase_ ) ) elif mp_dtype == BFaa: self.assertIsNone(accelerator.scaler ) AcceleratorState._reset_state(UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: UpperCamelCase__ = self.dist_env.copy() UpperCamelCase__ = str(UpperCAmelCase_ ).lower() with mockenv_context(**UpperCAmelCase_ ): UpperCamelCase__ = FullyShardedDataParallelPlugin() self.assertEqual(fsdp_plugin.cpu_offload , CPUOffload(offload_params=UpperCAmelCase_ ) ) @require_fsdp @require_multi_gpu @slow class __lowerCamelCase ( __lowerCamelCase ): def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: '''simple docstring''' super().setUp() UpperCamelCase__ = 0.82 UpperCamelCase__ = [ 'fsdp_shard_grad_op_transformer_based_wrap', 'fsdp_full_shard_transformer_based_wrap', ] UpperCamelCase__ = { 'multi_gpu_fp16': 3200, 'fsdp_shard_grad_op_transformer_based_wrap_fp16': 2000, 'fsdp_full_shard_transformer_based_wrap_fp16': 1900, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } UpperCamelCase__ = 160 UpperCamelCase__ = 160 UpperCamelCase__ = inspect.getfile(accelerate.test_utils ) UpperCamelCase__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps'] ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = os.path.join(self.test_scripts_folder , 'test_performance.py' ) UpperCamelCase__ = ['accelerate', 'launch', '--num_processes=2', '--num_machines=1', '--machine_rank=0', '--use_fsdp'] for config in self.performance_configs: UpperCamelCase__ = cmd.copy() for i, strategy in enumerate(UpperCAmelCase_ ): if strategy.lower() in config: cmd_config.append(F'--fsdp_sharding_strategy={i+1}' ) break if "fp32" in config: cmd_config.append('--mixed_precision=no' ) else: cmd_config.append('--mixed_precision=fp16' ) if "cpu_offload" in config: cmd_config.append('--fsdp_offload_params=True' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(F'--fsdp_auto_wrap_policy={policy}' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('--fsdp_transformer_layer_cls_to_wrap=BertLayer' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('--fsdp_min_num_params=2000' ) cmd_config.extend( [ self.test_file_path, F'--output_dir={self.tmpdir}', F'--performance_lower_bound={self.performance_lower_bound}', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy() ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' UpperCamelCase__ = os.path.join(self.test_scripts_folder , 'test_checkpointing.py' ) UpperCamelCase__ = [ 'accelerate', 'launch', '--num_processes=2', '--num_machines=1', '--machine_rank=0', '--use_fsdp', '--mixed_precision=fp16', '--fsdp_transformer_layer_cls_to_wrap=BertLayer', ] for i, strategy in enumerate(UpperCAmelCase_ ): UpperCamelCase__ = cmd.copy() cmd_config.append(F'--fsdp_sharding_strategy={i+1}' ) if strategy != "FULL_SHARD": continue UpperCamelCase__ = len(UpperCAmelCase_ ) for state_dict_type in FSDP_STATE_DICT_TYPE: UpperCamelCase__ = cmd_config[:state_dict_config_index] cmd_config.append(F'--fsdp_state_dict_type={state_dict_type}' ) cmd_config.extend( [ self.test_file_path, F'--output_dir={self.tmpdir}', '--partial_train_epoch=1', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy() ) UpperCamelCase__ = cmd_config[:-1] UpperCamelCase__ = os.path.join(self.tmpdir , 'epoch_0' ) cmd_config.extend( [ F'--resume_from_checkpoint={resume_from_checkpoint}', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy() ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: '''simple docstring''' UpperCamelCase__ = os.path.join(self.test_scripts_folder , 'test_peak_memory_usage.py' ) UpperCamelCase__ = [ 'accelerate', 'launch', '--num_processes=2', '--num_machines=1', '--machine_rank=0', ] for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): UpperCamelCase__ = cmd.copy() if "fp16" in spec: cmd_config.extend(['--mixed_precision=fp16'] ) else: cmd_config.extend(['--mixed_precision=no'] ) if "multi_gpu" in spec: continue else: cmd_config.extend(['--use_fsdp'] ) for i, strategy in enumerate(UpperCAmelCase_ ): if strategy.lower() in spec: cmd_config.append(F'--fsdp_sharding_strategy={i+1}' ) break if "cpu_offload" in spec: cmd_config.append('--fsdp_offload_params=True' ) for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(F'--fsdp_auto_wrap_policy={policy}' ) break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append('--fsdp_transformer_layer_cls_to_wrap=BertLayer' ) elif policy == "SIZE_BASED_WRAP": cmd_config.append('--fsdp_min_num_params=2000' ) cmd_config.extend( [ self.test_file_path, F'--output_dir={self.tmpdir}', F'--peak_memory_upper_bound={peak_mem_upper_bound}', F'--n_train={self.n_train}', F'--n_val={self.n_val}', ] ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy() )
706
"""simple docstring""" A__ : Tuple= """Alexander Joslin""" import operator as op from .stack import Stack def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} UpperCamelCase__ = Stack() UpperCamelCase__ = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(SCREAMING_SNAKE_CASE ) ) elif i in operators: # RULE 2 operator_stack.push(SCREAMING_SNAKE_CASE ) elif i == ")": # RULE 4 UpperCamelCase__ = operator_stack.peek() operator_stack.pop() UpperCamelCase__ = operand_stack.peek() operand_stack.pop() UpperCamelCase__ = operand_stack.peek() operand_stack.pop() UpperCamelCase__ = operators[opr](SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) operand_stack.push(SCREAMING_SNAKE_CASE ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": A__ : int= """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
20
0
"""simple docstring""" from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Union[str, Any]= logging.get_logger(__name__) # TODO Update this A__ : List[str]= { "facebook/esm-1b": "https://huggingface.co/facebook/esm-1b/resolve/main/config.json", # See all ESM models at https://huggingface.co/models?filter=esm } class __lowerCamelCase ( UpperCAmelCase_ ): a : Dict ='esm' def __init__( self , snake_case_=None , snake_case_=None , snake_case_=None , snake_case_=768 , snake_case_=12 , snake_case_=12 , snake_case_=3072 , snake_case_=0.1 , snake_case_=0.1 , snake_case_=1026 , snake_case_=0.02 , snake_case_=1E-12 , snake_case_="absolute" , snake_case_=True , snake_case_=None , snake_case_=False , snake_case_=False , snake_case_=None , snake_case_=None , **snake_case_ , ) -> int: super().__init__(pad_token_id=_lowercase , mask_token_id=_lowercase , **_lowercase ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = position_embedding_type UpperCamelCase__ = use_cache UpperCamelCase__ = emb_layer_norm_before UpperCamelCase__ = token_dropout UpperCamelCase__ = is_folding_model if is_folding_model: if esmfold_config is None: logger.info('No esmfold_config supplied for folding model, using default values.' ) UpperCamelCase__ = EsmFoldConfig() elif isinstance(_lowercase , _lowercase ): UpperCamelCase__ = EsmFoldConfig(**_lowercase ) UpperCamelCase__ = esmfold_config if vocab_list is None: logger.warning('No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!' ) UpperCamelCase__ = get_default_vocab_list() else: UpperCamelCase__ = vocab_list else: UpperCamelCase__ = None UpperCamelCase__ = None if self.esmfold_config is not None and getattr(self.esmfold_config , 'use_esm_attn_map' , _lowercase ): raise ValueError('The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!' ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = super().to_dict() if isinstance(self.esmfold_config , _lowercase ): UpperCamelCase__ = self.esmfold_config.to_dict() return output @dataclass class __lowerCamelCase : a : str =None a : bool =True a : bool =False a : bool =False a : bool =False a : float =0 a : bool =True a : bool =False a : int =1_2_8 a : "TrunkConfig" =None def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: if self.trunk is None: UpperCamelCase__ = TrunkConfig() elif isinstance(self.trunk , _lowercase ): UpperCamelCase__ = TrunkConfig(**self.trunk ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = asdict(self ) UpperCamelCase__ = self.trunk.to_dict() return output @dataclass class __lowerCamelCase : a : int =4_8 a : int =1_0_2_4 a : int =1_2_8 a : int =3_2 a : int =3_2 a : int =3_2 a : float =0 a : float =0 a : bool =False a : int =4 a : Optional[int] =1_2_8 a : "StructureModuleConfig" =None def SCREAMING_SNAKE_CASE__ ( self ) -> int: if self.structure_module is None: UpperCamelCase__ = StructureModuleConfig() elif isinstance(self.structure_module , _lowercase ): UpperCamelCase__ = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(F'`max_recycles` should be positive, got {self.max_recycles}.' ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got' F' {self.sequence_state_dim} and {self.sequence_state_dim}.' ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got' F' {self.pairwise_state_dim} and {self.pairwise_state_dim}.' ) UpperCamelCase__ = self.sequence_state_dim // self.sequence_head_width UpperCamelCase__ = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got' F' {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.' ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got' F' {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.' ) if self.pairwise_state_dim % 2 != 0: raise ValueError(F'`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.' ) if self.dropout >= 0.4: raise ValueError(F'`dropout` should not be greater than 0.4, got {self.dropout}.' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = asdict(self ) UpperCamelCase__ = self.structure_module.to_dict() return output @dataclass class __lowerCamelCase : a : int =3_8_4 a : int =1_2_8 a : int =1_6 a : int =1_2_8 a : int =1_2 a : int =4 a : int =8 a : float =0.1 a : int =8 a : int =1 a : int =2 a : int =7 a : int =1_0 a : float =1E-8 a : float =1E5 def SCREAMING_SNAKE_CASE__ ( self ) -> Any: return asdict(self ) def lowerCAmelCase_( ) -> int: """simple docstring""" return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
707
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py A__ : Any= """src/diffusers""" # Matches is_xxx_available() A__ : Tuple= re.compile(r"""is\_([a-z_]*)_available\(\)""") # Matches from xxx import bla A__ : Any= re.compile(r"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""") A__ : Optional[Any]= """ {0} = None """ A__ : List[Any]= """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) """ A__ : Dict= """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ = _re_backend.findall(SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) == 0: return None return "_and_".join(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( ) -> str: """simple docstring""" with open(os.path.join(SCREAMING_SNAKE_CASE , '__init__.py' ) , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.readlines() # Get to the point we do the actual imports for type checking UpperCamelCase__ = 0 UpperCamelCase__ = {} # Go through the end of the file while line_index < len(SCREAMING_SNAKE_CASE ): # If the line contains is_backend_available, we grab all objects associated with the `else` block UpperCamelCase__ = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('else:' ): line_index += 1 line_index += 1 UpperCamelCase__ = [] # Until we unindent, add backend objects to the list while line_index < len(SCREAMING_SNAKE_CASE ) and len(lines[line_index] ) > 1: UpperCamelCase__ = lines[line_index] UpperCamelCase__ = _re_single_line_import.search(SCREAMING_SNAKE_CASE ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(SCREAMING_SNAKE_CASE ) > 0: UpperCamelCase__ = objects else: line_index += 1 return backend_specific_objects def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if name.isupper(): return DUMMY_CONSTANT.format(SCREAMING_SNAKE_CASE ) elif name.islower(): return DUMMY_FUNCTION.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: return DUMMY_CLASS.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" if backend_specific_objects is None: UpperCamelCase__ = read_init() # For special correspondence backend to module name as used in the function requires_modulename UpperCamelCase__ = {} for backend, objects in backend_specific_objects.items(): UpperCamelCase__ = '[' + ', '.join(F'"{b}"' for b in backend.split('_and_' ) ) + ']' UpperCamelCase__ = '# This file is autogenerated by the command `make fix-copies`, do not edit.\n' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for o in objects] ) UpperCamelCase__ = dummy_file return dummy_files def lowerCAmelCase_( SCREAMING_SNAKE_CASE=False ) -> int: """simple docstring""" UpperCamelCase__ = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py UpperCamelCase__ = {'torch': 'pt'} # Locate actual dummy modules and read their content. UpperCamelCase__ = os.path.join(SCREAMING_SNAKE_CASE , 'utils' ) UpperCamelCase__ = { backend: os.path.join(SCREAMING_SNAKE_CASE , F'dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py' ) for backend in dummy_files.keys() } UpperCamelCase__ = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(SCREAMING_SNAKE_CASE ): with open(SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.read() else: UpperCamelCase__ = '' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( F'Updating diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py as the main ' '__init__ has new objects.' ) with open(dummy_file_paths[backend] , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( 'The main __init__ has objects that are not present in ' F'diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py. Run `make fix-copies` ' 'to fix this.' ) if __name__ == "__main__": A__ : Any= argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") A__ : Optional[int]= parser.parse_args() check_dummies(args.fix_and_overwrite)
20
0
"""simple docstring""" import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class __lowerCamelCase ( unittest.TestCase ): @require_torch def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = pipeline( task='zero-shot-audio-classification' , model='hf-internal-testing/tiny-clap-htsat-unfused' ) UpperCamelCase__ = load_dataset('ashraq/esc50' ) UpperCamelCase__ = dataset['''train''']['''audio'''][-1]['''array'''] UpperCamelCase__ = audio_classifier(snake_case_ , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(snake_case_ ) , [{'score': 0.501, 'label': 'Sound of a dog'}, {'score': 0.499, 'label': 'Sound of vaccum cleaner'}] , ) @unittest.skip('No models are available in TF' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: pass @slow @require_torch def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = pipeline( task='zero-shot-audio-classification' , model='laion/clap-htsat-unfused' , ) # This is an audio of a dog UpperCamelCase__ = load_dataset('ashraq/esc50' ) UpperCamelCase__ = dataset['''train''']['''audio'''][-1]['''array'''] UpperCamelCase__ = audio_classifier(snake_case_ , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(snake_case_ ) , [ {'score': 0.999, 'label': 'Sound of a dog'}, {'score': 0.001, 'label': 'Sound of vaccum cleaner'}, ] , ) UpperCamelCase__ = audio_classifier([audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(snake_case_ ) , [ [ {'score': 0.999, 'label': 'Sound of a dog'}, {'score': 0.001, 'label': 'Sound of vaccum cleaner'}, ], ] * 5 , ) UpperCamelCase__ = audio_classifier( [audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] , batch_size=5 ) self.assertEqual( nested_simplify(snake_case_ ) , [ [ {'score': 0.999, 'label': 'Sound of a dog'}, {'score': 0.001, 'label': 'Sound of vaccum cleaner'}, ], ] * 5 , ) @unittest.skip('No models are available in TF' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: pass
708
"""simple docstring""" # Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file A__ : Optional[Any]= """Run commands across TPU VMs for initial setup before running `accelerate launch`.""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> Dict: """simple docstring""" if subparsers is not None: UpperCamelCase__ = subparsers.add_parser('tpu-config' , description=_description ) else: UpperCamelCase__ = argparse.ArgumentParser('Accelerate tpu-config command' , description=_description ) # Core arguments UpperCamelCase__ = parser.add_argument_group( 'Config Arguments' , 'Arguments that can be configured through `accelerate config`.' ) config_args.add_argument( '--config_file' , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , help='Path to the config file to use for accelerate.' , ) config_args.add_argument( '--tpu_name' , default=SCREAMING_SNAKE_CASE , help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.' , ) config_args.add_argument( '--tpu_zone' , default=SCREAMING_SNAKE_CASE , help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.' , ) UpperCamelCase__ = parser.add_argument_group('TPU Arguments' , 'Arguments for options ran inside the TPU.' ) pod_args.add_argument( '--use_alpha' , action='store_true' , help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.' , ) pod_args.add_argument( '--command_file' , default=SCREAMING_SNAKE_CASE , help='The path to the file containing the commands to run on the pod on startup.' , ) pod_args.add_argument( '--command' , action='append' , nargs='+' , help='A command to run on the pod. Can be passed multiple times.' , ) pod_args.add_argument( '--install_accelerate' , action='store_true' , help='Whether to install accelerate on the pod. Defaults to False.' , ) pod_args.add_argument( '--accelerate_version' , default='latest' , help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.' , ) pod_args.add_argument( '--debug' , action='store_true' , help='If set, will print the command that would be run instead of running it.' ) if subparsers is not None: parser.set_defaults(func=SCREAMING_SNAKE_CASE ) return parser def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase__ = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: UpperCamelCase__ = defaults.command_file if not args.command and defaults.commands is not None: UpperCamelCase__ = defaults.commands if not args.tpu_name: UpperCamelCase__ = defaults.tpu_name if not args.tpu_zone: UpperCamelCase__ = defaults.tpu_zone if args.accelerate_version == "dev": UpperCamelCase__ = 'git+https://github.com/huggingface/accelerate.git' elif args.accelerate_version == "latest": UpperCamelCase__ = 'accelerate -U' elif isinstance(parse(args.accelerate_version ) , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = F'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError('You must specify either a command file or a command to run on the pod.' ) if args.command_file: with open(args.command_file , 'r' ) as f: UpperCamelCase__ = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate UpperCamelCase__ = ['cd /usr/share'] if args.install_accelerate: new_cmd += [F'pip install {args.accelerate_version}'] new_cmd += args.command UpperCamelCase__ = '; '.join(SCREAMING_SNAKE_CASE ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess UpperCamelCase__ = ['gcloud'] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'Running {" ".join(SCREAMING_SNAKE_CASE )}' ) return subprocess.run(SCREAMING_SNAKE_CASE ) print('Successfully setup pod.' ) def lowerCAmelCase_( ) -> int: """simple docstring""" UpperCamelCase__ = tpu_command_parser() UpperCamelCase__ = parser.parse_args() tpu_command_launcher(SCREAMING_SNAKE_CASE )
20
0
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __lowerCamelCase ( _a ): a : Any =4_2 a : Optional[int] =4_2 def __init__( self , snake_case_ , snake_case_ ) -> Any: super().__init__() self.register_modules(unet=_lowerCAmelCase , scheduler=_lowerCAmelCase ) @torch.no_grad() def __call__( self , snake_case_ = 1 , snake_case_ = 50 , snake_case_ = None , snake_case_ = "pil" , snake_case_ = True , **snake_case_ , ) -> Dict: UpperCamelCase__ = self.unet.config.sample_size UpperCamelCase__ = (batch_size, 3, img_size, img_size) UpperCamelCase__ = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) UpperCamelCase__ = randn_tensor(_lowerCAmelCase , generator=_lowerCAmelCase , device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_lowerCAmelCase ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper UpperCamelCase__ = self.scheduler.schedule[t] UpperCamelCase__ = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat UpperCamelCase__ , UpperCamelCase__ = self.scheduler.add_noise_to_input(_lowerCAmelCase , _lowerCAmelCase , generator=_lowerCAmelCase ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. UpperCamelCase__ = (sigma_hat / 2) * model((sample_hat + 1) / 2 , sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev UpperCamelCase__ = self.scheduler.step(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. UpperCamelCase__ = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 , sigma_prev / 2 ).sample UpperCamelCase__ = self.scheduler.step_correct( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , step_output.prev_sample , step_output['derivative'] , ) UpperCamelCase__ = step_output.prev_sample UpperCamelCase__ = (sample / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase__ = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(_lowerCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=_lowerCAmelCase )
709
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : List[str]= logging.get_logger(__name__) class __lowerCamelCase ( _a ): a : Optional[int] ="""timm_backbone""" def __init__( self , snake_case_=None , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=None , **snake_case_ , ) -> Dict: super().__init__(**snake_case_ ) UpperCamelCase__ = backbone UpperCamelCase__ = num_channels UpperCamelCase__ = features_only UpperCamelCase__ = use_pretrained_backbone UpperCamelCase__ = True UpperCamelCase__ = out_indices if out_indices is not None else (-1,)
20
0
"""simple docstring""" from __future__ import annotations import math import random from typing import Any class __lowerCamelCase : def __init__( self ) -> Union[str, Any]: UpperCamelCase__ = [] UpperCamelCase__ = 0 UpperCamelCase__ = 0 def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: return self.head == self.tail def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Dict: self.data.append(UpperCamelCase_ ) UpperCamelCase__ = self.tail + 1 def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.data[self.head] UpperCamelCase__ = self.head + 1 return ret def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: return self.tail - self.head def SCREAMING_SNAKE_CASE__ ( self ) -> int: print(self.data ) print('**************' ) print(self.data[self.head : self.tail] ) class __lowerCamelCase : def __init__( self , snake_case_ ) -> Optional[Any]: UpperCamelCase__ = data UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = 1 def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return self.data def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: return self.left def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: return self.right def SCREAMING_SNAKE_CASE__ ( self ) -> str: return self.height def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[Any]: UpperCamelCase__ = data def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Optional[int]: UpperCamelCase__ = node def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Dict: UpperCamelCase__ = node def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Tuple: UpperCamelCase__ = height def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" if node is None: return 0 return node.get_height() def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" if a > b: return a return b def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> MyNode: """simple docstring""" print('left rotation node:' , node.get_data() ) UpperCamelCase__ = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(lowerCamelCase__ ) UpperCamelCase__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCamelCase__ ) UpperCamelCase__ = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowerCamelCase__ ) return ret def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> MyNode: """simple docstring""" print('right rotation node:' , node.get_data() ) UpperCamelCase__ = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(lowerCamelCase__ ) UpperCamelCase__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCamelCase__ ) UpperCamelCase__ = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowerCamelCase__ ) return ret def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> MyNode: """simple docstring""" UpperCamelCase__ = node.get_left() assert left_child is not None node.set_left(left_rotation(lowerCamelCase__ ) ) return right_rotation(lowerCamelCase__ ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> MyNode: """simple docstring""" UpperCamelCase__ = node.get_right() assert right_child is not None node.set_right(right_rotation(lowerCamelCase__ ) ) return left_rotation(lowerCamelCase__ ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> MyNode | None: """simple docstring""" if node is None: return MyNode(lowerCamelCase__ ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , lowerCamelCase__ ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected UpperCamelCase__ = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child UpperCamelCase__ = right_rotation(lowerCamelCase__ ) else: UpperCamelCase__ = lr_rotation(lowerCamelCase__ ) else: node.set_right(insert_node(node.get_right() , lowerCamelCase__ ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: UpperCamelCase__ = node.get_right() assert right_child is not None if data < right_child.get_data(): UpperCamelCase__ = rl_rotation(lowerCamelCase__ ) else: UpperCamelCase__ = left_rotation(lowerCamelCase__ ) UpperCamelCase__ = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCamelCase__ ) return node def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" while True: UpperCamelCase__ = root.get_right() if right_child is None: break UpperCamelCase__ = right_child return root.get_data() def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" while True: UpperCamelCase__ = root.get_left() if left_child is None: break UpperCamelCase__ = left_child return root.get_data() def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> MyNode | None: """simple docstring""" UpperCamelCase__ = root.get_left() UpperCamelCase__ = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: UpperCamelCase__ = get_left_most(lowerCamelCase__ ) root.set_data(lowerCamelCase__ ) root.set_right(del_node(lowerCamelCase__ , lowerCamelCase__ ) ) elif left_child is not None: UpperCamelCase__ = left_child elif right_child is not None: UpperCamelCase__ = right_child else: return None elif root.get_data() > data: if left_child is None: print('No such data' ) return root else: root.set_left(del_node(lowerCamelCase__ , lowerCamelCase__ ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(lowerCamelCase__ , lowerCamelCase__ ) ) if get_height(lowerCamelCase__ ) - get_height(lowerCamelCase__ ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): UpperCamelCase__ = left_rotation(lowerCamelCase__ ) else: UpperCamelCase__ = rl_rotation(lowerCamelCase__ ) elif get_height(lowerCamelCase__ ) - get_height(lowerCamelCase__ ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): UpperCamelCase__ = right_rotation(lowerCamelCase__ ) else: UpperCamelCase__ = lr_rotation(lowerCamelCase__ ) UpperCamelCase__ = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(lowerCamelCase__ ) return root class __lowerCamelCase : def __init__( self ) -> Optional[int]: UpperCamelCase__ = None def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: return get_height(self.root ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: print('insert:' + str(UpperCamelCase_ ) ) UpperCamelCase__ = insert_node(self.root , UpperCamelCase_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: print('delete:' + str(UpperCamelCase_ ) ) if self.root is None: print('Tree is empty!' ) return UpperCamelCase__ = del_node(self.root , UpperCamelCase_ ) def __str__( self , ) -> Dict: # a level traversale, gives a more intuitive look on the tree UpperCamelCase__ = "" UpperCamelCase__ = MyQueue() q.push(self.root ) UpperCamelCase__ = self.get_height() if layer == 0: return output UpperCamelCase__ = 0 while not q.is_empty(): UpperCamelCase__ = q.pop() UpperCamelCase__ = " " * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(UpperCamelCase_ ) q.push(UpperCamelCase_ ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space UpperCamelCase__ = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , UpperCamelCase_ ) - 1: UpperCamelCase__ = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def lowerCAmelCase_( ) -> None: """simple docstring""" import doctest doctest.testmod() if __name__ == "__main__": _test() A__ : Dict= AVLtree() A__ : List[str]= list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
710
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType A__ : Any= logging.get_logger(__name__) A__ : str= { """microsoft/layoutlmv3-base""": """https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json""", } class __lowerCamelCase ( _a ): a : List[str] ="""layoutlmv3""" def __init__( self , snake_case_=5_0265 , snake_case_=768 , snake_case_=12 , snake_case_=12 , snake_case_=3072 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=2 , snake_case_=0.02 , snake_case_=1E-5 , snake_case_=1 , snake_case_=0 , snake_case_=2 , snake_case_=1024 , snake_case_=128 , snake_case_=128 , snake_case_=True , snake_case_=32 , snake_case_=128 , snake_case_=64 , snake_case_=256 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=224 , snake_case_=3 , snake_case_=16 , snake_case_=None , **snake_case_ , ) -> Union[str, Any]: super().__init__( vocab_size=snake_case_ , hidden_size=snake_case_ , num_hidden_layers=snake_case_ , num_attention_heads=snake_case_ , intermediate_size=snake_case_ , hidden_act=snake_case_ , hidden_dropout_prob=snake_case_ , attention_probs_dropout_prob=snake_case_ , max_position_embeddings=snake_case_ , type_vocab_size=snake_case_ , initializer_range=snake_case_ , layer_norm_eps=snake_case_ , pad_token_id=snake_case_ , bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ , ) UpperCamelCase__ = max_ad_position_embeddings UpperCamelCase__ = coordinate_size UpperCamelCase__ = shape_size UpperCamelCase__ = has_relative_attention_bias UpperCamelCase__ = rel_pos_bins UpperCamelCase__ = max_rel_pos UpperCamelCase__ = has_spatial_attention_bias UpperCamelCase__ = rel_ad_pos_bins UpperCamelCase__ = max_rel_ad_pos UpperCamelCase__ = text_embed UpperCamelCase__ = visual_embed UpperCamelCase__ = input_size UpperCamelCase__ = num_channels UpperCamelCase__ = patch_size UpperCamelCase__ = classifier_dropout class __lowerCamelCase ( _a ): a : Tuple =version.parse("""1.12""" ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) else: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels'}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: return 12 def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , snake_case_ = 3 , snake_case_ = 40 , snake_case_ = 40 , ) -> Mapping[str, Any]: setattr(processor.image_processor , 'apply_ocr' , snake_case_ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase__ = processor.tokenizer.num_special_tokens_to_add(snake_case_ ) UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case_ ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase__ = [[' '.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes UpperCamelCase__ = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) UpperCamelCase__ = self._generate_dummy_images(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) UpperCamelCase__ = dict( processor( snake_case_ , text=snake_case_ , boxes=snake_case_ , return_tensors=snake_case_ , ) ) return inputs
20
0
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class __lowerCamelCase ( _a ): a : int =4_2 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
711
"""simple docstring""" from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class __lowerCamelCase : def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=2 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> Tuple: UpperCamelCase__ = parent UpperCamelCase__ = 13 UpperCamelCase__ = 7 UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = 99 UpperCamelCase__ = 384 UpperCamelCase__ = 2 UpperCamelCase__ = 4 UpperCamelCase__ = 37 UpperCamelCase__ = 'gelu' UpperCamelCase__ = 0.1 UpperCamelCase__ = 0.1 UpperCamelCase__ = 512 UpperCamelCase__ = 16 UpperCamelCase__ = 2 UpperCamelCase__ = 0.02 UpperCamelCase__ = 3 UpperCamelCase__ = 4 UpperCamelCase__ = 128 UpperCamelCase__ = 2 UpperCamelCase__ = 9 UpperCamelCase__ = 1 UpperCamelCase__ = None def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=snake_case_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertModel(config=snake_case_ ) UpperCamelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} UpperCamelCase__ = [input_ids, input_mask] UpperCamelCase__ = model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertForMaskedLM(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForSequenceClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = self.num_choices UpperCamelCase__ = TFConvBertForMultipleChoice(config=snake_case_ ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForTokenClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = TFConvBertForQuestionAnswering(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class __lowerCamelCase ( _a , _a , unittest.TestCase ): a : Any =( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) a : str =( { """feature-extraction""": TFConvBertModel, """fill-mask""": TFConvBertForMaskedLM, """question-answering""": TFConvBertForQuestionAnswering, """text-classification""": TFConvBertForSequenceClassification, """token-classification""": TFConvBertForTokenClassification, """zero-shot""": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) a : Any =False a : Dict =False a : str =False def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = TFConvBertModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = True if hasattr(snake_case_ , 'use_cache' ): UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) for model_class in self.all_model_classes: UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ ) UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = len(model(snake_case_ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(snake_case_ , saved_model=snake_case_ ) UpperCamelCase__ = os.path.join(snake_case_ , 'saved_model' , '1' ) UpperCamelCase__ = tf.keras.models.load_model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = outputs['encoder_hidden_states'] UpperCamelCase__ = outputs['encoder_attentions'] else: UpperCamelCase__ = outputs['hidden_states'] UpperCamelCase__ = outputs['attentions'] self.assertEqual(len(snake_case_ ) , snake_case_ ) UpperCamelCase__ = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(snake_case_ ) , snake_case_ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) def check_decoder_attentions_output(snake_case_ ): UpperCamelCase__ = len(snake_case_ ) self.assertEqual(out_len % 2 , 0 ) UpperCamelCase__ = outputs.decoder_attentions self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(snake_case_ ): UpperCamelCase__ = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: UpperCamelCase__ = True UpperCamelCase__ = False UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) UpperCamelCase__ = len(snake_case_ ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_decoder_attentions_output(snake_case_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) # Check attention is always last and order is fine UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(snake_case_ ) ) self.assertEqual(model.config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) @require_tf class __lowerCamelCase ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) UpperCamelCase__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase__ = model(snake_case_ )[0] UpperCamelCase__ = [1, 6, 768] self.assertEqual(output.shape , snake_case_ ) UpperCamelCase__ = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , snake_case_ , atol=1E-4 )
20
0
"""simple docstring""" import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __lowerCamelCase ( UpperCamelCase_ , unittest.TestCase ): a : Optional[int] =RobertaTokenizer a : List[str] =RobertaTokenizerFast a : List[Any] =True a : List[str] ={"""cls_token""": """<s>"""} def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase__ = dict(zip(_a , range(len(_a ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_a ) ) def SCREAMING_SNAKE_CASE__ ( self , **snake_case_ ) -> Union[str, Any]: kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **_a ) def SCREAMING_SNAKE_CASE__ ( self , **snake_case_ ) -> Union[str, Any]: kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **_a ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Optional[int]: UpperCamelCase__ = """lower newer""" UpperCamelCase__ = """lower newer""" return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCamelCase__ = tokenizer.tokenize(_a ) # , add_prefix_space=True) self.assertListEqual(_a , _a ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , _a ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ = self.get_tokenizer() self.assertListEqual(tokenizer.encode('Hello world!' , add_special_tokens=_a ) , [0, 3_1414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode('Hello world! cécé herlolip 418' , add_special_tokens=_a ) , [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2] , ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.tokenizer_class.from_pretrained('roberta-base' ) UpperCamelCase__ = tokenizer.encode('sequence builders' , add_special_tokens=_a ) UpperCamelCase__ = tokenizer.encode('multi-sequence build' , add_special_tokens=_a ) UpperCamelCase__ = tokenizer.encode( 'sequence builders' , add_special_tokens=_a , add_prefix_space=_a ) UpperCamelCase__ = tokenizer.encode( 'sequence builders' , 'multi-sequence build' , add_special_tokens=_a , add_prefix_space=_a ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(_a ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(_a , _a ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = """Encode this sequence.""" UpperCamelCase__ = tokenizer.byte_encoder[""" """.encode('utf-8' )[0]] # Testing encoder arguments UpperCamelCase__ = tokenizer.encode(_a , add_special_tokens=_a , add_prefix_space=_a ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(_a , _a ) UpperCamelCase__ = tokenizer.encode(_a , add_special_tokens=_a , add_prefix_space=_a ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(_a , _a ) tokenizer.add_special_tokens({'bos_token': '<s>'} ) UpperCamelCase__ = tokenizer.encode(_a , add_special_tokens=_a ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(_a , _a ) # Testing spaces after special tokens UpperCamelCase__ = """<mask>""" tokenizer.add_special_tokens( {'mask_token': AddedToken(_a , lstrip=_a , rstrip=_a )} ) # mask token has a left space UpperCamelCase__ = tokenizer.convert_tokens_to_ids(_a ) UpperCamelCase__ = """Encode <mask> sequence""" UpperCamelCase__ = """Encode <mask>sequence""" UpperCamelCase__ = tokenizer.encode(_a ) UpperCamelCase__ = encoded.index(_a ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(_a , _a ) UpperCamelCase__ = tokenizer.encode(_a ) UpperCamelCase__ = encoded.index(_a ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(_a , _a ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: pass def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(_a , **_a ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(_a , **_a ) UpperCamelCase__ = """A, <mask> AllenNLP sentence.""" UpperCamelCase__ = tokenizer_r.encode_plus(_a , add_special_tokens=_a , return_token_type_ids=_a ) UpperCamelCase__ = tokenizer_p.encode_plus(_a , add_special_tokens=_a , return_token_type_ids=_a ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['token_type_ids'] ) , sum(tokens_p['token_type_ids'] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['attention_mask'] ) / len(tokens_r['attention_mask'] ) , sum(tokens_p['attention_mask'] ) / len(tokens_p['attention_mask'] ) , ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids'] ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids'] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['input_ids'] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r['input_ids'] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( _a , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] ) self.assertSequenceEqual( _a , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=_a , add_prefix_space=_a , trim_offsets=_a ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state['add_prefix_space'] , _a ) self.assertEqual(post_processor_state['add_prefix_space'] , _a ) self.assertEqual(post_processor_state['trim_offsets'] , _a ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): UpperCamelCase__ = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = F'{text_of_1_token} {text_of_1_token}' UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( _a , use_fast=_a , add_prefix_space=_a , trim_offsets=_a ) UpperCamelCase__ = tokenizer_r(_a , return_offsets_mapping=_a , add_special_tokens=_a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_a ) + 1, len(_a ) + 1 + len(_a )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( _a , use_fast=_a , add_prefix_space=_a , trim_offsets=_a ) UpperCamelCase__ = tokenizer_r(_a , return_offsets_mapping=_a , add_special_tokens=_a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_a ) + 1, len(_a ) + 1 + len(_a )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( _a , use_fast=_a , add_prefix_space=_a , trim_offsets=_a ) UpperCamelCase__ = tokenizer_r(_a , return_offsets_mapping=_a , add_special_tokens=_a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_a ), len(_a ) + 1 + len(_a )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( _a , use_fast=_a , add_prefix_space=_a , trim_offsets=_a ) UpperCamelCase__ = tokenizer_r(_a , return_offsets_mapping=_a , add_special_tokens=_a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_a ), len(_a ) + 1 + len(_a )) , ) UpperCamelCase__ = F' {text}' # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( _a , use_fast=_a , add_prefix_space=_a , trim_offsets=_a ) UpperCamelCase__ = tokenizer_r(_a , return_offsets_mapping=_a , add_special_tokens=_a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(_a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_a ) + 1, 1 + len(_a ) + 1 + len(_a )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( _a , use_fast=_a , add_prefix_space=_a , trim_offsets=_a ) UpperCamelCase__ = tokenizer_r(_a , return_offsets_mapping=_a , add_special_tokens=_a ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(_a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_a ), 1 + len(_a ) + 1 + len(_a )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( _a , use_fast=_a , add_prefix_space=_a , trim_offsets=_a ) UpperCamelCase__ = tokenizer_r(_a , return_offsets_mapping=_a , add_special_tokens=_a ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(_a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_a ), 1 + len(_a ) + 1 + len(_a )) , )
712
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 1_00_00_00 , SCREAMING_SNAKE_CASE = 10 ) -> int: """simple docstring""" UpperCamelCase__ = defaultdict(SCREAMING_SNAKE_CASE ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: UpperCamelCase__ = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: UpperCamelCase__ = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(SCREAMING_SNAKE_CASE , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"""{solution() = }""")
20
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : List[str]= { """configuration_clipseg""": [ """CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CLIPSegConfig""", """CLIPSegTextConfig""", """CLIPSegVisionConfig""", ], """processing_clipseg""": ["""CLIPSegProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[Any]= [ """CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST""", """CLIPSegModel""", """CLIPSegPreTrainedModel""", """CLIPSegTextModel""", """CLIPSegVisionModel""", """CLIPSegForImageSegmentation""", ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys A__ : Union[str, Any]= _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
713
"""simple docstring""" import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __lowerCamelCase ( unittest.TestCase ): def __init__( self , snake_case_ , snake_case_=100 , snake_case_=13 , snake_case_=30 , snake_case_=2 , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=10 , snake_case_=0.02 , snake_case_=3 , ) -> Optional[int]: UpperCamelCase__ = parent UpperCamelCase__ = vocab_size UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = patch_size UpperCamelCase__ = num_channels UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCamelCase__ = (image_size // patch_size) ** 2 UpperCamelCase__ = num_patches + 1 def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=snake_case_ , initializer_range=self.initializer_range , ) return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = FlaxBeitModel(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = FlaxBeitForMaskedImageModeling(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.type_sequence_label_size UpperCamelCase__ = FlaxBeitForImageClassification(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase__ = 1 UpperCamelCase__ = FlaxBeitForImageClassification(snake_case_ ) UpperCamelCase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase__ = model(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class __lowerCamelCase ( _a , unittest.TestCase ): a : int =( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE__ ( self ) -> None: UpperCamelCase__ = FlaxBeitModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ['pixel_values'] self.assertListEqual(arg_names[:1] , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ ) UpperCamelCase__ = model_class(snake_case_ ) @jax.jit def model_jitted(snake_case_ , **snake_case_ ): return model(pixel_values=snake_case_ , **snake_case_ ) with self.subTest('JIT Enabled' ): UpperCamelCase__ = model_jitted(**snake_case_ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): UpperCamelCase__ = model_jitted(**snake_case_ ).to_tuple() self.assertEqual(len(snake_case_ ) , len(snake_case_ ) ) for jitted_output, output in zip(snake_case_ , snake_case_ ): self.assertEqual(jitted_output.shape , output.shape ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: for model_class_name in self.all_model_classes: UpperCamelCase__ = model_class_name.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase__ = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(snake_case_ ) def lowerCAmelCase_( ) -> Optional[int]: """simple docstring""" UpperCamelCase__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @require_flax class __lowerCamelCase ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = FlaxBeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ).pixel_values # prepare bool_masked_pos UpperCamelCase__ = np.ones((1, 196) , dtype=snake_case_ ) # forward pass UpperCamelCase__ = model(pixel_values=snake_case_ , bool_masked_pos=snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 196, 8192) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , snake_case_ , atol=1E-2 ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ) # forward pass UpperCamelCase__ = model(**snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 1000) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array([-1.2_385, -1.0_987, -1.0_108] ) self.assertTrue(np.allclose(logits[0, :3] , snake_case_ , atol=1E-4 ) ) UpperCamelCase__ = 281 self.assertEqual(logits.argmax(-1 ).item() , snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ) # forward pass UpperCamelCase__ = model(**snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 2_1841) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array([1.6_881, -0.2_787, 0.5_901] ) self.assertTrue(np.allclose(logits[0, :3] , snake_case_ , atol=1E-4 ) ) UpperCamelCase__ = 2396 self.assertEqual(logits.argmax(-1 ).item() , snake_case_ )
20
0
"""simple docstring""" from heapq import heappop, heappush import numpy as np def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" UpperCamelCase__ , UpperCamelCase__ = grid.shape UpperCamelCase__ = [-1, 1, 0, 0] UpperCamelCase__ = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] UpperCamelCase__ , UpperCamelCase__ = [(0, source)], set() UpperCamelCase__ = np.full((rows, cols) , np.inf ) UpperCamelCase__ = 0 UpperCamelCase__ = np.empty((rows, cols) , dtype=lowerCAmelCase__ ) UpperCamelCase__ = None while queue: ((UpperCamelCase__) , (UpperCamelCase__)) = heappop(lowerCAmelCase__ ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: UpperCamelCase__ = [] while (x, y) != source: path.append((x, y) ) UpperCamelCase__ , UpperCamelCase__ = predecessors[x, y] path.append(lowerCAmelCase__ ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(lowerCAmelCase__ ) ): UpperCamelCase__ , UpperCamelCase__ = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: UpperCamelCase__ = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(lowerCAmelCase__ , (dist + 1, (nx, ny)) ) UpperCamelCase__ = dist + 1 UpperCamelCase__ = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
714
"""simple docstring""" import sys from collections import defaultdict class __lowerCamelCase : def __init__( self ) -> Tuple: UpperCamelCase__ = [] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: return self.node_position[vertex] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Optional[int]: UpperCamelCase__ = pos def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: UpperCamelCase__ = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: UpperCamelCase__ = 2 * start + 1 else: UpperCamelCase__ = 2 * start + 2 if heap[smallest_child] < heap[start]: UpperCamelCase__ , UpperCamelCase__ = heap[smallest_child], positions[smallest_child] UpperCamelCase__ , UpperCamelCase__ = ( heap[start], positions[start], ) UpperCamelCase__ , UpperCamelCase__ = temp, tempa UpperCamelCase__ = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , snake_case_ ) self.top_to_bottom(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Any: UpperCamelCase__ = position[index] while index != 0: UpperCamelCase__ = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: UpperCamelCase__ = heap[parent] UpperCamelCase__ = position[parent] self.set_position(position[parent] , snake_case_ ) else: UpperCamelCase__ = val UpperCamelCase__ = temp self.set_position(snake_case_ , snake_case_ ) break UpperCamelCase__ = parent else: UpperCamelCase__ = val UpperCamelCase__ = temp self.set_position(snake_case_ , 0 ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Any: UpperCamelCase__ = len(snake_case_ ) // 2 - 1 for i in range(snake_case_ , -1 , -1 ): self.top_to_bottom(snake_case_ , snake_case_ , len(snake_case_ ) , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = positions[0] UpperCamelCase__ = sys.maxsize self.top_to_bottom(snake_case_ , 0 , len(snake_case_ ) , snake_case_ ) return temp def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = Heap() UpperCamelCase__ = [0] * len(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = [-1] * len(SCREAMING_SNAKE_CASE ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph UpperCamelCase__ = [] # Heap of Distance of vertices from their neighboring vertex UpperCamelCase__ = [] for vertex in range(len(SCREAMING_SNAKE_CASE ) ): distance_tv.append(sys.maxsize ) positions.append(SCREAMING_SNAKE_CASE ) heap.node_position.append(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = [] UpperCamelCase__ = 1 UpperCamelCase__ = sys.maxsize for neighbor, distance in adjacency_list[0]: UpperCamelCase__ = 0 UpperCamelCase__ = distance heap.heapify(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for _ in range(1 , len(SCREAMING_SNAKE_CASE ) ): UpperCamelCase__ = heap.delete_minimum(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) UpperCamelCase__ = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(SCREAMING_SNAKE_CASE )] ): UpperCamelCase__ = distance heap.bottom_to_top( SCREAMING_SNAKE_CASE , heap.get_position(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A__ : Dict= int(input("""Enter number of edges: """).strip()) A__ : Dict= defaultdict(list) for _ in range(edges_number): A__ : Dict= [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
20
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging A__ : List[Any]= logging.get_logger(__name__) A__ : Optional[int]= "▁" A__ : Dict= {"vocab_file": "spiece.model"} A__ : Optional[int]= { "vocab_file": { "google/reformer-crime-and-punishment": ( "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model" ) } } A__ : Union[str, Any]= { "google/reformer-crime-and-punishment": 52_42_88, } class __lowerCamelCase ( __lowerCAmelCase ): a : List[str] =VOCAB_FILES_NAMES a : str =PRETRAINED_VOCAB_FILES_MAP a : List[str] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : List[Any] =["""input_ids""", """attention_mask"""] def __init__( self , snake_case_ , snake_case_="</s>" , snake_case_="<unk>" , snake_case_=[] , snake_case_ = None , **snake_case_ , ) -> None: UpperCamelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_UpperCamelCase , unk_token=_UpperCamelCase , additional_special_tokens=_UpperCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_UpperCamelCase , ) UpperCamelCase__ = vocab_file UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_UpperCamelCase ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Any: return self.sp_model.get_piece_size() def SCREAMING_SNAKE_CASE__ ( self ) -> Dict[str, int]: UpperCamelCase__ = {self.convert_ids_to_tokens(_UpperCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> List[str]: UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = None return state def __setstate__( self , snake_case_ ) -> List[str]: UpperCamelCase__ = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): UpperCamelCase__ = {} UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: return self.sp_model.encode(_UpperCamelCase , out_type=_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Optional[int]: return self.sp_model.piece_to_id(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Union[str, Any]: if index < self.sp_model.get_piece_size(): UpperCamelCase__ = self.sp_model.IdToPiece(_UpperCamelCase ) return token def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[Any]: UpperCamelCase__ = [] UpperCamelCase__ = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_UpperCamelCase ) + token UpperCamelCase__ = [] else: current_sub_tokens.append(_UpperCamelCase ) out_string += self.sp_model.decode(_UpperCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> Tuple[str]: if not os.path.isdir(_UpperCamelCase ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase__ = os.path.join( _UpperCamelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _UpperCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_UpperCamelCase , 'wb' ) as fi: UpperCamelCase__ = self.sp_model.serialized_model_proto() fi.write(_UpperCamelCase ) return (out_vocab_file,)
715
"""simple docstring""" from copy import deepcopy class __lowerCamelCase : def __init__( self , snake_case_ = None , snake_case_ = None ) -> None: if arr is None and size is not None: UpperCamelCase__ = size UpperCamelCase__ = [0] * size elif arr is not None: self.init(snake_case_ ) else: raise ValueError('Either arr or size must be specified' ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: UpperCamelCase__ = len(snake_case_ ) UpperCamelCase__ = deepcopy(snake_case_ ) for i in range(1 , self.size ): UpperCamelCase__ = self.next_(snake_case_ ) if j < self.size: self.tree[j] += self.tree[i] def SCREAMING_SNAKE_CASE__ ( self ) -> list[int]: UpperCamelCase__ = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): UpperCamelCase__ = self.next_(snake_case_ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: return index + (index & (-index)) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: return index - (index & (-index)) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value UpperCamelCase__ = self.next_(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: self.add(snake_case_ , value - self.get(snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: if right == 0: return 0 UpperCamelCase__ = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] UpperCamelCase__ = self.prev(snake_case_ ) return result def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> int: return self.prefix(snake_case_ ) - self.prefix(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: return self.query(snake_case_ , index + 1 ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: value -= self.tree[0] if value < 0: return -1 UpperCamelCase__ = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 UpperCamelCase__ = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
20
0
"""simple docstring""" import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation A__ : int= logging.get_logger(__name__) A__ : Optional[int]= {"""vocab_file""": """vocab.txt""", """emoji_file""": """emoji.json"""} A__ : Optional[int]= { """vocab_file""": { """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt""", }, """emoji_file""": { """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json""", }, } A__ : Optional[Any]= { """abeja/gpt-neox-japanese-2.7b""": 20_48, } def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" with open(_lowerCamelCase , 'r' , encoding='utf-8' ) as f: UpperCamelCase__ = json.loads(f.read() ) UpperCamelCase__ = collections.OrderedDict() UpperCamelCase__ = collections.OrderedDict() UpperCamelCase__ = collections.OrderedDict() with open(_lowerCamelCase , 'r' , encoding='utf-8' ) as f: UpperCamelCase__ = f.readlines() UpperCamelCase__ = [[t.rstrip('\n' )] if (t == ',' or ',' not in t) else t.rstrip('\n' ).split(',' ) for t in token] for idx, b in enumerate(_lowerCamelCase ): UpperCamelCase__ = b UpperCamelCase__ = idx for wd in b: UpperCamelCase__ = idx return vocab, raw_vocab, ids_to_tokens, emoji class __lowerCamelCase ( a__ ): a : Union[str, Any] =VOCAB_FILES_NAMES a : Dict =PRETRAINED_VOCAB_FILES_MAP a : str =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : str =["""input_ids""", """attention_mask"""] def __init__( self , snake_case_ , snake_case_ , snake_case_="<|endoftext|>" , snake_case_="<|endoftext|>" , snake_case_="<|startoftext|>" , snake_case_="<|endoftext|>" , snake_case_=False , **snake_case_ , ) -> Dict: super().__init__( unk_token=_A , pad_token=_A , bos_token=_A , eos_token=_A , do_clean_text=_A , **_A , ) if not os.path.isfile(_A ): raise ValueError( F'Can\'t find a vocabulary file at path \'{vocab_file}\'. To load the vocabulary from a Google pretrained' ' model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`' ) if not os.path.isfile(_A ): raise ValueError( F'Can\'t find a emoji file at path \'{emoji_file}\'. To load the emoji information from a Google' ' pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`' ) UpperCamelCase__ = do_clean_text UpperCamelCase__ = load_vocab_and_emoji(_A , _A ) UpperCamelCase__ = SubWordJapaneseTokenizer( vocab=self.vocab , ids_to_tokens=self.ids_to_tokens , emoji=self.emoji ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: return len(self.raw_vocab ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: return dict(self.raw_vocab , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Dict: return self.subword_tokenizer.tokenize(_A , clean=self.do_clean_text ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: return self.vocab.get(_A , self.vocab.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: return self.subword_tokenizer.convert_id_to_token(_A ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: UpperCamelCase__ = ''.join(_A ).strip() return out_string def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Optional[int]: UpperCamelCase__ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(_A , add_special_tokens=_A ) + [self.eos_token_id] ) if len(_A ) > self.model_max_length: UpperCamelCase__ = input_ids[-self.model_max_length :] return input_ids def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> str: UpperCamelCase__ = 0 if os.path.isdir(_A ): UpperCamelCase__ = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase__ = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['emoji_file'] ) else: UpperCamelCase__ = ( (filename_prefix + '-' if filename_prefix else '') + save_directory + VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase__ = ( (filename_prefix + '-' if filename_prefix else '') + save_directory + VOCAB_FILES_NAMES['emoji_file'] ) with open(_A , 'w' , encoding='utf-8' ) as writer: for token_index, token in self.ids_to_tokens.items(): if index != token_index: logger.warning( F'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.' ' Please check that the vocabulary is not corrupted!' ) UpperCamelCase__ = token_index writer.write(','.join(_A ) + '\n' ) index += 1 with open(_A , 'w' , encoding='utf-8' ) as writer: json.dump(self.emoji , _A ) return vocab_file, emoji_file class __lowerCamelCase ( a__ ): def __init__( self , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = vocab # same as swe UpperCamelCase__ = ids_to_tokens # same as bpe UpperCamelCase__ = emoji UpperCamelCase__ = np.max([len(_A ) for w in self.vocab.keys()] ) UpperCamelCase__ = re.compile(r'(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)' ) UpperCamelCase__ = re.compile(r'[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*' ) UpperCamelCase__ = re.compile(r'[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}' ) UpperCamelCase__ = re.compile( r'([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*' ) UpperCamelCase__ = re.compile( r'(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*' ) UpperCamelCase__ = re.compile( r'((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*' ) UpperCamelCase__ = '─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿' UpperCamelCase__ = '▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟' UpperCamelCase__ = str.maketrans({k: '<BLOCK>' for k in keisen + blocks} ) def __len__( self ) -> Optional[Any]: return len(self.ids_to_tokens ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Tuple: UpperCamelCase__ = self.content_repattera.sub('<URL>' , _A ) UpperCamelCase__ = self.content_repattera.sub('<EMAIL>' , _A ) UpperCamelCase__ = self.content_repattera.sub('<TEL>' , _A ) UpperCamelCase__ = self.content_repattera.sub('<DATE>' , _A ) UpperCamelCase__ = self.content_repattera.sub('<DATE>' , _A ) UpperCamelCase__ = self.content_repattera.sub('<PRICE>' , _A ) UpperCamelCase__ = content.translate(self.content_transa ) while "<BLOCK><BLOCK>" in content: UpperCamelCase__ = content.replace('<BLOCK><BLOCK>' , '<BLOCK>' ) return content def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_=False ) -> Union[str, Any]: UpperCamelCase__ = text.replace(' ' , '<SP>' ) UpperCamelCase__ = text.replace(' ' , '<SP>' ) UpperCamelCase__ = text.replace('\r\n' , '<BR>' ) UpperCamelCase__ = text.replace('\n' , '<BR>' ) UpperCamelCase__ = text.replace('\r' , '<BR>' ) UpperCamelCase__ = text.replace('\t' , '<TAB>' ) UpperCamelCase__ = text.replace('—' , 'ー' ) UpperCamelCase__ = text.replace('−' , 'ー' ) for k, v in self.emoji["emoji"].items(): if k in text: UpperCamelCase__ = text.replace(_A , _A ) if clean: UpperCamelCase__ = self.clean_text(_A ) def check_simbol(snake_case_ ): UpperCamelCase__ = x.encode() if len(_A ) == 1 and len(_A ) == 2: UpperCamelCase__ = (int(e[0] ) << 8) + int(e[1] ) if ( (c >= 0Xc2a1 and c <= 0Xc2bf) or (c >= 0Xc780 and c <= 0Xc783) or (c >= 0Xcab9 and c <= 0Xcbbf) or (c >= 0Xcc80 and c <= 0Xcda2) ): return True return False def checkuae(snake_case_ ): UpperCamelCase__ = x.encode() if len(_A ) == 1 and len(_A ) == 3: UpperCamelCase__ = (int(e[0] ) << 16) + (int(e[1] ) << 8) + int(e[2] ) if c >= 0Xe2_8080 and c <= 0Xe2_b07f: return True return False UpperCamelCase__ = 0 UpperCamelCase__ = [] while pos < len(_A ): UpperCamelCase__ = min(len(_A ) , pos + self.maxlen + 1 ) if text[pos] == '<' else pos + 3 UpperCamelCase__ = [] # (token_id, token, pos) for e in range(_A , _A , -1 ): UpperCamelCase__ = text[pos:e] if wd in self.vocab: if wd[0] == "<" and len(_A ) > 2: UpperCamelCase__ = [(self.vocab[wd], wd, e)] break else: candidates.append((self.vocab[wd], wd, e) ) if len(_A ) > 0: # the smallest token_id is adopted UpperCamelCase__ = sorted(_A , key=lambda snake_case_ : x[0] )[0] result.append(_A ) UpperCamelCase__ = e else: UpperCamelCase__ = pos + 1 UpperCamelCase__ = text[pos:end] if check_simbol(_A ): result.append('<KIGOU>' ) elif checkuae(_A ): result.append('<U2000U2BFF>' ) else: for i in wd.encode('utf-8' ): result.append('<|byte%d|>' % i ) UpperCamelCase__ = end return result def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_="\n" ) -> str: UpperCamelCase__ = [] UpperCamelCase__ = [] UpperCamelCase__ = self.ids_to_tokens[index][0] if word[:6] == "<|byte" and word[-2:] == "|>": byte_tokens.append(int(word[6:-2] ) ) else: if len(_A ) > 0: words.append(bytearray(_A ).decode('utf-8' , errors='replace' ) ) UpperCamelCase__ = [] if word[:7] == "<|emoji" and word[-2:] == "|>": words.append(self.emoji['emoji_inv'][word] ) elif word == "<SP>": words.append(' ' ) elif word == "<BR>": words.append(_A ) elif word == "<TAB>": words.append('\t' ) elif word == "<BLOCK>": words.append('▀' ) elif word == "<KIGOU>": words.append('ǀ' ) elif word == "<U2000U2BFF>": words.append('‖' ) else: words.append(_A ) if len(_A ) > 0: words.append(bytearray(_A ).decode('utf-8' , errors='replace' ) ) UpperCamelCase__ = ''.join(_A ) return text
716
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow A__ : Union[str, Any]= logging.getLogger() @unittest.skip("""Temporarily disable the doc tests.""" ) @require_torch @require_tf @slow class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = None , snake_case_ = None , snake_case_ = True , ) -> Tuple: UpperCamelCase__ = [file for file in os.listdir(snake_case_ ) if os.path.isfile(os.path.join(snake_case_ , snake_case_ ) )] if identifier is not None: UpperCamelCase__ = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(snake_case_ , snake_case_ ): for n_ in n_identifier: UpperCamelCase__ = [file for file in files if n_ not in file] else: UpperCamelCase__ = [file for file in files if n_identifier not in file] UpperCamelCase__ = ignore_files or [] ignore_files.append('__init__.py' ) UpperCamelCase__ = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' , snake_case_ ) if only_modules: UpperCamelCase__ = file.split('.' )[0] try: UpperCamelCase__ = getattr(snake_case_ , snake_case_ ) UpperCamelCase__ = doctest.DocTestSuite(snake_case_ ) UpperCamelCase__ = unittest.TextTestRunner().run(snake_case_ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'{module_identifier} is not a module.' ) else: UpperCamelCase__ = doctest.testfile(str('..' / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'modeling' UpperCamelCase__ = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(snake_case_ , identifier=snake_case_ , ignore_files=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'tokenization' self.analyze_directory(snake_case_ , identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'configuration' self.analyze_directory(snake_case_ , identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(snake_case_ , n_identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = Path('docs/source' ) UpperCamelCase__ = ['favicon.ico'] self.analyze_directory(snake_case_ , ignore_files=snake_case_ , only_modules=snake_case_ )
20
0
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase__ = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def lowerCAmelCase_( ) -> int: """simple docstring""" print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
717
"""simple docstring""" import warnings 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 A__ : str= logging.get_logger(__name__) A__ : List[Any]= { """nvidia/segformer-b0-finetuned-ade-512-512""": ( """https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json""" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class __lowerCamelCase ( _a ): a : Any ="""segformer""" def __init__( self , snake_case_=3 , snake_case_=4 , snake_case_=[2, 2, 2, 2] , snake_case_=[8, 4, 2, 1] , snake_case_=[32, 64, 160, 256] , snake_case_=[7, 3, 3, 3] , snake_case_=[4, 2, 2, 2] , snake_case_=[1, 2, 5, 8] , snake_case_=[4, 4, 4, 4] , snake_case_="gelu" , snake_case_=0.0 , snake_case_=0.0 , snake_case_=0.1 , snake_case_=0.02 , snake_case_=0.1 , snake_case_=1E-6 , snake_case_=256 , snake_case_=255 , **snake_case_ , ) -> Tuple: super().__init__(**snake_case_ ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( 'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be' ' removed, as the behaviour will default to that of reshape_last_stage = True.' , snake_case_ , ) UpperCamelCase__ = num_channels UpperCamelCase__ = num_encoder_blocks UpperCamelCase__ = depths UpperCamelCase__ = sr_ratios UpperCamelCase__ = hidden_sizes UpperCamelCase__ = patch_sizes UpperCamelCase__ = strides UpperCamelCase__ = mlp_ratios UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = classifier_dropout_prob UpperCamelCase__ = initializer_range UpperCamelCase__ = drop_path_rate UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = decoder_hidden_size UpperCamelCase__ = kwargs.get('reshape_last_stage' , snake_case_ ) UpperCamelCase__ = semantic_loss_ignore_index class __lowerCamelCase ( _a ): a : Any =version.parse("""1.11""" ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: return 1E-4 @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: return 12
20
0
"""simple docstring""" import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging A__ : Tuple= logging.get_logger(__name__) A__ : Tuple= {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all LED models at https://huggingface.co/models?filter=LED A__ : int= { "vocab_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", }, "merges_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt", }, "tokenizer_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json", }, } A__ : List[str]= { "allenai/led-base-16384": 1_63_84, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def lowerCAmelCase_( ) -> Tuple: """simple docstring""" UpperCamelCase__ = ( list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) ) ) UpperCamelCase__ = bs[:] UpperCamelCase__ = 0 for b in range(2**8 ): if b not in bs: bs.append(a_ ) cs.append(2**8 + n ) n += 1 UpperCamelCase__ = [chr(a_ ) for n in cs] return dict(zip(a_ , a_ ) ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" UpperCamelCase__ = set() UpperCamelCase__ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCamelCase__ = char return pairs class __lowerCamelCase ( _UpperCAmelCase ): a : str =VOCAB_FILES_NAMES a : int =PRETRAINED_VOCAB_FILES_MAP a : Union[str, Any] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : List[str] =["""input_ids""", """attention_mask"""] def __init__( self , snake_case_ , snake_case_ , snake_case_="replace" , snake_case_="<s>" , snake_case_="</s>" , snake_case_="</s>" , snake_case_="<s>" , snake_case_="<unk>" , snake_case_="<pad>" , snake_case_="<mask>" , snake_case_=False , **snake_case_ , ) -> List[Any]: UpperCamelCase__ = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else bos_token UpperCamelCase__ = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else eos_token UpperCamelCase__ = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else sep_token UpperCamelCase__ = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else cls_token UpperCamelCase__ = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else unk_token UpperCamelCase__ = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it UpperCamelCase__ = AddedToken(lowerCamelCase_ , lstrip=lowerCamelCase_ , rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else mask_token super().__init__( errors=lowerCamelCase_ , bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , add_prefix_space=lowerCamelCase_ , **lowerCamelCase_ , ) with open(lowerCamelCase_ , encoding='utf-8' ) as vocab_handle: UpperCamelCase__ = json.load(lowerCamelCase_ ) UpperCamelCase__ = {v: k for k, v in self.encoder.items()} UpperCamelCase__ = errors # how to handle errors in decoding UpperCamelCase__ = bytes_to_unicode() UpperCamelCase__ = {v: k for k, v in self.byte_encoder.items()} with open(lowerCamelCase_ , encoding='utf-8' ) as merges_handle: UpperCamelCase__ = merges_handle.read().split('\n' )[1:-1] UpperCamelCase__ = [tuple(merge.split() ) for merge in bpe_merges] UpperCamelCase__ = dict(zip(lowerCamelCase_ , range(len(lowerCamelCase_ ) ) ) ) UpperCamelCase__ = {} UpperCamelCase__ = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions UpperCamelCase__ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def SCREAMING_SNAKE_CASE__ ( self ) -> str: return len(self.encoder ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: if token in self.cache: return self.cache[token] UpperCamelCase__ = tuple(lowerCamelCase_ ) UpperCamelCase__ = get_pairs(lowerCamelCase_ ) if not pairs: return token while True: UpperCamelCase__ = min(lowerCamelCase_ , key=lambda snake_case_ : self.bpe_ranks.get(lowerCamelCase_ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break UpperCamelCase__ = bigram UpperCamelCase__ = [] UpperCamelCase__ = 0 while i < len(lowerCamelCase_ ): try: UpperCamelCase__ = word.index(lowerCamelCase_ , lowerCamelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) UpperCamelCase__ = j 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 UpperCamelCase__ = tuple(lowerCamelCase_ ) UpperCamelCase__ = new_word if len(lowerCamelCase_ ) == 1: break else: UpperCamelCase__ = get_pairs(lowerCamelCase_ ) UpperCamelCase__ = ''' '''.join(lowerCamelCase_ ) UpperCamelCase__ = word return word def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Tuple: UpperCamelCase__ = [] for token in re.findall(self.pat , lowerCamelCase_ ): UpperCamelCase__ = ''''''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCamelCase_ ).split(' ' ) ) return bpe_tokens def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Dict: return self.encoder.get(lowerCamelCase_ , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Union[str, Any]: return self.decoder.get(lowerCamelCase_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Union[str, Any]: UpperCamelCase__ = ''''''.join(lowerCamelCase_ ) UpperCamelCase__ = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> Tuple[str]: if not os.path.isdir(lowerCamelCase_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase__ = os.path.join( lowerCamelCase_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase__ = 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' ) UpperCamelCase__ = 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 snake_case_ : kv[1] ): if index != token_index: logger.warning( F'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' ' Please check that the tokenizer is not corrupted!' ) UpperCamelCase__ = token_index writer.write(' '.join(lowerCamelCase_ ) + '\n' ) index += 1 return vocab_file, merge_file def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase_ , token_ids_a=lowerCamelCase_ , already_has_special_tokens=lowerCamelCase_ ) if token_ids_a is None: return [1] + ([0] * len(lowerCamelCase_ )) + [1] return [1] + ([0] * len(lowerCamelCase_ )) + [1, 1] + ([0] * len(lowerCamelCase_ )) + [1] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_=False , **snake_case_ ) -> Optional[Any]: UpperCamelCase__ = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(lowerCamelCase_ ) > 0 and not text[0].isspace()): UpperCamelCase__ = ''' ''' + text return (text, kwargs) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = PaddingStrategy.DO_NOT_PAD , snake_case_ = None , snake_case_ = None , ) -> dict: UpperCamelCase__ = super()._pad( encoded_inputs=lowerCamelCase_ , max_length=lowerCamelCase_ , padding_strategy=lowerCamelCase_ , pad_to_multiple_of=lowerCamelCase_ , return_attention_mask=lowerCamelCase_ , ) # Load from model defaults if return_attention_mask is None: UpperCamelCase__ = '''attention_mask''' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: UpperCamelCase__ = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. UpperCamelCase__ = len(encoded_inputs['global_attention_mask'] ) != len(lowerCamelCase_ ) if needs_to_be_padded: UpperCamelCase__ = len(lowerCamelCase_ ) - len(encoded_inputs['global_attention_mask'] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` UpperCamelCase__ = ( encoded_inputs['''global_attention_mask'''] + [-1] * difference ) elif self.padding_side == "left": UpperCamelCase__ = [-1] * difference + encoded_inputs[ '''global_attention_mask''' ] else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return encoded_inputs
718
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class __lowerCamelCase ( _a ): @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: UpperCamelCase__ = parser.add_parser('download' ) download_parser.add_argument( '--cache-dir' , type=snake_case_ , default=snake_case_ , help='Path to location to store the models' ) download_parser.add_argument( '--force' , action='store_true' , help='Force the model to be download even if already in cache-dir' ) download_parser.add_argument( '--trust-remote-code' , action='store_true' , help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine' , ) download_parser.add_argument('model' , type=snake_case_ , help='Name of the model to download' ) download_parser.set_defaults(func=snake_case_ ) def __init__( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: UpperCamelCase__ = model UpperCamelCase__ = cache UpperCamelCase__ = force UpperCamelCase__ = trust_remote_code def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
20
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A__ : Any= {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple= ['''NllbTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Any= ['''NllbTokenizerFast'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys A__ : List[Any]= _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
719
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCamelCase ( _a ): def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=False , snake_case_=True , snake_case_="None" , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> str: UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = relative_attention UpperCamelCase__ = position_biased_input UpperCamelCase__ = pos_att_type UpperCamelCase__ = scope def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Any: self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: UpperCamelCase__ = DebertaVaModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ )[0] UpperCamelCase__ = model(snake_case_ , token_type_ids=snake_case_ )[0] UpperCamelCase__ = model(snake_case_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: UpperCamelCase__ = DebertaVaForMaskedLM(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Dict: UpperCamelCase__ = self.num_labels UpperCamelCase__ = DebertaVaForSequenceClassification(snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[int]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = DebertaVaForTokenClassification(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = DebertaVaForQuestionAnswering(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , start_positions=snake_case_ , end_positions=snake_case_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = DebertaVaForMultipleChoice(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __lowerCamelCase ( _a , _a , unittest.TestCase ): a : Any =( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) a : Dict =( { """feature-extraction""": DebertaVaModel, """fill-mask""": DebertaVaForMaskedLM, """question-answering""": DebertaVaForQuestionAnswering, """text-classification""": DebertaVaForSequenceClassification, """token-classification""": DebertaVaForTokenClassification, """zero-shot""": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) a : Tuple =True a : Union[str, Any] =False a : Tuple =False a : Union[str, Any] =False a : Dict =False def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = DebertaVaModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = DebertaVaModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) @require_torch @require_sentencepiece @require_tokenizers class __lowerCamelCase ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: pass @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) UpperCamelCase__ = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) UpperCamelCase__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ )[0] # compare the actual values for a slice. UpperCamelCase__ = torch.tensor( [[[0.2_356, 0.1_948, 0.0_369], [-0.1_063, 0.3_586, -0.5_152], [-0.6_399, -0.0_259, -0.2_525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , snake_case_ , atol=1E-4 ) , F'{output[:, 1:4, 1:4]}' )
20
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__ : Union[str, Any]= logging.get_logger(__name__) A__ : Union[str, Any]= { '''kssteven/ibert-roberta-base''': '''https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json''', '''kssteven/ibert-roberta-large''': '''https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json''', '''kssteven/ibert-roberta-large-mnli''': ( '''https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json''' ), } class __lowerCamelCase ( SCREAMING_SNAKE_CASE__ ): a : Dict ="""ibert""" def __init__( self , snake_case_=3_0522 , snake_case_=768 , snake_case_=12 , snake_case_=12 , snake_case_=3072 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=2 , snake_case_=0.02 , snake_case_=1E-12 , snake_case_=1 , snake_case_=0 , snake_case_=2 , snake_case_="absolute" , snake_case_=False , snake_case_="none" , **snake_case_ , ) -> Union[str, Any]: super().__init__(pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase , **_lowercase ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = position_embedding_type UpperCamelCase__ = quant_mode UpperCamelCase__ = force_dequant class __lowerCamelCase ( SCREAMING_SNAKE_CASE__ ): @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": UpperCamelCase__ = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCamelCase__ = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
720
"""simple docstring""" 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 lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = SwinConfig() UpperCamelCase__ = swin_name.split('_' ) UpperCamelCase__ = name_split[1] UpperCamelCase__ = int(name_split[4] ) UpperCamelCase__ = int(name_split[3][-1] ) if model_size == "tiny": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 6, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "small": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "base": UpperCamelCase__ = 1_28 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (4, 8, 16, 32) else: UpperCamelCase__ = 1_92 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (6, 12, 24, 48) if "in22k" in swin_name: UpperCamelCase__ = 2_18_41 else: UpperCamelCase__ = 10_00 UpperCamelCase__ = 'huggingface/label-files' UpperCamelCase__ = 'imagenet-1k-id2label.json' UpperCamelCase__ = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) UpperCamelCase__ = {int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} UpperCamelCase__ = idalabel UpperCamelCase__ = {v: k for k, v in idalabel.items()} UpperCamelCase__ = img_size UpperCamelCase__ = num_classes UpperCamelCase__ = embed_dim UpperCamelCase__ = depths UpperCamelCase__ = num_heads UpperCamelCase__ = window_size return config def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" if "patch_embed.proj" in name: UpperCamelCase__ = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: UpperCamelCase__ = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: UpperCamelCase__ = 'encoder.' + name if "attn.proj" in name: UpperCamelCase__ = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: UpperCamelCase__ = name.replace('attn' , 'attention.self' ) if "norm1" in name: UpperCamelCase__ = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: UpperCamelCase__ = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: UpperCamelCase__ = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: UpperCamelCase__ = name.replace('mlp.fc2' , 'output.dense' ) if name == "norm.weight": UpperCamelCase__ = 'layernorm.weight' if name == "norm.bias": UpperCamelCase__ = 'layernorm.bias' if "head" in name: UpperCamelCase__ = name.replace('head' , 'classifier' ) else: UpperCamelCase__ = 'swin.' + name return name def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCamelCase__ = orig_state_dict.pop(SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: UpperCamelCase__ = key.split('.' ) UpperCamelCase__ = int(key_split[1] ) UpperCamelCase__ = int(key_split[3] ) UpperCamelCase__ = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: UpperCamelCase__ = val[:dim, :] UpperCamelCase__ = val[ dim : dim * 2, : ] UpperCamelCase__ = val[-dim:, :] else: UpperCamelCase__ = val[ :dim ] UpperCamelCase__ = val[ dim : dim * 2 ] UpperCamelCase__ = val[ -dim: ] else: UpperCamelCase__ = val return orig_state_dict def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = timm.create_model(SCREAMING_SNAKE_CASE , pretrained=SCREAMING_SNAKE_CASE ) timm_model.eval() UpperCamelCase__ = get_swin_config(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = SwinForImageClassification(SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase__ = convert_state_dict(timm_model.state_dict() , SCREAMING_SNAKE_CASE ) model.load_state_dict(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = 'http://images.cocodataset.org/val2017/000000039769.jpg' UpperCamelCase__ = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swin_name.replace('_' , '-' ) ) ) UpperCamelCase__ = Image.open(requests.get(SCREAMING_SNAKE_CASE , stream=SCREAMING_SNAKE_CASE ).raw ) UpperCamelCase__ = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='pt' ) UpperCamelCase__ = timm_model(inputs['pixel_values'] ) UpperCamelCase__ = 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__": A__ : Optional[Any]= 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.""" ) A__ : Tuple= parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
20
0
"""simple docstring""" import warnings 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 A__ : Optional[int]= logging.get_logger(__name__) A__ : Optional[int]= { """nvidia/segformer-b0-finetuned-ade-512-512""": ( """https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json""" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class __lowerCamelCase ( _lowercase ): a : List[str] ='''segformer''' def __init__( self , snake_case_=3 , snake_case_=4 , snake_case_=[2, 2, 2, 2] , snake_case_=[8, 4, 2, 1] , snake_case_=[32, 64, 160, 256] , snake_case_=[7, 3, 3, 3] , snake_case_=[4, 2, 2, 2] , snake_case_=[1, 2, 5, 8] , snake_case_=[4, 4, 4, 4] , snake_case_="gelu" , snake_case_=0.0 , snake_case_=0.0 , snake_case_=0.1 , snake_case_=0.02 , snake_case_=0.1 , snake_case_=1E-6 , snake_case_=256 , snake_case_=255 , **snake_case_ , ) -> Any: super().__init__(**A_ ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( 'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be' ' removed, as the behaviour will default to that of reshape_last_stage = True.' , A_ , ) UpperCamelCase__ = num_channels UpperCamelCase__ = num_encoder_blocks UpperCamelCase__ = depths UpperCamelCase__ = sr_ratios UpperCamelCase__ = hidden_sizes UpperCamelCase__ = patch_sizes UpperCamelCase__ = strides UpperCamelCase__ = mlp_ratios UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = classifier_dropout_prob UpperCamelCase__ = initializer_range UpperCamelCase__ = drop_path_rate UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = decoder_hidden_size UpperCamelCase__ = kwargs.get('reshape_last_stage' , A_ ) UpperCamelCase__ = semantic_loss_ignore_index class __lowerCamelCase ( _lowercase ): a : Optional[Any] =version.parse("""1.11""" ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: return 1E-4 @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: return 12
721
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" UpperCamelCase__ = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 50_00 ) -> int: """simple docstring""" UpperCamelCase__ = [(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 ) ): UpperCamelCase__ = pentagonal_nums[j] UpperCamelCase__ = pentagonal_i + pentagonal_j UpperCamelCase__ = 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() = }""")
20
0
"""simple docstring""" import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer A__ : List[str]= logging.get_logger(__name__) A__ : str= {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} A__ : str= { """vocab_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json""", }, """merges_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt""", }, """tokenizer_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json""", }, } A__ : List[Any]= { """allenai/led-base-16384""": 1_63_84, } class __lowerCamelCase ( lowercase__ ): '''simple docstring''' a : Optional[int] =VOCAB_FILES_NAMES a : List[str] =PRETRAINED_VOCAB_FILES_MAP a : str =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : str =LEDTokenizer a : List[Any] =['input_ids', 'attention_mask'] def __init__( self , snake_case_=None , snake_case_=None , snake_case_=None , snake_case_="replace" , snake_case_="<s>" , snake_case_="</s>" , snake_case_="</s>" , snake_case_="<s>" , snake_case_="<unk>" , snake_case_="<pad>" , snake_case_="<mask>" , snake_case_=False , snake_case_=True , **snake_case_ , ) -> Optional[int]: super().__init__( snake_case_ , snake_case_ , tokenizer_file=snake_case_ , errors=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , sep_token=snake_case_ , cls_token=snake_case_ , unk_token=snake_case_ , pad_token=snake_case_ , mask_token=snake_case_ , add_prefix_space=snake_case_ , trim_offsets=snake_case_ , **snake_case_ , ) UpperCamelCase__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , snake_case_ ) != add_prefix_space: UpperCamelCase__ = getattr(snake_case_ , pre_tok_state.pop('type' ) ) UpperCamelCase__ = add_prefix_space UpperCamelCase__ = pre_tok_class(**snake_case_ ) UpperCamelCase__ = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` UpperCamelCase__ = 'post_processor' UpperCamelCase__ = getattr(self.backend_tokenizer , snake_case_ , snake_case_ ) if tokenizer_component_instance: UpperCamelCase__ = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: UpperCamelCase__ = tuple(state['sep'] ) if "cls" in state: UpperCamelCase__ = tuple(state['cls'] ) UpperCamelCase__ = False if state.get('add_prefix_space' , snake_case_ ) != add_prefix_space: UpperCamelCase__ = add_prefix_space UpperCamelCase__ = True if state.get('trim_offsets' , snake_case_ ) != trim_offsets: UpperCamelCase__ = trim_offsets UpperCamelCase__ = True if changes_to_apply: UpperCamelCase__ = getattr(snake_case_ , state.pop('type' ) ) UpperCamelCase__ = component_class(**snake_case_ ) setattr(self.backend_tokenizer , snake_case_ , snake_case_ ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: UpperCamelCase__ = AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else value UpperCamelCase__ = value def SCREAMING_SNAKE_CASE__ ( self , *snake_case_ , **snake_case_ ) -> List[Any]: UpperCamelCase__ = kwargs.get('is_split_into_words' , snake_case_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' 'to use it with pretokenized inputs.' ) return super()._batch_encode_plus(*snake_case_ , **snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , *snake_case_ , **snake_case_ ) -> Union[str, Any]: UpperCamelCase__ = kwargs.get('is_split_into_words' , snake_case_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' 'to use it with pretokenized inputs.' ) return super()._encode_plus(*snake_case_ , **snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> Union[str, Any]: UpperCamelCase__ = self._tokenizer.model.save(snake_case_ , name=snake_case_ ) return tuple(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_=None ) -> int: UpperCamelCase__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> Optional[int]: UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = PaddingStrategy.DO_NOT_PAD , snake_case_ = None , snake_case_ = None , ) -> Optional[Any]: UpperCamelCase__ = super()._pad( encoded_inputs=snake_case_ , max_length=snake_case_ , padding_strategy=snake_case_ , pad_to_multiple_of=snake_case_ , return_attention_mask=snake_case_ , ) # Load from model defaults if return_attention_mask is None: UpperCamelCase__ = 'attention_mask' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: UpperCamelCase__ = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. UpperCamelCase__ = len(encoded_inputs['global_attention_mask'] ) != len(snake_case_ ) if needs_to_be_padded: UpperCamelCase__ = len(snake_case_ ) - len(encoded_inputs['global_attention_mask'] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` UpperCamelCase__ = ( encoded_inputs['global_attention_mask'] + [-1] * difference ) elif self.padding_side == "left": UpperCamelCase__ = [-1] * difference + encoded_inputs[ 'global_attention_mask' ] else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return encoded_inputs
700
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 50_00_00_00 ) -> int: """simple docstring""" UpperCamelCase__ = set() UpperCamelCase__ = int((limit - 24) ** (1 / 2) ) UpperCamelCase__ = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , SCREAMING_SNAKE_CASE ) ) ) for primea in primes: UpperCamelCase__ = primea * primea for primea in primes: UpperCamelCase__ = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: UpperCamelCase__ = primea * primea * primea * primea UpperCamelCase__ = square + cube + tetr if total >= limit: break ret.add(SCREAMING_SNAKE_CASE ) return len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(F"""{solution() = }""")
20
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor A__ : str= logging.get_logger(__name__) class __lowerCamelCase ( _a ): def __init__( self , *snake_case_ , **snake_case_ ) -> None: warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' , snake_case_ , ) super().__init__(*snake_case_ , **snake_case_ )
701
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer A__ : List[Any]= ["""bert-base-uncased""", """bert-base-cased"""] A__ : Optional[int]= """hf-internal-testing/tiny-bert-tf-only""" if is_tf_available(): class __lowerCamelCase ( tf.keras.Model ): def __init__( self , snake_case_ ) -> Optional[int]: super().__init__() UpperCamelCase__ = tokenizer UpperCamelCase__ = AutoConfig.from_pretrained(snake_case_ ) UpperCamelCase__ = TFAutoModel.from_config(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: UpperCamelCase__ = self.tokenizer(snake_case_ ) UpperCamelCase__ = self.bert(**snake_case_ ) return out["pooler_output"] @require_tf @require_tensorflow_text class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ) -> str: super().setUp() UpperCamelCase__ = [ BertTokenizer.from_pretrained(snake_case_ ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false UpperCamelCase__ = [TFBertTokenizer.from_pretrained(snake_case_ ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(snake_case_ , use_fast_bert_tokenizer=snake_case_ ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCamelCase__ = [ 'This is a straightforward English test sentence.', 'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.', 'Now we\'re going to add some Chinese: 一 二 三 一二三', 'And some much more rare Chinese: 齉 堃 齉堃', 'Je vais aussi écrire en français pour tester les accents', 'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ', ] UpperCamelCase__ = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase__ = tokenizer(snake_case_ , return_tensors='tf' , padding='longest' ) UpperCamelCase__ = tf_tokenizer(snake_case_ ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> str: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = tf_tokenizer(self.paired_sentences ) UpperCamelCase__ = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = tf.function(snake_case_ ) for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase__ = tf.constant(snake_case_ ) UpperCamelCase__ = compiled_tokenizer(snake_case_ ) UpperCamelCase__ = tf_tokenizer(snake_case_ ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = ModelToSave(tokenizer=snake_case_ ) UpperCamelCase__ = tf.convert_to_tensor(self.test_sentences ) UpperCamelCase__ = model(snake_case_ ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCamelCase__ = Path(snake_case_ ) / 'saved.model' model.save(snake_case_ ) UpperCamelCase__ = tf.keras.models.load_model(snake_case_ ) UpperCamelCase__ = loaded_model(snake_case_ ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
20
0
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class __lowerCamelCase : def __init__( self , snake_case_ , snake_case_=99 , snake_case_=13 , snake_case_=7 , snake_case_=9 , snake_case_=True , snake_case_=True , snake_case_=False , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_=8 , snake_case_=0.1 , snake_case_=0.002 , snake_case_=1 , snake_case_=0 , snake_case_=0 , snake_case_=None , snake_case_=None , ) -> List[Any]: UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = encoder_seq_length UpperCamelCase__ = decoder_seq_length # For common tests UpperCamelCase__ = self.decoder_seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_attention_mask UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = d_ff UpperCamelCase__ = relative_attention_num_buckets UpperCamelCase__ = dropout_rate UpperCamelCase__ = initializer_factor UpperCamelCase__ = eos_token_id UpperCamelCase__ = pad_token_id UpperCamelCase__ = decoder_start_token_id UpperCamelCase__ = None UpperCamelCase__ = decoder_layers def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: return TaConfig.from_pretrained('google/umt5-base' ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_=None , snake_case_=None , snake_case_=None , snake_case_=None , snake_case_=None , ) -> Optional[Any]: if attention_mask is None: UpperCamelCase__ = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: UpperCamelCase__ = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: UpperCamelCase__ = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=__A ) if decoder_head_mask is None: UpperCamelCase__ = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=__A ) if cross_attn_head_mask is None: UpperCamelCase__ = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=__A ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input UpperCamelCase__ = input_ids.clamp(self.pad_token_id + 1 ) UpperCamelCase__ = decoder_input_ids.clamp(self.pad_token_id + 1 ) UpperCamelCase__ = self.get_config() UpperCamelCase__ = config.num_attention_heads UpperCamelCase__ = self.prepare_inputs_dict(__A , __A , __A ) return config, input_dict def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = self.prepare_config_and_inputs() return config, inputs_dict def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , ) -> Dict: UpperCamelCase__ = UMTaModel(config=__A ) model.to(__A ) model.eval() UpperCamelCase__ = model( input_ids=__A , decoder_input_ids=__A , attention_mask=__A , decoder_attention_mask=__A , ) UpperCamelCase__ = model(input_ids=__A , decoder_input_ids=__A ) UpperCamelCase__ = result.last_hidden_state UpperCamelCase__ = result.past_key_values UpperCamelCase__ = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(__A ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , ) -> str: UpperCamelCase__ = UMTaModel(config=__A ).get_decoder().to(__A ).eval() # first forward pass UpperCamelCase__ = model(__A , use_cache=__A ) UpperCamelCase__ = model(__A ) UpperCamelCase__ = model(__A , use_cache=__A ) self.parent.assertTrue(len(__A ) == len(__A ) ) self.parent.assertTrue(len(__A ) == len(__A ) + 1 ) UpperCamelCase__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = model(__A )["last_hidden_state"] UpperCamelCase__ = model(__A , past_key_values=__A )["last_hidden_state"] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -1, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__A , __A , atol=1E-3 ) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , ) -> int: UpperCamelCase__ = UMTaModel(config=__A ).to(__A ).half().eval() UpperCamelCase__ = model(**__A )["last_hidden_state"] self.parent.assertFalse(torch.isnan(__A ).any().item() ) @require_torch class __lowerCamelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): a : List[str] =( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) a : Optional[Any] =(UMTaForConditionalGeneration,) if is_torch_available() else () a : Optional[int] =( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) a : List[str] =True a : Dict =False a : Tuple =False a : List[Any] =True a : str =True # The small UMT5 model needs higher percentages for CPU/MP tests a : str =[0.8, 0.9] def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = UMTaModelTester(self ) @unittest.skip('Test has a segmentation fault on torch 1.8.0' ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() UpperCamelCase__ = UMTaModel(config_and_inputs[0] ).to(__A ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( __A , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F'{tmpdirname}/t5_test.onnx' , export_params=__A , opset_version=9 , input_names=['input_ids', 'decoder_input_ids'] , ) @unittest.skipIf(torch_device == 'cpu' , 'Cant do half precision' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*__A ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = ["encoder_attentions", "decoder_attentions", "cross_attentions"] UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() UpperCamelCase__ = config_and_inputs[0] UpperCamelCase__ = UMTaForConditionalGeneration(__A ).eval() model.to(__A ) UpperCamelCase__ = { "head_mask": torch.zeros(config.num_layers , config.num_heads , device=__A ), "decoder_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=__A ), "cross_attn_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=__A ), } for attn_name, (name, mask) in zip(__A , head_masking.items() ): UpperCamelCase__ = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": UpperCamelCase__ = torch.ones( config.num_decoder_layers , config.num_heads , device=__A ) UpperCamelCase__ = model.generate( config_and_inputs[1]['input_ids'] , num_beams=1 , max_length=3 , output_attentions=__A , return_dict_in_generate=__A , **__A , ) # We check the state of decoder_attentions and cross_attentions just from the last step UpperCamelCase__ = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('Does not work on the tiny model as we keep hitting edge cases.' ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: pass @require_torch @require_sentencepiece @require_tokenizers class __lowerCamelCase ( unittest.TestCase ): @slow @unittest.skip( 'Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = UMTaForConditionalGeneration.from_pretrained('google/umt5-small' , return_dict=__A ).to(__A ) UpperCamelCase__ = AutoTokenizer.from_pretrained('google/umt5-small' , use_fast=__A , legacy=__A ) UpperCamelCase__ = [ "Bonjour monsieur <extra_id_0> bien <extra_id_1>.", "No se como puedo <extra_id_0>.", "This is the reason why we <extra_id_0> them.", "The <extra_id_0> walks in <extra_id_1>, seats", "A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.", ] UpperCamelCase__ = tokenizer(__A , return_tensors='pt' , padding=__A ).input_ids # fmt: off UpperCamelCase__ = torch.tensor( [ [ 3_8530, 21_0703, 25_6299, 1410, 25_6298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 2_5922, 25_6299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 1_9014, 1_0620, 758, 25_6299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 25_6299, 1_4869, 281, 301, 25_6298, 275, 11_9983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 25_6299, 1_4869, 281, 2234, 289, 2275, 333,6_1391, 289, 25_6298, 543, 25_6297, 16_8714, 329, 25_6296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(__A , __A ) UpperCamelCase__ = model.generate(input_ids.to(__A ) ) UpperCamelCase__ = [ "<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>", "<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", ] UpperCamelCase__ = tokenizer.batch_decode(__A ) self.assertEqual(__A , __A )
702
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> list[int]: """simple docstring""" UpperCamelCase__ = len(SCREAMING_SNAKE_CASE ) for i in range(SCREAMING_SNAKE_CASE ): for j in range(i + 1 , SCREAMING_SNAKE_CASE ): if numbers[j] < numbers[i]: UpperCamelCase__ , UpperCamelCase__ = numbers[j], numbers[i] return numbers if __name__ == "__main__": A__ : Union[str, Any]= input("""Enter numbers separated by a comma:\n""").strip() A__ : List[Any]= [int(item) for item in user_input.split(""",""")] print(exchange_sort(unsorted))
20
0
"""simple docstring""" from __future__ import annotations from typing import Any class __lowerCamelCase : def __init__( self , snake_case_ , snake_case_ , snake_case_ = 0 ) -> None: UpperCamelCase__ = row, column UpperCamelCase__ = [[default_value for c in range(snake_case_ )] for r in range(snake_case_ )] def __str__( self ) -> str: UpperCamelCase__ = F'Matrix consist of {self.row} rows and {self.column} columns\n' # Make string identifier UpperCamelCase__ = 0 for row_vector in self.array: for obj in row_vector: UpperCamelCase__ = max(snake_case_ , len(str(snake_case_ ) ) ) UpperCamelCase__ = F'%{max_element_length}s' # Make string and return def single_line(snake_case_ ) -> str: nonlocal string_format_identifier UpperCamelCase__ = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(snake_case_ ) for row_vector in self.array ) return s def __repr__( self ) -> str: return str(self ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> bool: if not (isinstance(snake_case_ , (list, tuple) ) and len(snake_case_ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self , snake_case_ ) -> Any: assert self.validate_indicies(snake_case_ ) return self.array[loc[0]][loc[1]] def __setitem__( self , snake_case_ , snake_case_ ) -> None: assert self.validate_indicies(snake_case_ ) UpperCamelCase__ = value def __add__( self , snake_case_ ) -> Matrix: assert isinstance(snake_case_ , snake_case_ ) assert self.row == another.row and self.column == another.column # Add UpperCamelCase__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCamelCase__ = self[r, c] + another[r, c] return result def __neg__( self ) -> Matrix: UpperCamelCase__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCamelCase__ = -self[r, c] return result def __sub__( self , snake_case_ ) -> Matrix: return self + (-another) def __mul__( self , snake_case_ ) -> Matrix: if isinstance(snake_case_ , (int, float) ): # Scalar multiplication UpperCamelCase__ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCamelCase__ = self[r, c] * another return result elif isinstance(snake_case_ , snake_case_ ): # Matrix multiplication assert self.column == another.row UpperCamelCase__ = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: UpperCamelCase__ = F'Unsupported type given for another ({type(snake_case_ )})' raise TypeError(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Matrix: UpperCamelCase__ = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): UpperCamelCase__ = self[r, c] return result def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Any: assert isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate UpperCamelCase__ = v.transpose() UpperCamelCase__ = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowerCAmelCase_( ) -> str: """simple docstring""" UpperCamelCase__ = Matrix(3 , 3 , 0 ) for i in range(3 ): UpperCamelCase__ = 1 print(F'a^(-1) is {ainv}' ) # u, v UpperCamelCase__ = Matrix(3 , 1 , 0 ) UpperCamelCase__ = 1, 2, -3 UpperCamelCase__ = Matrix(3 , 1 , 0 ) UpperCamelCase__ = 4, -2, 5 print(F'u is {u}' ) print(F'v is {v}' ) print(F'uv^T is {u * v.transpose()}' ) # Sherman Morrison print(F'(a + uv^T)^(-1) is {ainv.sherman_morrison(_lowerCamelCase , _lowerCamelCase )}' ) def lowerCAmelCase_( ) -> Any: """simple docstring""" import doctest doctest.testmod() testa()
703
"""simple docstring""" import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("""9.1.0"""): A__ : str= { """linear""": PIL.Image.Resampling.BILINEAR, """bilinear""": PIL.Image.Resampling.BILINEAR, """bicubic""": PIL.Image.Resampling.BICUBIC, """lanczos""": PIL.Image.Resampling.LANCZOS, """nearest""": PIL.Image.Resampling.NEAREST, } else: A__ : str= { """linear""": PIL.Image.LINEAR, """bilinear""": PIL.Image.BILINEAR, """bicubic""": PIL.Image.BICUBIC, """lanczos""": PIL.Image.LANCZOS, """nearest""": PIL.Image.NEAREST, } def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = (images / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() UpperCamelCase__ = numpy_to_pil(SCREAMING_SNAKE_CASE ) return images def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if images.ndim == 3: UpperCamelCase__ = images[None, ...] UpperCamelCase__ = (images * 2_55).round().astype('uint8' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images UpperCamelCase__ = [Image.fromarray(image.squeeze() , mode='L' ) for image in images] else: UpperCamelCase__ = [Image.fromarray(SCREAMING_SNAKE_CASE ) for image in images] return pil_images
20
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class __lowerCamelCase ( metaclass=__SCREAMING_SNAKE_CASE ): a : Any =["""onnx"""] def __init__( self , *snake_case_ , **snake_case_ ) -> List[Any]: requires_backends(self , ['onnx'] ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *snake_case_ , **snake_case_ ) -> int: requires_backends(cls , ['onnx'] ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *snake_case_ , **snake_case_ ) -> int: requires_backends(cls , ['onnx'] )
704
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging A__ : Dict= logging.get_logger(__name__) A__ : str= {"""vocab_file""": """spiece.model"""} A__ : Union[str, Any]= { """vocab_file""": { """t5-small""": """https://huggingface.co/t5-small/resolve/main/spiece.model""", """t5-base""": """https://huggingface.co/t5-base/resolve/main/spiece.model""", """t5-large""": """https://huggingface.co/t5-large/resolve/main/spiece.model""", """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/spiece.model""", """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/spiece.model""", } } # TODO(PVP) - this should be removed in Transformers v5 A__ : Union[str, Any]= { """t5-small""": 5_12, """t5-base""": 5_12, """t5-large""": 5_12, """t5-3b""": 5_12, """t5-11b""": 5_12, } A__ : Optional[Any]= """▁""" class __lowerCamelCase ( _a ): a : Dict =VOCAB_FILES_NAMES a : str =PRETRAINED_VOCAB_FILES_MAP a : Union[str, Any] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : List[str] =["""input_ids""", """attention_mask"""] def __init__( self , snake_case_ , snake_case_="</s>" , snake_case_="<unk>" , snake_case_="<pad>" , snake_case_=100 , snake_case_=None , snake_case_ = None , snake_case_=True , **snake_case_ , ) -> None: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: UpperCamelCase__ = [F'<extra_id_{i}>' for i in range(snake_case_ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens UpperCamelCase__ = len(set(filter(lambda snake_case_ : bool('extra_id' in str(snake_case_ ) ) , snake_case_ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' ' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids' ' tokens' ) if legacy: logger.warning_once( F'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to' ' read the related pull request available at https://github.com/huggingface/transformers/pull/24565' ) UpperCamelCase__ = legacy UpperCamelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=snake_case_ , unk_token=snake_case_ , pad_token=snake_case_ , extra_ids=snake_case_ , additional_special_tokens=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , legacy=snake_case_ , **snake_case_ , ) UpperCamelCase__ = vocab_file UpperCamelCase__ = extra_ids UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: UpperCamelCase__ = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( 'This tokenizer was incorrectly instantiated with a model max length of' F' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' ' behavior is kept to avoid breaking backwards compatibility when padding/encoding with' ' `truncation is True`.\n- Be aware that you SHOULD NOT rely on' F' {pretrained_model_name_or_path} automatically truncating your input to' F' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' F' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' ' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please' ' instantiate this tokenizer with `model_max_length` set to your preferred value.' , snake_case_ , ) return max_model_length @property def SCREAMING_SNAKE_CASE__ ( self ) -> Any: return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = {self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case_ , token_ids_a=snake_case_ , already_has_special_tokens=snake_case_ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(snake_case_ )) + [1] return ([0] * len(snake_case_ )) + [1] + ([0] * len(snake_case_ )) + [1] def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return list( set(filter(lambda snake_case_ : bool(re.search(r'<extra_id_\d+>' , snake_case_ ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: return [self._convert_token_to_id(snake_case_ ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[int]: if len(snake_case_ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' ' eos tokens being added.' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = self._add_eos_if_not_present(snake_case_ ) if token_ids_a is None: return token_ids_a else: UpperCamelCase__ = self._add_eos_if_not_present(snake_case_ ) return token_ids_a + token_ids_a def __getstate__( self ) -> str: UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = None return state def __setstate__( self , snake_case_ ) -> Any: UpperCamelCase__ = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): UpperCamelCase__ = {} UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , **snake_case_ ) -> List[str]: # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: UpperCamelCase__ = SPIECE_UNDERLINE + text.replace(snake_case_ , ' ' ) return super().tokenize(snake_case_ , **snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , **snake_case_ ) -> List[Any]: if not self.legacy: UpperCamelCase__ = text.startswith(snake_case_ ) if is_first: UpperCamelCase__ = text[1:] UpperCamelCase__ = self.sp_model.encode(snake_case_ , out_type=snake_case_ ) if not self.legacy and not is_first and not text.startswith(' ' ) and tokens[0].startswith(snake_case_ ): UpperCamelCase__ = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: if token.startswith('<extra_id_' ): UpperCamelCase__ = re.match(r'<extra_id_(\d+)>' , snake_case_ ) UpperCamelCase__ = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Optional[int]: if index < self.sp_model.get_piece_size(): UpperCamelCase__ = self.sp_model.IdToPiece(snake_case_ ) else: UpperCamelCase__ = F'<extra_id_{self.vocab_size - 1 - index}>' return token def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: UpperCamelCase__ = [] UpperCamelCase__ = '' UpperCamelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(snake_case_ ) + token UpperCamelCase__ = True UpperCamelCase__ = [] else: current_sub_tokens.append(snake_case_ ) UpperCamelCase__ = False out_string += self.sp_model.decode(snake_case_ ) return out_string.strip() def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> Tuple[str]: if not os.path.isdir(snake_case_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase__ = os.path.join( snake_case_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case_ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case_ , 'wb' ) as fi: UpperCamelCase__ = self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,)
20
0
"""simple docstring""" from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets from .splits import NamedSplit from .utils import logging from .utils.py_utils import Literal A__ : List[str]= logging.get_logger(__name__) A__ : List[str]= TypeVar("""DatasetType""", Dataset, IterableDataset) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = "first_exhausted" , ) -> str: """simple docstring""" from .arrow_dataset import Dataset from .iterable_dataset import IterableDataset if not datasets: raise ValueError('Unable to interleave an empty list of datasets.' ) for i, dataset in enumerate(snake_case__ ): if not isinstance(snake_case__ , (Dataset, IterableDataset) ): if isinstance(snake_case__ , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ' 'is an empty dataset dictionary.' ) raise ValueError( F'Dataset at position {i} has at least one split: {list(snake_case__ )}\n' F'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(snake_case__ ) )}\']' ) raise ValueError( F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(snake_case__ ).__name__}.' ) if i == 0: UpperCamelCase__ = ( (Dataset, IterableDataset) if isinstance(snake_case__ , snake_case__ ) else (IterableDataset, Dataset) ) elif not isinstance(snake_case__ , snake_case__ ): raise ValueError( F'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.' ) if stopping_strategy not in ["first_exhausted", "all_exhausted"]: raise ValueError(F'{stopping_strategy} is not supported. Please enter a valid stopping_strategy.' ) if dataset_type is Dataset: return _interleave_map_style_datasets( snake_case__ , snake_case__ , snake_case__ , info=snake_case__ , split=snake_case__ , stopping_strategy=snake_case__ ) else: return _interleave_iterable_datasets( snake_case__ , snake_case__ , snake_case__ , info=snake_case__ , split=snake_case__ , stopping_strategy=snake_case__ ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 0 , ) -> Any: """simple docstring""" if not dsets: raise ValueError('Unable to concatenate an empty list of datasets.' ) for i, dataset in enumerate(snake_case__ ): if not isinstance(snake_case__ , (Dataset, IterableDataset) ): if isinstance(snake_case__ , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ' 'is an empty dataset dictionary.' ) raise ValueError( F'Dataset at position {i} has at least one split: {list(snake_case__ )}\n' F'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(snake_case__ ) )}\']' ) raise ValueError( F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(snake_case__ ).__name__}.' ) if i == 0: UpperCamelCase__ = ( (Dataset, IterableDataset) if isinstance(snake_case__ , snake_case__ ) else (IterableDataset, Dataset) ) elif not isinstance(snake_case__ , snake_case__ ): raise ValueError( F'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.' ) if dataset_type is Dataset: return _concatenate_map_style_datasets(snake_case__ , info=snake_case__ , split=snake_case__ , axis=snake_case__ ) else: return _concatenate_iterable_datasets(snake_case__ , info=snake_case__ , split=snake_case__ , axis=snake_case__ )
705
"""simple docstring""" from __future__ import annotations from typing import Generic, TypeVar A__ : Any= TypeVar("""T""") class __lowerCamelCase ( Generic[T] ): def __init__( self , snake_case_ ) -> None: UpperCamelCase__ = data UpperCamelCase__ = self UpperCamelCase__ = 0 class __lowerCamelCase ( Generic[T] ): def __init__( self ) -> None: # map from node name to the node object UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: # create a new set with x as its member UpperCamelCase__ = DisjointSetTreeNode(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> DisjointSetTreeNode[T]: # find the set x belongs to (with path-compression) UpperCamelCase__ = self.map[data] if elem_ref != elem_ref.parent: UpperCamelCase__ = self.find_set(elem_ref.parent.data ) return elem_ref.parent def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: # helper function for union operation if nodea.rank > nodea.rank: UpperCamelCase__ = nodea else: UpperCamelCase__ = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: # merge 2 disjoint sets self.link(self.find_set(snake_case_ ) , self.find_set(snake_case_ ) ) class __lowerCamelCase ( Generic[T] ): def __init__( self ) -> None: # connections: map from the node to the neighbouring nodes (with weights) UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: # add a node ONLY if its not present in the graph if node not in self.connections: UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> None: # add an edge with the given weight self.add_node(snake_case_ ) self.add_node(snake_case_ ) UpperCamelCase__ = weight UpperCamelCase__ = weight def SCREAMING_SNAKE_CASE__ ( self ) -> GraphUndirectedWeighted[T]: UpperCamelCase__ = [] UpperCamelCase__ = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda snake_case_ : x[2] ) # creating the disjoint set UpperCamelCase__ = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(snake_case_ ) # MST generation UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = edges[index] index += 1 UpperCamelCase__ = disjoint_set.find_set(snake_case_ ) UpperCamelCase__ = disjoint_set.find_set(snake_case_ ) if parent_u != parent_v: num_edges += 1 graph.add_edge(snake_case_ , snake_case_ , snake_case_ ) disjoint_set.union(snake_case_ , snake_case_ ) return graph
20
0
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None ) -> None: """simple docstring""" if start is None: UpperCamelCase__ = 0 if end is None: UpperCamelCase__ = len(__snake_case ) - 1 if start >= end: return UpperCamelCase__ = (start + end) // 2 slowsort(__snake_case , __snake_case , __snake_case ) slowsort(__snake_case , mid + 1 , __snake_case ) if sequence[end] < sequence[mid]: UpperCamelCase__ , UpperCamelCase__ = sequence[mid], sequence[end] slowsort(__snake_case , __snake_case , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
706
"""simple docstring""" A__ : Tuple= """Alexander Joslin""" import operator as op from .stack import Stack def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} UpperCamelCase__ = Stack() UpperCamelCase__ = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(SCREAMING_SNAKE_CASE ) ) elif i in operators: # RULE 2 operator_stack.push(SCREAMING_SNAKE_CASE ) elif i == ")": # RULE 4 UpperCamelCase__ = operator_stack.peek() operator_stack.pop() UpperCamelCase__ = operand_stack.peek() operand_stack.pop() UpperCamelCase__ = operand_stack.peek() operand_stack.pop() UpperCamelCase__ = operators[opr](SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) operand_stack.push(SCREAMING_SNAKE_CASE ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": A__ : int= """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
20
0
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = AutoImageProcessor.from_pretrained('microsoft/dit-base-finetuned-rvlcdip' ) UpperCamelCase__ = AutoModelForImageClassification.from_pretrained('microsoft/dit-base-finetuned-rvlcdip' ) model.to(lowercase_ ) from datasets import load_dataset UpperCamelCase__ = load_dataset('nielsr/rvlcdip-demo' ) UpperCamelCase__ = dataset["""train"""][0]["""image"""].convert('RGB' ) UpperCamelCase__ = image_processor(lowercase_ , return_tensors='pt' ).to(lowercase_ ) # forward pass with torch.no_grad(): UpperCamelCase__ = model(**lowercase_ ) UpperCamelCase__ = outputs.logits UpperCamelCase__ = torch.Size((1, 16) ) self.assertEqual(logits.shape , lowercase_ ) UpperCamelCase__ = torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=lowercase_ , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , lowercase_ , atol=1E-4 ) )
707
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py A__ : Any= """src/diffusers""" # Matches is_xxx_available() A__ : Tuple= re.compile(r"""is\_([a-z_]*)_available\(\)""") # Matches from xxx import bla A__ : Any= re.compile(r"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""") A__ : Optional[Any]= """ {0} = None """ A__ : List[Any]= """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) """ A__ : Dict= """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ = _re_backend.findall(SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) == 0: return None return "_and_".join(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( ) -> str: """simple docstring""" with open(os.path.join(SCREAMING_SNAKE_CASE , '__init__.py' ) , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.readlines() # Get to the point we do the actual imports for type checking UpperCamelCase__ = 0 UpperCamelCase__ = {} # Go through the end of the file while line_index < len(SCREAMING_SNAKE_CASE ): # If the line contains is_backend_available, we grab all objects associated with the `else` block UpperCamelCase__ = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('else:' ): line_index += 1 line_index += 1 UpperCamelCase__ = [] # Until we unindent, add backend objects to the list while line_index < len(SCREAMING_SNAKE_CASE ) and len(lines[line_index] ) > 1: UpperCamelCase__ = lines[line_index] UpperCamelCase__ = _re_single_line_import.search(SCREAMING_SNAKE_CASE ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(SCREAMING_SNAKE_CASE ) > 0: UpperCamelCase__ = objects else: line_index += 1 return backend_specific_objects def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if name.isupper(): return DUMMY_CONSTANT.format(SCREAMING_SNAKE_CASE ) elif name.islower(): return DUMMY_FUNCTION.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: return DUMMY_CLASS.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" if backend_specific_objects is None: UpperCamelCase__ = read_init() # For special correspondence backend to module name as used in the function requires_modulename UpperCamelCase__ = {} for backend, objects in backend_specific_objects.items(): UpperCamelCase__ = '[' + ', '.join(F'"{b}"' for b in backend.split('_and_' ) ) + ']' UpperCamelCase__ = '# This file is autogenerated by the command `make fix-copies`, do not edit.\n' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for o in objects] ) UpperCamelCase__ = dummy_file return dummy_files def lowerCAmelCase_( SCREAMING_SNAKE_CASE=False ) -> int: """simple docstring""" UpperCamelCase__ = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py UpperCamelCase__ = {'torch': 'pt'} # Locate actual dummy modules and read their content. UpperCamelCase__ = os.path.join(SCREAMING_SNAKE_CASE , 'utils' ) UpperCamelCase__ = { backend: os.path.join(SCREAMING_SNAKE_CASE , F'dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py' ) for backend in dummy_files.keys() } UpperCamelCase__ = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(SCREAMING_SNAKE_CASE ): with open(SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.read() else: UpperCamelCase__ = '' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( F'Updating diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py as the main ' '__init__ has new objects.' ) with open(dummy_file_paths[backend] , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( 'The main __init__ has objects that are not present in ' F'diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py. Run `make fix-copies` ' 'to fix this.' ) if __name__ == "__main__": A__ : Any= argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") A__ : Optional[int]= parser.parse_args() check_dummies(args.fix_and_overwrite)
20
0
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : List[str]= logging.get_logger(__name__) A__ : Union[str, Any]= { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/config.json''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/config.json''', } class __lowerCamelCase ( a__ ): a : str ="""xlnet""" a : Dict =["""mems"""] a : Optional[int] ={ """n_token""": """vocab_size""", # Backward compatibility """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , snake_case_=3_2000 , snake_case_=1024 , snake_case_=24 , snake_case_=16 , snake_case_=4096 , snake_case_="gelu" , snake_case_=True , snake_case_="bi" , snake_case_=0.02 , snake_case_=1E-12 , snake_case_=0.1 , snake_case_=512 , snake_case_=None , snake_case_=True , snake_case_=False , snake_case_=False , snake_case_=-1 , snake_case_=False , snake_case_="last" , snake_case_=True , snake_case_="tanh" , snake_case_=0.1 , snake_case_=5 , snake_case_=5 , snake_case_=5 , snake_case_=1 , snake_case_=2 , **snake_case_ , ) -> Optional[int]: UpperCamelCase__ = vocab_size UpperCamelCase__ = d_model UpperCamelCase__ = n_layer UpperCamelCase__ = n_head if d_model % n_head != 0: raise ValueError(F'\'d_model % n_head\' ({d_model % n_head}) should be equal to 0' ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( F'`d_head` ({kwargs["d_head"]}) should be equal to `d_model // n_head` ({d_model // n_head})' ) UpperCamelCase__ = d_model // n_head UpperCamelCase__ = ff_activation UpperCamelCase__ = d_inner UpperCamelCase__ = untie_r UpperCamelCase__ = attn_type UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = dropout UpperCamelCase__ = mem_len UpperCamelCase__ = reuse_len UpperCamelCase__ = bi_data UpperCamelCase__ = clamp_len UpperCamelCase__ = same_length UpperCamelCase__ = summary_type UpperCamelCase__ = summary_use_proj UpperCamelCase__ = summary_activation UpperCamelCase__ = summary_last_dropout UpperCamelCase__ = start_n_top UpperCamelCase__ = end_n_top UpperCamelCase__ = bos_token_id UpperCamelCase__ = pad_token_id UpperCamelCase__ = eos_token_id if "use_cache" in kwargs: warnings.warn( 'The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`' ' instead.' , lowerCAmelCase__ , ) UpperCamelCase__ = kwargs["use_cache"] UpperCamelCase__ = use_mems_eval UpperCamelCase__ = use_mems_train super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: logger.info(F'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: # Message copied from Transformer-XL documentation raise NotImplementedError( F'The model {self.model_type} is one of the few models that has no sequence length limit.' )
708
"""simple docstring""" # Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file A__ : Optional[Any]= """Run commands across TPU VMs for initial setup before running `accelerate launch`.""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> Dict: """simple docstring""" if subparsers is not None: UpperCamelCase__ = subparsers.add_parser('tpu-config' , description=_description ) else: UpperCamelCase__ = argparse.ArgumentParser('Accelerate tpu-config command' , description=_description ) # Core arguments UpperCamelCase__ = parser.add_argument_group( 'Config Arguments' , 'Arguments that can be configured through `accelerate config`.' ) config_args.add_argument( '--config_file' , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , help='Path to the config file to use for accelerate.' , ) config_args.add_argument( '--tpu_name' , default=SCREAMING_SNAKE_CASE , help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.' , ) config_args.add_argument( '--tpu_zone' , default=SCREAMING_SNAKE_CASE , help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.' , ) UpperCamelCase__ = parser.add_argument_group('TPU Arguments' , 'Arguments for options ran inside the TPU.' ) pod_args.add_argument( '--use_alpha' , action='store_true' , help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.' , ) pod_args.add_argument( '--command_file' , default=SCREAMING_SNAKE_CASE , help='The path to the file containing the commands to run on the pod on startup.' , ) pod_args.add_argument( '--command' , action='append' , nargs='+' , help='A command to run on the pod. Can be passed multiple times.' , ) pod_args.add_argument( '--install_accelerate' , action='store_true' , help='Whether to install accelerate on the pod. Defaults to False.' , ) pod_args.add_argument( '--accelerate_version' , default='latest' , help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.' , ) pod_args.add_argument( '--debug' , action='store_true' , help='If set, will print the command that would be run instead of running it.' ) if subparsers is not None: parser.set_defaults(func=SCREAMING_SNAKE_CASE ) return parser def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase__ = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: UpperCamelCase__ = defaults.command_file if not args.command and defaults.commands is not None: UpperCamelCase__ = defaults.commands if not args.tpu_name: UpperCamelCase__ = defaults.tpu_name if not args.tpu_zone: UpperCamelCase__ = defaults.tpu_zone if args.accelerate_version == "dev": UpperCamelCase__ = 'git+https://github.com/huggingface/accelerate.git' elif args.accelerate_version == "latest": UpperCamelCase__ = 'accelerate -U' elif isinstance(parse(args.accelerate_version ) , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = F'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError('You must specify either a command file or a command to run on the pod.' ) if args.command_file: with open(args.command_file , 'r' ) as f: UpperCamelCase__ = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate UpperCamelCase__ = ['cd /usr/share'] if args.install_accelerate: new_cmd += [F'pip install {args.accelerate_version}'] new_cmd += args.command UpperCamelCase__ = '; '.join(SCREAMING_SNAKE_CASE ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess UpperCamelCase__ = ['gcloud'] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'Running {" ".join(SCREAMING_SNAKE_CASE )}' ) return subprocess.run(SCREAMING_SNAKE_CASE ) print('Successfully setup pod.' ) def lowerCAmelCase_( ) -> int: """simple docstring""" UpperCamelCase__ = tpu_command_parser() UpperCamelCase__ = parser.parse_args() tpu_command_launcher(SCREAMING_SNAKE_CASE )
20
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Dict= logging.get_logger(__name__) A__ : List[str]= { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class __lowerCamelCase ( UpperCAmelCase__ ): a : List[str] ="""roc_bert""" def __init__( self , snake_case_=3_0522 , snake_case_=768 , snake_case_=12 , snake_case_=12 , snake_case_=3072 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=2 , snake_case_=0.02 , snake_case_=1E-12 , snake_case_=True , snake_case_=0 , snake_case_="absolute" , snake_case_=None , snake_case_=True , snake_case_=True , snake_case_=768 , snake_case_=910 , snake_case_=512 , snake_case_=2_4858 , snake_case_=True , **snake_case_ , ) -> List[str]: UpperCamelCase__ = vocab_size UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = initializer_range UpperCamelCase__ = type_vocab_size UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = use_cache UpperCamelCase__ = enable_pronunciation UpperCamelCase__ = enable_shape UpperCamelCase__ = pronunciation_embed_dim UpperCamelCase__ = pronunciation_vocab_size UpperCamelCase__ = shape_embed_dim UpperCamelCase__ = shape_vocab_size UpperCamelCase__ = concat_input UpperCamelCase__ = position_embedding_type UpperCamelCase__ = classifier_dropout super().__init__(pad_token_id=__lowerCAmelCase , **__lowerCAmelCase )
709
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : List[str]= logging.get_logger(__name__) class __lowerCamelCase ( _a ): a : Optional[int] ="""timm_backbone""" def __init__( self , snake_case_=None , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=None , **snake_case_ , ) -> Dict: super().__init__(**snake_case_ ) UpperCamelCase__ = backbone UpperCamelCase__ = num_channels UpperCamelCase__ = features_only UpperCamelCase__ = use_pretrained_backbone UpperCamelCase__ = True UpperCamelCase__ = out_indices if out_indices is not None else (-1,)
20
0
"""simple docstring""" import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = '| <pad> <unk> <s> </s> a b c d e f g h i j k'.split() UpperCamelCase__ = dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_ ) ) ) ) UpperCamelCase__ = { 'unk_token': '<unk>', 'bos_token': '<s>', 'eos_token': '</s>', } UpperCamelCase__ = { 'feature_size': 1, 'padding_value': 0.0, 'sampling_rate': 1_6000, 'return_attention_mask': False, 'do_normalize': True, } UpperCamelCase__ = tempfile.mkdtemp() UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase__ = os.path.join(self.tmpdirname , UpperCAmelCase_ ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(UpperCAmelCase_ ) + '\n' ) with open(self.feature_extraction_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(UpperCAmelCase_ ) + '\n' ) # load decoder from hub UpperCamelCase__ = 'hf-internal-testing/ngram-beam-search-decoder' def SCREAMING_SNAKE_CASE__ ( self , **snake_case_ ) -> int: UpperCamelCase__ = self.add_kwargs_tokens_map.copy() kwargs.update(UpperCAmelCase_ ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self , **snake_case_ ) -> Union[str, Any]: return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self , **snake_case_ ) -> List[str]: return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_feature_extractor() UpperCamelCase__ = self.get_decoder() UpperCamelCase__ = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase__ = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase_ ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , UpperCAmelCase_ ) # decoder self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , ) self.assertIsInstance(processor.decoder , UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match UpperCamelCase__ = WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha , 5.0 ) self.assertEqual(processor.language_model.beta , 3.0 ) self.assertEqual(processor.language_model.score_boundary , -7.0 ) self.assertEqual(processor.language_model.unk_score_offset , 3 ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(['xx'] ) with self.assertRaisesRegex(UpperCAmelCase_ , 'include' ): WavaVecaProcessorWithLM( tokenizer=UpperCAmelCase_ , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = self.get_feature_extractor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_decoder() UpperCamelCase__ = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) UpperCamelCase__ = floats_list((3, 1000) ) UpperCamelCase__ = feature_extractor(UpperCAmelCase_ , return_tensors='np' ) UpperCamelCase__ = processor(UpperCAmelCase_ , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.get_feature_extractor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_decoder() UpperCamelCase__ = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) UpperCamelCase__ = 'This is a test string' UpperCamelCase__ = processor(text=UpperCAmelCase_ ) UpperCamelCase__ = tokenizer(UpperCAmelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_=(2, 10, 16) , snake_case_=77 ) -> int: np.random.seed(UpperCAmelCase_ ) return np.random.rand(*UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.get_feature_extractor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_decoder() UpperCamelCase__ = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) UpperCamelCase__ = self._get_dummy_logits(shape=(10, 16) , seed=13 ) UpperCamelCase__ = processor.decode(UpperCAmelCase_ ) UpperCamelCase__ = decoder.decode_beams(UpperCAmelCase_ )[0] self.assertEqual(decoded_decoder[0] , decoded_processor.text ) self.assertEqual('</s> <s> </s>' , decoded_processor.text ) self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score ) @parameterized.expand([[None], ['fork'], ['spawn']] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: UpperCamelCase__ = self.get_feature_extractor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_decoder() UpperCamelCase__ = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) UpperCamelCase__ = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: UpperCamelCase__ = processor.batch_decode(UpperCAmelCase_ ) else: with get_context(UpperCAmelCase_ ).Pool() as pool: UpperCamelCase__ = processor.batch_decode(UpperCAmelCase_ , UpperCAmelCase_ ) UpperCamelCase__ = list(UpperCAmelCase_ ) with get_context('fork' ).Pool() as p: UpperCamelCase__ = decoder.decode_beams_batch(UpperCAmelCase_ , UpperCAmelCase_ ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = [], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(UpperCAmelCase_ , decoded_processor.text ) self.assertListEqual(['<s> <s> </s>', '<s> <s> <s>'] , decoded_processor.text ) self.assertListEqual(UpperCAmelCase_ , decoded_processor.logit_score ) self.assertListEqual(UpperCAmelCase_ , decoded_processor.lm_score ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.get_feature_extractor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_decoder() UpperCamelCase__ = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) UpperCamelCase__ = self._get_dummy_logits() UpperCamelCase__ = 15 UpperCamelCase__ = -20.0 UpperCamelCase__ = -4.0 UpperCamelCase__ = processor.batch_decode( UpperCAmelCase_ , beam_width=UpperCAmelCase_ , beam_prune_logp=UpperCAmelCase_ , token_min_logp=UpperCAmelCase_ , ) UpperCamelCase__ = decoded_processor_out.text UpperCamelCase__ = list(UpperCAmelCase_ ) with get_context('fork' ).Pool() as pool: UpperCamelCase__ = decoder.decode_beams_batch( UpperCAmelCase_ , UpperCAmelCase_ , beam_width=UpperCAmelCase_ , beam_prune_logp=UpperCAmelCase_ , token_min_logp=UpperCAmelCase_ , ) UpperCamelCase__ = [d[0][0] for d in decoded_decoder_out] UpperCamelCase__ = [d[0][2] for d in decoded_decoder_out] UpperCamelCase__ = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertListEqual(['</s> <s> <s>', '<s> <s> <s>'] , UpperCAmelCase_ ) self.assertTrue(np.array_equal(UpperCAmelCase_ , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.054, -18.447] , UpperCAmelCase_ , atol=1E-3 ) ) self.assertTrue(np.array_equal(UpperCAmelCase_ , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.554, -13.9_474] , UpperCAmelCase_ , atol=1E-3 ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.get_feature_extractor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_decoder() UpperCamelCase__ = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) UpperCamelCase__ = self._get_dummy_logits() UpperCamelCase__ = 2.0 UpperCamelCase__ = 5.0 UpperCamelCase__ = -20.0 UpperCamelCase__ = True UpperCamelCase__ = processor.batch_decode( UpperCAmelCase_ , alpha=UpperCAmelCase_ , beta=UpperCAmelCase_ , unk_score_offset=UpperCAmelCase_ , lm_score_boundary=UpperCAmelCase_ , ) UpperCamelCase__ = decoded_processor_out.text UpperCamelCase__ = list(UpperCAmelCase_ ) decoder.reset_params( alpha=UpperCAmelCase_ , beta=UpperCAmelCase_ , unk_score_offset=UpperCAmelCase_ , lm_score_boundary=UpperCAmelCase_ , ) with get_context('fork' ).Pool() as pool: UpperCamelCase__ = decoder.decode_beams_batch( UpperCAmelCase_ , UpperCAmelCase_ , ) UpperCamelCase__ = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertListEqual(['<s> </s> <s> </s> </s>', '</s> </s> <s> </s> </s>'] , UpperCAmelCase_ ) UpperCamelCase__ = processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha , 2.0 ) self.assertEqual(lm_model.beta , 5.0 ) self.assertEqual(lm_model.unk_score_offset , -20.0 ) self.assertEqual(lm_model.score_boundary , UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = WavaVecaProcessorWithLM.from_pretrained('hf-internal-testing/processor_with_lm' ) UpperCamelCase__ = processor.decoder.model_container[processor.decoder._model_key] UpperCamelCase__ = Path(language_model._kenlm_model.path.decode('utf-8' ) ).parent.parent.absolute() UpperCamelCase__ = os.listdir(UpperCAmelCase_ ) UpperCamelCase__ = ['alphabet.json', 'language_model'] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = snapshot_download('hf-internal-testing/processor_with_lm' ) UpperCamelCase__ = WavaVecaProcessorWithLM.from_pretrained(UpperCAmelCase_ ) UpperCamelCase__ = processor.decoder.model_container[processor.decoder._model_key] UpperCamelCase__ = Path(language_model._kenlm_model.path.decode('utf-8' ) ).parent.parent.absolute() UpperCamelCase__ = os.listdir(UpperCAmelCase_ ) UpperCamelCase__ = os.listdir(UpperCAmelCase_ ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = WavaVecaProcessorWithLM.from_pretrained('hf-internal-testing/processor_with_lm' ) UpperCamelCase__ = AutoProcessor.from_pretrained('hf-internal-testing/processor_with_lm' ) UpperCamelCase__ = floats_list((3, 1000) ) UpperCamelCase__ = processor_wavaveca(UpperCAmelCase_ , return_tensors='np' ) UpperCamelCase__ = processor_auto(UpperCAmelCase_ , return_tensors='np' ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1E-2 ) UpperCamelCase__ = self._get_dummy_logits() UpperCamelCase__ = processor_wavaveca.batch_decode(UpperCAmelCase_ ) UpperCamelCase__ = processor_auto.batch_decode(UpperCAmelCase_ ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.get_feature_extractor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_decoder() UpperCamelCase__ = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , ) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ , snake_case_ ) -> Union[str, Any]: UpperCamelCase__ = [d[key] for d in offsets] return retrieved_list def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = WavaVecaProcessorWithLM.from_pretrained('hf-internal-testing/processor_with_lm' ) UpperCamelCase__ = self._get_dummy_logits()[0] UpperCamelCase__ = processor.decode(UpperCAmelCase_ , output_word_offsets=UpperCAmelCase_ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue('text' in outputs ) self.assertTrue('word_offsets' in outputs ) self.assertTrue(isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertEqual(' '.join(self.get_from_offsets(outputs['word_offsets'] , 'word' ) ) , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs['word_offsets'] , 'word' ) , ['<s>', '<s>', '</s>'] ) self.assertListEqual(self.get_from_offsets(outputs['word_offsets'] , 'start_offset' ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs['word_offsets'] , 'end_offset' ) , [1, 3, 5] ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = WavaVecaProcessorWithLM.from_pretrained('hf-internal-testing/processor_with_lm' ) UpperCamelCase__ = self._get_dummy_logits() UpperCamelCase__ = processor.batch_decode(UpperCAmelCase_ , output_word_offsets=UpperCAmelCase_ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue('text' in outputs ) self.assertTrue('word_offsets' in outputs ) self.assertTrue(isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertListEqual( [' '.join(self.get_from_offsets(UpperCAmelCase_ , 'word' ) ) for o in outputs['word_offsets']] , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs['word_offsets'][0] , 'word' ) , ['<s>', '<s>', '</s>'] ) self.assertListEqual(self.get_from_offsets(outputs['word_offsets'][0] , 'start_offset' ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs['word_offsets'][0] , 'end_offset' ) , [1, 3, 5] ) @slow @require_torch @require_torchaudio def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: import torch UpperCamelCase__ = load_dataset('common_voice' , 'en' , split='train' , streaming=UpperCAmelCase_ ) UpperCamelCase__ = ds.cast_column('audio' , datasets.Audio(sampling_rate=1_6000 ) ) UpperCamelCase__ = iter(UpperCAmelCase_ ) UpperCamelCase__ = next(UpperCAmelCase_ ) UpperCamelCase__ = AutoProcessor.from_pretrained('patrickvonplaten/wav2vec2-base-100h-with-lm' ) UpperCamelCase__ = WavaVecaForCTC.from_pretrained('patrickvonplaten/wav2vec2-base-100h-with-lm' ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train UpperCamelCase__ = processor(sample['audio']['array'] , return_tensors='pt' ).input_values with torch.no_grad(): UpperCamelCase__ = model(UpperCAmelCase_ ).logits.cpu().numpy() UpperCamelCase__ = processor.decode(logits[0] , output_word_offsets=UpperCAmelCase_ ) UpperCamelCase__ = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate UpperCamelCase__ = [ { 'start_time': d['start_offset'] * time_offset, 'end_time': d['end_offset'] * time_offset, 'word': d['word'], } for d in output['word_offsets'] ] UpperCamelCase__ = 'WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL' # output words self.assertEqual(' '.join(self.get_from_offsets(UpperCAmelCase_ , 'word' ) ) , UpperCAmelCase_ ) self.assertEqual(' '.join(self.get_from_offsets(UpperCAmelCase_ , 'word' ) ) , output.text ) # output times UpperCamelCase__ = torch.tensor(self.get_from_offsets(UpperCAmelCase_ , 'start_time' ) ) UpperCamelCase__ = torch.tensor(self.get_from_offsets(UpperCAmelCase_ , 'end_time' ) ) # fmt: off UpperCamelCase__ = torch.tensor([1.4_199, 1.6_599, 2.2_599, 3.0, 3.24, 3.5_999, 3.7_999, 4.0_999, 4.26, 4.94, 5.28, 5.6_599, 5.78, 5.94, 6.32, 6.5_399, 6.6_599] ) UpperCamelCase__ = torch.tensor([1.5_399, 1.8_999, 2.9, 3.16, 3.5_399, 3.72, 4.0_199, 4.1_799, 4.76, 5.1_599, 5.5_599, 5.6_999, 5.86, 6.1_999, 6.38, 6.6_199, 6.94] ) # fmt: on self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=0.01 ) ) self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=0.01 ) )
710
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType A__ : Any= logging.get_logger(__name__) A__ : str= { """microsoft/layoutlmv3-base""": """https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json""", } class __lowerCamelCase ( _a ): a : List[str] ="""layoutlmv3""" def __init__( self , snake_case_=5_0265 , snake_case_=768 , snake_case_=12 , snake_case_=12 , snake_case_=3072 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=2 , snake_case_=0.02 , snake_case_=1E-5 , snake_case_=1 , snake_case_=0 , snake_case_=2 , snake_case_=1024 , snake_case_=128 , snake_case_=128 , snake_case_=True , snake_case_=32 , snake_case_=128 , snake_case_=64 , snake_case_=256 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=224 , snake_case_=3 , snake_case_=16 , snake_case_=None , **snake_case_ , ) -> Union[str, Any]: super().__init__( vocab_size=snake_case_ , hidden_size=snake_case_ , num_hidden_layers=snake_case_ , num_attention_heads=snake_case_ , intermediate_size=snake_case_ , hidden_act=snake_case_ , hidden_dropout_prob=snake_case_ , attention_probs_dropout_prob=snake_case_ , max_position_embeddings=snake_case_ , type_vocab_size=snake_case_ , initializer_range=snake_case_ , layer_norm_eps=snake_case_ , pad_token_id=snake_case_ , bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ , ) UpperCamelCase__ = max_ad_position_embeddings UpperCamelCase__ = coordinate_size UpperCamelCase__ = shape_size UpperCamelCase__ = has_relative_attention_bias UpperCamelCase__ = rel_pos_bins UpperCamelCase__ = max_rel_pos UpperCamelCase__ = has_spatial_attention_bias UpperCamelCase__ = rel_ad_pos_bins UpperCamelCase__ = max_rel_ad_pos UpperCamelCase__ = text_embed UpperCamelCase__ = visual_embed UpperCamelCase__ = input_size UpperCamelCase__ = num_channels UpperCamelCase__ = patch_size UpperCamelCase__ = classifier_dropout class __lowerCamelCase ( _a ): a : Tuple =version.parse("""1.12""" ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) else: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels'}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: return 12 def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , snake_case_ = 3 , snake_case_ = 40 , snake_case_ = 40 , ) -> Mapping[str, Any]: setattr(processor.image_processor , 'apply_ocr' , snake_case_ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase__ = processor.tokenizer.num_special_tokens_to_add(snake_case_ ) UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case_ ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase__ = [[' '.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes UpperCamelCase__ = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) UpperCamelCase__ = self._generate_dummy_images(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) UpperCamelCase__ = dict( processor( snake_case_ , text=snake_case_ , boxes=snake_case_ , return_tensors=snake_case_ , ) ) return inputs
20
0
"""simple docstring""" from __future__ import annotations class __lowerCamelCase : def __init__( self , snake_case_ ) -> int: UpperCamelCase__ = data UpperCamelCase__ = None UpperCamelCase__ = None def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[Any]: # In Order traversal of the tree """simple docstring""" if tree: display(tree.left ) print(tree.data ) display(tree.right ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def lowerCAmelCase_( ) -> Any: # Main function for testing. """simple docstring""" UpperCamelCase__ = Node(1 ) UpperCamelCase__ = Node(2 ) UpperCamelCase__ = Node(3 ) UpperCamelCase__ = Node(4 ) UpperCamelCase__ = Node(5 ) UpperCamelCase__ = Node(6 ) UpperCamelCase__ = Node(7 ) UpperCamelCase__ = Node(8 ) UpperCamelCase__ = Node(9 ) print(is_full_binary_tree(_lowercase ) ) print(depth_of_tree(_lowercase ) ) print('Tree is: ' ) display(_lowercase ) if __name__ == "__main__": main()
711
"""simple docstring""" from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class __lowerCamelCase : def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=2 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> Tuple: UpperCamelCase__ = parent UpperCamelCase__ = 13 UpperCamelCase__ = 7 UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = 99 UpperCamelCase__ = 384 UpperCamelCase__ = 2 UpperCamelCase__ = 4 UpperCamelCase__ = 37 UpperCamelCase__ = 'gelu' UpperCamelCase__ = 0.1 UpperCamelCase__ = 0.1 UpperCamelCase__ = 512 UpperCamelCase__ = 16 UpperCamelCase__ = 2 UpperCamelCase__ = 0.02 UpperCamelCase__ = 3 UpperCamelCase__ = 4 UpperCamelCase__ = 128 UpperCamelCase__ = 2 UpperCamelCase__ = 9 UpperCamelCase__ = 1 UpperCamelCase__ = None def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=snake_case_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertModel(config=snake_case_ ) UpperCamelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} UpperCamelCase__ = [input_ids, input_mask] UpperCamelCase__ = model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertForMaskedLM(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForSequenceClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = self.num_choices UpperCamelCase__ = TFConvBertForMultipleChoice(config=snake_case_ ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForTokenClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = TFConvBertForQuestionAnswering(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class __lowerCamelCase ( _a , _a , unittest.TestCase ): a : Any =( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) a : str =( { """feature-extraction""": TFConvBertModel, """fill-mask""": TFConvBertForMaskedLM, """question-answering""": TFConvBertForQuestionAnswering, """text-classification""": TFConvBertForSequenceClassification, """token-classification""": TFConvBertForTokenClassification, """zero-shot""": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) a : Any =False a : Dict =False a : str =False def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = TFConvBertModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = True if hasattr(snake_case_ , 'use_cache' ): UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) for model_class in self.all_model_classes: UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ ) UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = len(model(snake_case_ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(snake_case_ , saved_model=snake_case_ ) UpperCamelCase__ = os.path.join(snake_case_ , 'saved_model' , '1' ) UpperCamelCase__ = tf.keras.models.load_model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = outputs['encoder_hidden_states'] UpperCamelCase__ = outputs['encoder_attentions'] else: UpperCamelCase__ = outputs['hidden_states'] UpperCamelCase__ = outputs['attentions'] self.assertEqual(len(snake_case_ ) , snake_case_ ) UpperCamelCase__ = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(snake_case_ ) , snake_case_ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) def check_decoder_attentions_output(snake_case_ ): UpperCamelCase__ = len(snake_case_ ) self.assertEqual(out_len % 2 , 0 ) UpperCamelCase__ = outputs.decoder_attentions self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(snake_case_ ): UpperCamelCase__ = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: UpperCamelCase__ = True UpperCamelCase__ = False UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) UpperCamelCase__ = len(snake_case_ ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_decoder_attentions_output(snake_case_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) # Check attention is always last and order is fine UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(snake_case_ ) ) self.assertEqual(model.config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) @require_tf class __lowerCamelCase ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) UpperCamelCase__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase__ = model(snake_case_ )[0] UpperCamelCase__ = [1, 6, 768] self.assertEqual(output.shape , snake_case_ ) UpperCamelCase__ = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , snake_case_ , atol=1E-4 )
20
0
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
712
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 1_00_00_00 , SCREAMING_SNAKE_CASE = 10 ) -> int: """simple docstring""" UpperCamelCase__ = defaultdict(SCREAMING_SNAKE_CASE ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: UpperCamelCase__ = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: UpperCamelCase__ = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(SCREAMING_SNAKE_CASE , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"""{solution() = }""")
20
0
def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 1_00 ) -> Tuple: """simple docstring""" UpperCamelCase__ = 0 UpperCamelCase__ = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(F"""{solution() = }""")
713
"""simple docstring""" import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __lowerCamelCase ( unittest.TestCase ): def __init__( self , snake_case_ , snake_case_=100 , snake_case_=13 , snake_case_=30 , snake_case_=2 , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=10 , snake_case_=0.02 , snake_case_=3 , ) -> Optional[int]: UpperCamelCase__ = parent UpperCamelCase__ = vocab_size UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = patch_size UpperCamelCase__ = num_channels UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCamelCase__ = (image_size // patch_size) ** 2 UpperCamelCase__ = num_patches + 1 def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=snake_case_ , initializer_range=self.initializer_range , ) return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = FlaxBeitModel(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = FlaxBeitForMaskedImageModeling(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.type_sequence_label_size UpperCamelCase__ = FlaxBeitForImageClassification(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase__ = 1 UpperCamelCase__ = FlaxBeitForImageClassification(snake_case_ ) UpperCamelCase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase__ = model(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class __lowerCamelCase ( _a , unittest.TestCase ): a : int =( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE__ ( self ) -> None: UpperCamelCase__ = FlaxBeitModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ['pixel_values'] self.assertListEqual(arg_names[:1] , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ ) UpperCamelCase__ = model_class(snake_case_ ) @jax.jit def model_jitted(snake_case_ , **snake_case_ ): return model(pixel_values=snake_case_ , **snake_case_ ) with self.subTest('JIT Enabled' ): UpperCamelCase__ = model_jitted(**snake_case_ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): UpperCamelCase__ = model_jitted(**snake_case_ ).to_tuple() self.assertEqual(len(snake_case_ ) , len(snake_case_ ) ) for jitted_output, output in zip(snake_case_ , snake_case_ ): self.assertEqual(jitted_output.shape , output.shape ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: for model_class_name in self.all_model_classes: UpperCamelCase__ = model_class_name.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase__ = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(snake_case_ ) def lowerCAmelCase_( ) -> Optional[int]: """simple docstring""" UpperCamelCase__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @require_flax class __lowerCamelCase ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = FlaxBeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ).pixel_values # prepare bool_masked_pos UpperCamelCase__ = np.ones((1, 196) , dtype=snake_case_ ) # forward pass UpperCamelCase__ = model(pixel_values=snake_case_ , bool_masked_pos=snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 196, 8192) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , snake_case_ , atol=1E-2 ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ) # forward pass UpperCamelCase__ = model(**snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 1000) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array([-1.2_385, -1.0_987, -1.0_108] ) self.assertTrue(np.allclose(logits[0, :3] , snake_case_ , atol=1E-4 ) ) UpperCamelCase__ = 281 self.assertEqual(logits.argmax(-1 ).item() , snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ) # forward pass UpperCamelCase__ = model(**snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 2_1841) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array([1.6_881, -0.2_787, 0.5_901] ) self.assertTrue(np.allclose(logits[0, :3] , snake_case_ , atol=1E-4 ) ) UpperCamelCase__ = 2396 self.assertEqual(logits.argmax(-1 ).item() , snake_case_ )
20
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class __lowerCamelCase ( metaclass=lowercase__ ): a : Union[str, Any] =["""speech"""] def __init__( self , *snake_case_ , **snake_case_ ) -> str: requires_backends(self , ['speech'] ) class __lowerCamelCase ( metaclass=lowercase__ ): a : Optional[Any] =["""speech"""] def __init__( self , *snake_case_ , **snake_case_ ) -> int: requires_backends(self , ['speech'] )
714
"""simple docstring""" import sys from collections import defaultdict class __lowerCamelCase : def __init__( self ) -> Tuple: UpperCamelCase__ = [] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: return self.node_position[vertex] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Optional[int]: UpperCamelCase__ = pos def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: UpperCamelCase__ = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: UpperCamelCase__ = 2 * start + 1 else: UpperCamelCase__ = 2 * start + 2 if heap[smallest_child] < heap[start]: UpperCamelCase__ , UpperCamelCase__ = heap[smallest_child], positions[smallest_child] UpperCamelCase__ , UpperCamelCase__ = ( heap[start], positions[start], ) UpperCamelCase__ , UpperCamelCase__ = temp, tempa UpperCamelCase__ = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , snake_case_ ) self.top_to_bottom(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Any: UpperCamelCase__ = position[index] while index != 0: UpperCamelCase__ = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: UpperCamelCase__ = heap[parent] UpperCamelCase__ = position[parent] self.set_position(position[parent] , snake_case_ ) else: UpperCamelCase__ = val UpperCamelCase__ = temp self.set_position(snake_case_ , snake_case_ ) break UpperCamelCase__ = parent else: UpperCamelCase__ = val UpperCamelCase__ = temp self.set_position(snake_case_ , 0 ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Any: UpperCamelCase__ = len(snake_case_ ) // 2 - 1 for i in range(snake_case_ , -1 , -1 ): self.top_to_bottom(snake_case_ , snake_case_ , len(snake_case_ ) , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = positions[0] UpperCamelCase__ = sys.maxsize self.top_to_bottom(snake_case_ , 0 , len(snake_case_ ) , snake_case_ ) return temp def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = Heap() UpperCamelCase__ = [0] * len(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = [-1] * len(SCREAMING_SNAKE_CASE ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph UpperCamelCase__ = [] # Heap of Distance of vertices from their neighboring vertex UpperCamelCase__ = [] for vertex in range(len(SCREAMING_SNAKE_CASE ) ): distance_tv.append(sys.maxsize ) positions.append(SCREAMING_SNAKE_CASE ) heap.node_position.append(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = [] UpperCamelCase__ = 1 UpperCamelCase__ = sys.maxsize for neighbor, distance in adjacency_list[0]: UpperCamelCase__ = 0 UpperCamelCase__ = distance heap.heapify(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for _ in range(1 , len(SCREAMING_SNAKE_CASE ) ): UpperCamelCase__ = heap.delete_minimum(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) UpperCamelCase__ = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(SCREAMING_SNAKE_CASE )] ): UpperCamelCase__ = distance heap.bottom_to_top( SCREAMING_SNAKE_CASE , heap.get_position(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A__ : Dict= int(input("""Enter number of edges: """).strip()) A__ : Dict= defaultdict(list) for _ in range(edges_number): A__ : Dict= [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
20
0
"""simple docstring""" from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput A__ : List[Any]= 8 def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=BITS ) -> Optional[Any]: """simple docstring""" UpperCamelCase__ = x.device UpperCamelCase__ = (x * 2_55).int().clamp(0 , 2_55 ) UpperCamelCase__ = 2 ** torch.arange(bits - 1 , -1 , -1 , device=_lowerCAmelCase ) UpperCamelCase__ = rearrange(_lowerCAmelCase , 'd -> d 1 1' ) UpperCamelCase__ = rearrange(_lowerCAmelCase , 'b c h w -> b c 1 h w' ) UpperCamelCase__ = ((x & mask) != 0).float() UpperCamelCase__ = rearrange(_lowerCAmelCase , 'b c d h w -> b (c d) h w' ) UpperCamelCase__ = bits * 2 - 1 return bits def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=BITS ) -> int: """simple docstring""" UpperCamelCase__ = x.device UpperCamelCase__ = (x > 0).int() UpperCamelCase__ = 2 ** torch.arange(bits - 1 , -1 , -1 , device=_lowerCAmelCase , dtype=torch.intaa ) UpperCamelCase__ = rearrange(_lowerCAmelCase , 'd -> d 1 1' ) UpperCamelCase__ = rearrange(_lowerCAmelCase , 'b (c d) h w -> b c d h w' , d=8 ) UpperCamelCase__ = reduce(x * mask , 'b c d h w -> b c h w' , 'sum' ) return (dec / 2_55).clamp(0.0 , 1.0 ) def lowerCAmelCase_( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 0.0 , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE = True , ) -> Union[DDIMSchedulerOutput, Tuple]: """simple docstring""" if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) UpperCamelCase__ = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas UpperCamelCase__ = self.alphas_cumprod[timestep] UpperCamelCase__ = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod UpperCamelCase__ = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf UpperCamelCase__ = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" UpperCamelCase__ = self.bit_scale if self.config.clip_sample: UpperCamelCase__ = torch.clamp(_lowerCAmelCase , -scale , _lowerCAmelCase ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) UpperCamelCase__ = self._get_variance(_lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase__ = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide UpperCamelCase__ = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf UpperCamelCase__ = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf UpperCamelCase__ = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 UpperCamelCase__ = model_output.device if torch.is_tensor(_lowerCAmelCase ) else "cpu" UpperCamelCase__ = torch.randn(model_output.shape , dtype=model_output.dtype , generator=_lowerCAmelCase ).to(_lowerCAmelCase ) UpperCamelCase__ = self._get_variance(_lowerCAmelCase , _lowerCAmelCase ) ** 0.5 * eta * noise UpperCamelCase__ = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=_lowerCAmelCase , pred_original_sample=_lowerCAmelCase ) def lowerCAmelCase_( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE="epsilon" , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE = True , ) -> Union[DDPMSchedulerOutput, Tuple]: """simple docstring""" UpperCamelCase__ = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: UpperCamelCase__ = torch.split(_lowerCAmelCase , sample.shape[1] , dim=1 ) else: UpperCamelCase__ = None # 1. compute alphas, betas UpperCamelCase__ = self.alphas_cumprod[t] UpperCamelCase__ = self.alphas_cumprod[t - 1] if t > 0 else self.one UpperCamelCase__ = 1 - alpha_prod_t UpperCamelCase__ = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": UpperCamelCase__ = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": UpperCamelCase__ = model_output else: raise ValueError(F'Unsupported prediction_type {prediction_type}.' ) # 3. Clip "predicted x_0" UpperCamelCase__ = self.bit_scale if self.config.clip_sample: UpperCamelCase__ = torch.clamp(_lowerCAmelCase , -scale , _lowerCAmelCase ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCamelCase__ = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t UpperCamelCase__ = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCamelCase__ = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise UpperCamelCase__ = 0 if t > 0: UpperCamelCase__ = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=_lowerCAmelCase ).to(model_output.device ) UpperCamelCase__ = (self._get_variance(_lowerCAmelCase , predicted_variance=_lowerCAmelCase ) ** 0.5) * noise UpperCamelCase__ = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=_lowerCAmelCase , pred_original_sample=_lowerCAmelCase ) class __lowerCamelCase ( __snake_case ): def __init__( self , snake_case_ , snake_case_ , snake_case_ = 1.0 , ) -> Dict: super().__init__() UpperCamelCase__ = bit_scale UpperCamelCase__ = ( ddim_bit_scheduler_step if isinstance(A_ , A_ ) else ddpm_bit_scheduler_step ) self.register_modules(unet=A_ , scheduler=A_ ) @torch.no_grad() def __call__( self , snake_case_ = 256 , snake_case_ = 256 , snake_case_ = 50 , snake_case_ = None , snake_case_ = 1 , snake_case_ = "pil" , snake_case_ = True , **snake_case_ , ) -> Optional[int]: UpperCamelCase__ = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=A_ , ) UpperCamelCase__ = decimal_to_bits(A_ ) * self.bit_scale UpperCamelCase__ = latents.to(self.device ) self.scheduler.set_timesteps(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual UpperCamelCase__ = self.unet(A_ , A_ ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(A_ , A_ , A_ ).prev_sample UpperCamelCase__ = bits_to_decimal(A_ ) if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(A_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A_ )
715
"""simple docstring""" from copy import deepcopy class __lowerCamelCase : def __init__( self , snake_case_ = None , snake_case_ = None ) -> None: if arr is None and size is not None: UpperCamelCase__ = size UpperCamelCase__ = [0] * size elif arr is not None: self.init(snake_case_ ) else: raise ValueError('Either arr or size must be specified' ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: UpperCamelCase__ = len(snake_case_ ) UpperCamelCase__ = deepcopy(snake_case_ ) for i in range(1 , self.size ): UpperCamelCase__ = self.next_(snake_case_ ) if j < self.size: self.tree[j] += self.tree[i] def SCREAMING_SNAKE_CASE__ ( self ) -> list[int]: UpperCamelCase__ = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): UpperCamelCase__ = self.next_(snake_case_ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: return index + (index & (-index)) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: return index - (index & (-index)) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value UpperCamelCase__ = self.next_(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: self.add(snake_case_ , value - self.get(snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: if right == 0: return 0 UpperCamelCase__ = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] UpperCamelCase__ = self.prev(snake_case_ ) return result def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> int: return self.prefix(snake_case_ ) - self.prefix(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: return self.query(snake_case_ , index + 1 ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: value -= self.tree[0] if value < 0: return -1 UpperCamelCase__ = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 UpperCamelCase__ = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
20
0
"""simple docstring""" import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase__ = tmp_path / 'file.csv' UpperCamelCase__ = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20\n ' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE ) return str(SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase__ = tmp_path / 'malformed_file.csv' UpperCamelCase__ = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20,\n ' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE ) return str(SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = tmp_path / 'csv_with_image.csv' UpperCamelCase__ = textwrap.dedent( F'\\n image\n {image_file}\n ' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE ) return str(SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase__ = tmp_path / 'csv_with_label.csv' UpperCamelCase__ = textwrap.dedent( '\\n label\n good\n bad\n good\n ' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE ) return str(SCREAMING_SNAKE_CASE ) @pytest.fixture def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" UpperCamelCase__ = tmp_path / 'csv_with_int_list.csv' UpperCamelCase__ = textwrap.dedent( '\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n ' ) with open(SCREAMING_SNAKE_CASE , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE ) return str(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase__ = Csv() UpperCamelCase__ = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(SCREAMING_SNAKE_CASE , match='Error tokenizing data' ): for _ in generator: pass assert any( record.levelname == 'ERROR' and 'Failed to read file' in record.message and os.path.basename(SCREAMING_SNAKE_CASE ) in record.message for record in caplog.records ) @require_pil def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" with open(SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: UpperCamelCase__ = f.read().splitlines()[1] UpperCamelCase__ = Csv(encoding='utf-8' , features=Features({'image': Image()} ) ) UpperCamelCase__ = csv._generate_tables([[csv_file_with_image]] ) UpperCamelCase__ = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('image' ).type == Image()() UpperCamelCase__ = pa_table.to_pydict()['image'] assert generated_content == [{"path": image_file, "bytes": None}] def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" with open(SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f: UpperCamelCase__ = f.read().splitlines()[1:] UpperCamelCase__ = Csv(encoding='utf-8' , features=Features({'label': ClassLabel(names=['good', 'bad'] )} ) ) UpperCamelCase__ = csv._generate_tables([[csv_file_with_label]] ) UpperCamelCase__ = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('label' ).type == ClassLabel(names=['good', 'bad'] )() UpperCamelCase__ = pa_table.to_pydict()['label'] assert generated_content == [ClassLabel(names=['good', 'bad'] ).straint(SCREAMING_SNAKE_CASE ) for label in labels] def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase__ = Csv(encoding='utf-8' , sep=',' , converters={'int_list': lambda SCREAMING_SNAKE_CASE : [int(SCREAMING_SNAKE_CASE ) for i in x.split()]} ) UpperCamelCase__ = csv._generate_tables([[csv_file_with_int_list]] ) UpperCamelCase__ = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('int_list' ).type ) UpperCamelCase__ = pa_table.to_pydict()['int_list'] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
716
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow A__ : Union[str, Any]= logging.getLogger() @unittest.skip("""Temporarily disable the doc tests.""" ) @require_torch @require_tf @slow class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = None , snake_case_ = None , snake_case_ = True , ) -> Tuple: UpperCamelCase__ = [file for file in os.listdir(snake_case_ ) if os.path.isfile(os.path.join(snake_case_ , snake_case_ ) )] if identifier is not None: UpperCamelCase__ = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(snake_case_ , snake_case_ ): for n_ in n_identifier: UpperCamelCase__ = [file for file in files if n_ not in file] else: UpperCamelCase__ = [file for file in files if n_identifier not in file] UpperCamelCase__ = ignore_files or [] ignore_files.append('__init__.py' ) UpperCamelCase__ = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' , snake_case_ ) if only_modules: UpperCamelCase__ = file.split('.' )[0] try: UpperCamelCase__ = getattr(snake_case_ , snake_case_ ) UpperCamelCase__ = doctest.DocTestSuite(snake_case_ ) UpperCamelCase__ = unittest.TextTestRunner().run(snake_case_ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'{module_identifier} is not a module.' ) else: UpperCamelCase__ = doctest.testfile(str('..' / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'modeling' UpperCamelCase__ = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(snake_case_ , identifier=snake_case_ , ignore_files=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'tokenization' self.analyze_directory(snake_case_ , identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'configuration' self.analyze_directory(snake_case_ , identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(snake_case_ , n_identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = Path('docs/source' ) UpperCamelCase__ = ['favicon.ico'] self.analyze_directory(snake_case_ , ignore_files=snake_case_ , only_modules=snake_case_ )
20
0
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if len(__lowerCAmelCase ) <= 1: return lst UpperCamelCase__ = 1 while i < len(__lowerCAmelCase ): if lst[i - 1] <= lst[i]: i += 1 else: UpperCamelCase__ = lst[i], lst[i - 1] i -= 1 if i == 0: UpperCamelCase__ = 1 return lst if __name__ == "__main__": A__ : List[Any]= input("""Enter numbers separated by a comma:\n""").strip() A__ : int= [int(item) for item in user_input.split(""",""")] print(gnome_sort(unsorted))
717
"""simple docstring""" import warnings 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 A__ : str= logging.get_logger(__name__) A__ : List[Any]= { """nvidia/segformer-b0-finetuned-ade-512-512""": ( """https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json""" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class __lowerCamelCase ( _a ): a : Any ="""segformer""" def __init__( self , snake_case_=3 , snake_case_=4 , snake_case_=[2, 2, 2, 2] , snake_case_=[8, 4, 2, 1] , snake_case_=[32, 64, 160, 256] , snake_case_=[7, 3, 3, 3] , snake_case_=[4, 2, 2, 2] , snake_case_=[1, 2, 5, 8] , snake_case_=[4, 4, 4, 4] , snake_case_="gelu" , snake_case_=0.0 , snake_case_=0.0 , snake_case_=0.1 , snake_case_=0.02 , snake_case_=0.1 , snake_case_=1E-6 , snake_case_=256 , snake_case_=255 , **snake_case_ , ) -> Tuple: super().__init__(**snake_case_ ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( 'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be' ' removed, as the behaviour will default to that of reshape_last_stage = True.' , snake_case_ , ) UpperCamelCase__ = num_channels UpperCamelCase__ = num_encoder_blocks UpperCamelCase__ = depths UpperCamelCase__ = sr_ratios UpperCamelCase__ = hidden_sizes UpperCamelCase__ = patch_sizes UpperCamelCase__ = strides UpperCamelCase__ = mlp_ratios UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = classifier_dropout_prob UpperCamelCase__ = initializer_range UpperCamelCase__ = drop_path_rate UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = decoder_hidden_size UpperCamelCase__ = kwargs.get('reshape_last_stage' , snake_case_ ) UpperCamelCase__ = semantic_loss_ignore_index class __lowerCamelCase ( _a ): a : Any =version.parse("""1.11""" ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: return 1E-4 @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: return 12
20
0
"""simple docstring""" import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class __lowerCamelCase ( unittest.TestCase ): def __init__( self , snake_case_ ) -> int: UpperCamelCase__ = parent def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: return {} def lowerCAmelCase_( ) -> int: """simple docstring""" UpperCamelCase__ = '<HTML>\n\n <HEAD>\n <TITLE>sample document</TITLE>\n </HEAD>\n\n <BODY BGCOLOR=\"FFFFFF\">\n <HR>\n <a href=\"http://google.com\">Goog</a>\n <H1>This is one header</H1>\n <H2>This is a another Header</H2>\n <P>Travel from\n <P>\n <B>SFO to JFK</B>\n <BR>\n <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>\n <HR>\n <div style=\"color:#0000FF\">\n <h3>Traveler <b> name </b> is\n <p> John Doe </p>\n </div>' UpperCamelCase__ = '\n <!DOCTYPE html>\n <html>\n <body>\n\n <h1>My First Heading</h1>\n <p>My first paragraph.</p>\n\n </body>\n </html>\n ' return [html_string_a, html_string_a] @require_bsa class __lowerCamelCase ( __a , unittest.TestCase ): a : Optional[int] =MarkupLMFeatureExtractor if is_bsa_available() else None def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = MarkupLMFeatureExtractionTester(self ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: return self.feature_extract_tester.prepare_feat_extract_dict() def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = self.feature_extraction_class() # Test not batched input UpperCamelCase__ = get_html_strings()[0] UpperCamelCase__ = feature_extractor(lowerCAmelCase_ ) # fmt: off UpperCamelCase__ = [['sample document', 'Goog', 'This is one header', 'This is a another Header', 'Travel from', 'SFO to JFK', 'on May 2, 2015 at 2:00 pm. For details go to confirm.com', 'Traveler', 'name', 'is', 'John Doe']] UpperCamelCase__ = [['/html/head/title', '/html/body/a', '/html/body/h1', '/html/body/h2', '/html/body/p', '/html/body/p/p/b[1]', '/html/body/p/p/b[2]/i', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/b', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/p']] # fmt: on self.assertEqual(encoding.nodes , lowerCAmelCase_ ) self.assertEqual(encoding.xpaths , lowerCAmelCase_ ) # Test batched UpperCamelCase__ = get_html_strings() UpperCamelCase__ = feature_extractor(lowerCAmelCase_ ) # fmt: off UpperCamelCase__ = expected_nodes + [['My First Heading', 'My first paragraph.']] UpperCamelCase__ = expected_xpaths + [['/html/body/h1', '/html/body/p']] self.assertEqual(len(encoding.nodes ) , 2 ) self.assertEqual(len(encoding.xpaths ) , 2 ) self.assertEqual(encoding.nodes , lowerCAmelCase_ ) self.assertEqual(encoding.xpaths , lowerCAmelCase_ )
718
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class __lowerCamelCase ( _a ): @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: UpperCamelCase__ = parser.add_parser('download' ) download_parser.add_argument( '--cache-dir' , type=snake_case_ , default=snake_case_ , help='Path to location to store the models' ) download_parser.add_argument( '--force' , action='store_true' , help='Force the model to be download even if already in cache-dir' ) download_parser.add_argument( '--trust-remote-code' , action='store_true' , help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine' , ) download_parser.add_argument('model' , type=snake_case_ , help='Name of the model to download' ) download_parser.set_defaults(func=snake_case_ ) def __init__( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: UpperCamelCase__ = model UpperCamelCase__ = cache UpperCamelCase__ = force UpperCamelCase__ = trust_remote_code def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
20
0
"""simple docstring""" from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import PriorTransformer from .ta_film_transformer import TaFilmDecoder from .transformer_ad import TransformeraDModel from .unet_ad import UNetaDModel from .unet_ad import UNetaDModel from .unet_ad_condition import UNetaDConditionModel from .unet_ad_condition import UNetaDConditionModel from .vq_model import VQModel if is_flax_available(): from .controlnet_flax import FlaxControlNetModel from .unet_ad_condition_flax import FlaxUNetaDConditionModel from .vae_flax import FlaxAutoencoderKL
719
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCamelCase ( _a ): def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=False , snake_case_=True , snake_case_="None" , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> str: UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = relative_attention UpperCamelCase__ = position_biased_input UpperCamelCase__ = pos_att_type UpperCamelCase__ = scope def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Any: self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: UpperCamelCase__ = DebertaVaModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ )[0] UpperCamelCase__ = model(snake_case_ , token_type_ids=snake_case_ )[0] UpperCamelCase__ = model(snake_case_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: UpperCamelCase__ = DebertaVaForMaskedLM(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Dict: UpperCamelCase__ = self.num_labels UpperCamelCase__ = DebertaVaForSequenceClassification(snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[int]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = DebertaVaForTokenClassification(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = DebertaVaForQuestionAnswering(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , start_positions=snake_case_ , end_positions=snake_case_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = DebertaVaForMultipleChoice(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __lowerCamelCase ( _a , _a , unittest.TestCase ): a : Any =( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) a : Dict =( { """feature-extraction""": DebertaVaModel, """fill-mask""": DebertaVaForMaskedLM, """question-answering""": DebertaVaForQuestionAnswering, """text-classification""": DebertaVaForSequenceClassification, """token-classification""": DebertaVaForTokenClassification, """zero-shot""": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) a : Tuple =True a : Union[str, Any] =False a : Tuple =False a : Union[str, Any] =False a : Dict =False def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = DebertaVaModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = DebertaVaModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) @require_torch @require_sentencepiece @require_tokenizers class __lowerCamelCase ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: pass @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) UpperCamelCase__ = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) UpperCamelCase__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ )[0] # compare the actual values for a slice. UpperCamelCase__ = torch.tensor( [[[0.2_356, 0.1_948, 0.0_369], [-0.1_063, 0.3_586, -0.5_152], [-0.6_399, -0.0_259, -0.2_525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , snake_case_ , atol=1E-4 ) , F'{output[:, 1:4, 1:4]}' )
20
0
"""simple docstring""" import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file A__ : Tuple= "Run commands across TPU VMs for initial setup before running `accelerate launch`." def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> Any: """simple docstring""" if subparsers is not None: UpperCamelCase__ = subparsers.add_parser('tpu-config' , description=_description ) else: UpperCamelCase__ = argparse.ArgumentParser('Accelerate tpu-config command' , description=_description ) # Core arguments UpperCamelCase__ = parser.add_argument_group( 'Config Arguments' , 'Arguments that can be configured through `accelerate config`.' ) config_args.add_argument( '--config_file' , type=_UpperCamelCase , default=_UpperCamelCase , help='Path to the config file to use for accelerate.' , ) config_args.add_argument( '--tpu_name' , default=_UpperCamelCase , help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.' , ) config_args.add_argument( '--tpu_zone' , default=_UpperCamelCase , help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.' , ) UpperCamelCase__ = parser.add_argument_group('TPU Arguments' , 'Arguments for options ran inside the TPU.' ) pod_args.add_argument( '--use_alpha' , action='store_true' , help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.' , ) pod_args.add_argument( '--command_file' , default=_UpperCamelCase , help='The path to the file containing the commands to run on the pod on startup.' , ) pod_args.add_argument( '--command' , action='append' , nargs='+' , help='A command to run on the pod. Can be passed multiple times.' , ) pod_args.add_argument( '--install_accelerate' , action='store_true' , help='Whether to install accelerate on the pod. Defaults to False.' , ) pod_args.add_argument( '--accelerate_version' , default='latest' , help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.' , ) pod_args.add_argument( '--debug' , action='store_true' , help='If set, will print the command that would be run instead of running it.' ) if subparsers is not None: parser.set_defaults(func=_UpperCamelCase ) return parser def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" UpperCamelCase__ = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(_UpperCamelCase ): UpperCamelCase__ = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: UpperCamelCase__ = defaults.command_file if not args.command and defaults.commands is not None: UpperCamelCase__ = defaults.commands if not args.tpu_name: UpperCamelCase__ = defaults.tpu_name if not args.tpu_zone: UpperCamelCase__ = defaults.tpu_zone if args.accelerate_version == "dev": UpperCamelCase__ = 'git+https://github.com/huggingface/accelerate.git' elif args.accelerate_version == "latest": UpperCamelCase__ = 'accelerate -U' elif isinstance(parse(args.accelerate_version ) , _UpperCamelCase ): UpperCamelCase__ = F'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError('You must specify either a command file or a command to run on the pod.' ) if args.command_file: with open(args.command_file , 'r' ) as f: UpperCamelCase__ = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , _UpperCamelCase ): UpperCamelCase__ = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate UpperCamelCase__ = ['cd /usr/share'] if args.install_accelerate: new_cmd += [F'pip install {args.accelerate_version}'] new_cmd += args.command UpperCamelCase__ = '; '.join(_UpperCamelCase ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess UpperCamelCase__ = ['gcloud'] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'Running {" ".join(_UpperCamelCase )}' ) return subprocess.run(_UpperCamelCase ) print('Successfully setup pod.' ) def lowerCAmelCase_( ) -> Dict: """simple docstring""" UpperCamelCase__ = tpu_command_parser() UpperCamelCase__ = parser.parse_args() tpu_command_launcher(_UpperCamelCase )
720
"""simple docstring""" 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 lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = SwinConfig() UpperCamelCase__ = swin_name.split('_' ) UpperCamelCase__ = name_split[1] UpperCamelCase__ = int(name_split[4] ) UpperCamelCase__ = int(name_split[3][-1] ) if model_size == "tiny": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 6, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "small": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "base": UpperCamelCase__ = 1_28 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (4, 8, 16, 32) else: UpperCamelCase__ = 1_92 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (6, 12, 24, 48) if "in22k" in swin_name: UpperCamelCase__ = 2_18_41 else: UpperCamelCase__ = 10_00 UpperCamelCase__ = 'huggingface/label-files' UpperCamelCase__ = 'imagenet-1k-id2label.json' UpperCamelCase__ = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) UpperCamelCase__ = {int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} UpperCamelCase__ = idalabel UpperCamelCase__ = {v: k for k, v in idalabel.items()} UpperCamelCase__ = img_size UpperCamelCase__ = num_classes UpperCamelCase__ = embed_dim UpperCamelCase__ = depths UpperCamelCase__ = num_heads UpperCamelCase__ = window_size return config def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" if "patch_embed.proj" in name: UpperCamelCase__ = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: UpperCamelCase__ = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: UpperCamelCase__ = 'encoder.' + name if "attn.proj" in name: UpperCamelCase__ = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: UpperCamelCase__ = name.replace('attn' , 'attention.self' ) if "norm1" in name: UpperCamelCase__ = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: UpperCamelCase__ = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: UpperCamelCase__ = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: UpperCamelCase__ = name.replace('mlp.fc2' , 'output.dense' ) if name == "norm.weight": UpperCamelCase__ = 'layernorm.weight' if name == "norm.bias": UpperCamelCase__ = 'layernorm.bias' if "head" in name: UpperCamelCase__ = name.replace('head' , 'classifier' ) else: UpperCamelCase__ = 'swin.' + name return name def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCamelCase__ = orig_state_dict.pop(SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: UpperCamelCase__ = key.split('.' ) UpperCamelCase__ = int(key_split[1] ) UpperCamelCase__ = int(key_split[3] ) UpperCamelCase__ = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: UpperCamelCase__ = val[:dim, :] UpperCamelCase__ = val[ dim : dim * 2, : ] UpperCamelCase__ = val[-dim:, :] else: UpperCamelCase__ = val[ :dim ] UpperCamelCase__ = val[ dim : dim * 2 ] UpperCamelCase__ = val[ -dim: ] else: UpperCamelCase__ = val return orig_state_dict def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = timm.create_model(SCREAMING_SNAKE_CASE , pretrained=SCREAMING_SNAKE_CASE ) timm_model.eval() UpperCamelCase__ = get_swin_config(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = SwinForImageClassification(SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase__ = convert_state_dict(timm_model.state_dict() , SCREAMING_SNAKE_CASE ) model.load_state_dict(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = 'http://images.cocodataset.org/val2017/000000039769.jpg' UpperCamelCase__ = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swin_name.replace('_' , '-' ) ) ) UpperCamelCase__ = Image.open(requests.get(SCREAMING_SNAKE_CASE , stream=SCREAMING_SNAKE_CASE ).raw ) UpperCamelCase__ = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='pt' ) UpperCamelCase__ = timm_model(inputs['pixel_values'] ) UpperCamelCase__ = 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__": A__ : Optional[Any]= 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.""" ) A__ : Tuple= parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
20
0
"""simple docstring""" import unittest from transformers import AutoTokenizer, NystromformerConfig, 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 ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCamelCase : def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> Optional[Any]: UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self ) -> str: return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=A__ , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: UpperCamelCase__ = NystromformerModel(config=A__ ) model.to(A__ ) model.eval() UpperCamelCase__ = model(A__ , attention_mask=A__ , token_type_ids=A__ ) UpperCamelCase__ = model(A__ , token_type_ids=A__ ) UpperCamelCase__ = model(A__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[int]: UpperCamelCase__ = NystromformerForMaskedLM(config=A__ ) model.to(A__ ) model.eval() UpperCamelCase__ = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = NystromformerForQuestionAnswering(config=A__ ) model.to(A__ ) model.eval() UpperCamelCase__ = model( A__ , attention_mask=A__ , token_type_ids=A__ , start_positions=A__ , end_positions=A__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Dict: UpperCamelCase__ = self.num_labels UpperCamelCase__ = NystromformerForSequenceClassification(A__ ) model.to(A__ ) model.eval() UpperCamelCase__ = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Any: UpperCamelCase__ = self.num_labels UpperCamelCase__ = NystromformerForTokenClassification(config=A__ ) model.to(A__ ) model.eval() UpperCamelCase__ = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = self.num_choices UpperCamelCase__ = NystromformerForMultipleChoice(config=A__ ) model.to(A__ ) model.eval() UpperCamelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = model( A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __lowerCamelCase ( __a , __a , unittest.TestCase ): a : Optional[int] =( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) a : Optional[Any] =( { """feature-extraction""": NystromformerModel, """fill-mask""": NystromformerForMaskedLM, """question-answering""": NystromformerForQuestionAnswering, """text-classification""": NystromformerForSequenceClassification, """token-classification""": NystromformerForTokenClassification, """zero-shot""": NystromformerForSequenceClassification, } if is_torch_available() else {} ) a : Optional[int] =False a : Union[str, Any] =False def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = NystromformerModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=A__ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase__ = type self.model_tester.create_and_check_model(*A__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*A__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A__ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = NystromformerModel.from_pretrained(A__ ) self.assertIsNotNone(A__ ) @require_torch class __lowerCamelCase ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ = NystromformerModel.from_pretrained('uw-madison/nystromformer-512' ) UpperCamelCase__ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): UpperCamelCase__ = model(A__ )[0] UpperCamelCase__ = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , A__ ) UpperCamelCase__ = torch.tensor( [[[-0.4_532, -0.0_936, 0.5_137], [-0.2_676, 0.0_628, 0.6_186], [-0.3_629, -0.1_726, 0.4_716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , A__ , atol=1E-4 ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = 'the [MASK] of Belgium is Brussels' UpperCamelCase__ = AutoTokenizer.from_pretrained('uw-madison/nystromformer-512' ) UpperCamelCase__ = NystromformerForMaskedLM.from_pretrained('uw-madison/nystromformer-512' ) UpperCamelCase__ = tokenizer(A__ , return_tensors='pt' ) with torch.no_grad(): UpperCamelCase__ = model(encoding.input_ids ).logits UpperCamelCase__ = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(A__ ) , 'capital' )
721
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" UpperCamelCase__ = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 50_00 ) -> int: """simple docstring""" UpperCamelCase__ = [(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 ) ): UpperCamelCase__ = pentagonal_nums[j] UpperCamelCase__ = pentagonal_i + pentagonal_j UpperCamelCase__ = 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() = }""")
20
0
"""simple docstring""" import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" UpperCamelCase__ = tmp_path / 'cache' UpperCamelCase__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): UpperCamelCase__ = JsonDatasetReader(_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , keep_in_memory=_SCREAMING_SNAKE_CASE ).read() _check_json_dataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" UpperCamelCase__ = tmp_path / 'cache' UpperCamelCase__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} UpperCamelCase__ = features.copy() if features else default_expected_features UpperCamelCase__ = ( Features({feature: Value(_SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCamelCase__ = JsonDatasetReader(_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() _check_json_dataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( 'features' , [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ] , ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase__ = tmp_path / 'cache' UpperCamelCase__ = {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} UpperCamelCase__ = features.copy() if features else default_expected_features UpperCamelCase__ = ( Features({feature: Value(_SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCamelCase__ = JsonDatasetReader(_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = {'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} UpperCamelCase__ = features.copy() UpperCamelCase__ = ( Features({feature: Value(_SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCamelCase__ = tmp_path / 'cache' UpperCamelCase__ = JsonDatasetReader(_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" UpperCamelCase__ = tmp_path / 'cache' UpperCamelCase__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} UpperCamelCase__ = JsonDatasetReader(_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , split=_SCREAMING_SNAKE_CASE ).read() _check_json_dataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' , [str, list] ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" if issubclass(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase__ = jsonl_path elif issubclass(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase__ = [jsonl_path] UpperCamelCase__ = tmp_path / 'cache' UpperCamelCase__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} UpperCamelCase__ = JsonDatasetReader(_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() _check_json_dataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=("train",) ) -> int: """simple docstring""" assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for split in splits: UpperCamelCase__ = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase__ = tmp_path / 'cache' UpperCamelCase__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): UpperCamelCase__ = JsonDatasetReader({'train': jsonl_path} , cache_dir=_SCREAMING_SNAKE_CASE , keep_in_memory=_SCREAMING_SNAKE_CASE ).read() _check_json_datasetdict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" UpperCamelCase__ = tmp_path / 'cache' UpperCamelCase__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} UpperCamelCase__ = features.copy() if features else default_expected_features UpperCamelCase__ = ( Features({feature: Value(_SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCamelCase__ = JsonDatasetReader({'train': jsonl_path} , features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() _check_json_datasetdict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" if split: UpperCamelCase__ = {split: jsonl_path} else: UpperCamelCase__ = 'train' UpperCamelCase__ = {'train': jsonl_path, 'test': jsonl_path} UpperCamelCase__ = tmp_path / 'cache' UpperCamelCase__ = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} UpperCamelCase__ = JsonDatasetReader(_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ).read() _check_json_datasetdict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return json.load(_SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" return [json.loads(_SCREAMING_SNAKE_CASE ) for line in buffer] class __lowerCamelCase : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(snake_case_ , snake_case_ , lines=snake_case_ ).write() buffer.seek(0 ) UpperCamelCase__ = load_json_function(snake_case_ ) assert isinstance(snake_case_ , snake_case_ ) assert isinstance(exported_content[0] , snake_case_ ) assert len(snake_case_ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: with io.BytesIO() as buffer: JsonDatasetWriter(snake_case_ , snake_case_ , lines=snake_case_ , orient=snake_case_ ).write() buffer.seek(0 ) UpperCamelCase__ = load_json(snake_case_ ) assert isinstance(snake_case_ , snake_case_ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(snake_case_ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(snake_case_ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(snake_case_ , snake_case_ , lines=snake_case_ , num_proc=2 ).write() buffer.seek(0 ) UpperCamelCase__ = load_json_function(snake_case_ ) assert isinstance(snake_case_ , snake_case_ ) assert isinstance(exported_content[0] , snake_case_ ) assert len(snake_case_ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: with io.BytesIO() as buffer: JsonDatasetWriter(snake_case_ , snake_case_ , lines=snake_case_ , orient=snake_case_ , num_proc=2 ).write() buffer.seek(0 ) UpperCamelCase__ = load_json(snake_case_ ) assert isinstance(snake_case_ , snake_case_ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(snake_case_ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(snake_case_ ) == 10 def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: with pytest.raises(snake_case_ ): with io.BytesIO() as buffer: JsonDatasetWriter(snake_case_ , snake_case_ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Dict: UpperCamelCase__ = tmp_path_factory.mktemp('data' ) / F'test.json.{extension}' UpperCamelCase__ = str(shared_datadir / F'test_file.json.{extension}' ) JsonDatasetWriter(snake_case_ , snake_case_ , compression=snake_case_ ).write() with fsspec.open(snake_case_ , 'rb' , compression='infer' ) as f: UpperCamelCase__ = f.read() with fsspec.open(snake_case_ , 'rb' , compression='infer' ) as f: UpperCamelCase__ = f.read() assert exported_content == original_content
700
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 50_00_00_00 ) -> int: """simple docstring""" UpperCamelCase__ = set() UpperCamelCase__ = int((limit - 24) ** (1 / 2) ) UpperCamelCase__ = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , SCREAMING_SNAKE_CASE ) ) ) for primea in primes: UpperCamelCase__ = primea * primea for primea in primes: UpperCamelCase__ = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: UpperCamelCase__ = primea * primea * primea * primea UpperCamelCase__ = square + cube + tetr if total >= limit: break ret.add(SCREAMING_SNAKE_CASE ) return len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(F"""{solution() = }""")
20
0
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __lowerCamelCase ( __snake_case ): a : Optional[int] =(DDIMParallelScheduler,) a : Union[str, Any] =(("""eta""", 0.0), ("""num_inference_steps""", 5_0)) def SCREAMING_SNAKE_CASE__ ( self , **snake_case_ ) -> Dict: UpperCamelCase__ = { 'num_train_timesteps': 1000, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'clip_sample': True, } config.update(**__UpperCamelCase ) return config def SCREAMING_SNAKE_CASE__ ( self , **snake_case_ ) -> Any: UpperCamelCase__ = self.scheduler_classes[0] UpperCamelCase__ = self.get_scheduler_config(**__UpperCamelCase ) UpperCamelCase__ = scheduler_class(**__UpperCamelCase ) UpperCamelCase__ , UpperCamelCase__ = 10, 0.0 UpperCamelCase__ = self.dummy_model() UpperCamelCase__ = self.dummy_sample_deter scheduler.set_timesteps(__UpperCamelCase ) for t in scheduler.timesteps: UpperCamelCase__ = model(__UpperCamelCase , __UpperCamelCase ) UpperCamelCase__ = scheduler.step(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ).prev_sample return sample def SCREAMING_SNAKE_CASE__ ( self ) -> int: for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=__UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__UpperCamelCase ) UpperCamelCase__ = self.scheduler_classes[0] UpperCamelCase__ = self.get_scheduler_config(steps_offset=1 ) UpperCamelCase__ = scheduler_class(**__UpperCamelCase ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: for beta_start, beta_end in zip([0.0_001, 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 ) -> Any: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=__UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: self.check_over_configs(thresholding=__UpperCamelCase ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__UpperCamelCase , prediction_type=__UpperCamelCase , sample_max_value=__UpperCamelCase , ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: for t in [1, 10, 49]: self.check_over_forward(time_step=__UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=__UpperCamelCase , num_inference_steps=__UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__UpperCamelCase , eta=__UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.scheduler_classes[0] UpperCamelCase__ = self.get_scheduler_config() UpperCamelCase__ = scheduler_class(**__UpperCamelCase ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14_771 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32_460 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00_979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1E-5 def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = self.scheduler_classes[0] UpperCamelCase__ = self.get_scheduler_config() UpperCamelCase__ = scheduler_class(**__UpperCamelCase ) UpperCamelCase__ , UpperCamelCase__ = 10, 0.0 scheduler.set_timesteps(__UpperCamelCase ) UpperCamelCase__ = self.dummy_model() UpperCamelCase__ = self.dummy_sample_deter UpperCamelCase__ = self.dummy_sample_deter + 0.1 UpperCamelCase__ = self.dummy_sample_deter - 0.1 UpperCamelCase__ = samplea.shape[0] UpperCamelCase__ = torch.stack([samplea, samplea, samplea] , dim=0 ) UpperCamelCase__ = torch.arange(__UpperCamelCase )[0:3, None].repeat(1 , __UpperCamelCase ) UpperCamelCase__ = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) UpperCamelCase__ = scheduler.batch_step_no_noise(__UpperCamelCase , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __UpperCamelCase ) UpperCamelCase__ = torch.sum(torch.abs(__UpperCamelCase ) ) UpperCamelCase__ = torch.mean(torch.abs(__UpperCamelCase ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1E-2 assert abs(result_mean.item() - 0.4_982 ) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.full_loop() UpperCamelCase__ = torch.sum(torch.abs(__UpperCamelCase ) ) UpperCamelCase__ = torch.mean(torch.abs(__UpperCamelCase ) ) assert abs(result_sum.item() - 172.0_067 ) < 1E-2 assert abs(result_mean.item() - 0.223_967 ) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.full_loop(prediction_type='v_prediction' ) UpperCamelCase__ = torch.sum(torch.abs(__UpperCamelCase ) ) UpperCamelCase__ = torch.mean(torch.abs(__UpperCamelCase ) ) assert abs(result_sum.item() - 52.5_302 ) < 1E-2 assert abs(result_mean.item() - 0.0_684 ) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = self.full_loop(set_alpha_to_one=__UpperCamelCase , beta_start=0.01 ) UpperCamelCase__ = torch.sum(torch.abs(__UpperCamelCase ) ) UpperCamelCase__ = torch.mean(torch.abs(__UpperCamelCase ) ) assert abs(result_sum.item() - 149.8_295 ) < 1E-2 assert abs(result_mean.item() - 0.1_951 ) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = self.full_loop(set_alpha_to_one=__UpperCamelCase , beta_start=0.01 ) UpperCamelCase__ = torch.sum(torch.abs(__UpperCamelCase ) ) UpperCamelCase__ = torch.mean(torch.abs(__UpperCamelCase ) ) assert abs(result_sum.item() - 149.0_784 ) < 1E-2 assert abs(result_mean.item() - 0.1_941 ) < 1E-3
701
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer A__ : List[Any]= ["""bert-base-uncased""", """bert-base-cased"""] A__ : Optional[int]= """hf-internal-testing/tiny-bert-tf-only""" if is_tf_available(): class __lowerCamelCase ( tf.keras.Model ): def __init__( self , snake_case_ ) -> Optional[int]: super().__init__() UpperCamelCase__ = tokenizer UpperCamelCase__ = AutoConfig.from_pretrained(snake_case_ ) UpperCamelCase__ = TFAutoModel.from_config(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: UpperCamelCase__ = self.tokenizer(snake_case_ ) UpperCamelCase__ = self.bert(**snake_case_ ) return out["pooler_output"] @require_tf @require_tensorflow_text class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ) -> str: super().setUp() UpperCamelCase__ = [ BertTokenizer.from_pretrained(snake_case_ ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false UpperCamelCase__ = [TFBertTokenizer.from_pretrained(snake_case_ ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(snake_case_ , use_fast_bert_tokenizer=snake_case_ ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCamelCase__ = [ 'This is a straightforward English test sentence.', 'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.', 'Now we\'re going to add some Chinese: 一 二 三 一二三', 'And some much more rare Chinese: 齉 堃 齉堃', 'Je vais aussi écrire en français pour tester les accents', 'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ', ] UpperCamelCase__ = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase__ = tokenizer(snake_case_ , return_tensors='tf' , padding='longest' ) UpperCamelCase__ = tf_tokenizer(snake_case_ ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> str: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = tf_tokenizer(self.paired_sentences ) UpperCamelCase__ = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = tf.function(snake_case_ ) for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase__ = tf.constant(snake_case_ ) UpperCamelCase__ = compiled_tokenizer(snake_case_ ) UpperCamelCase__ = tf_tokenizer(snake_case_ ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = ModelToSave(tokenizer=snake_case_ ) UpperCamelCase__ = tf.convert_to_tensor(self.test_sentences ) UpperCamelCase__ = model(snake_case_ ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCamelCase__ = Path(snake_case_ ) / 'saved.model' model.save(snake_case_ ) UpperCamelCase__ = tf.keras.models.load_model(snake_case_ ) UpperCamelCase__ = loaded_model(snake_case_ ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
20
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A__ : Dict= {'configuration_xlnet': ['XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : List[Any]= ['XLNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : int= ['XLNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : List[Any]= [ 'XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLNetForMultipleChoice', 'XLNetForQuestionAnswering', 'XLNetForQuestionAnsweringSimple', 'XLNetForSequenceClassification', 'XLNetForTokenClassification', 'XLNetLMHeadModel', 'XLNetModel', 'XLNetPreTrainedModel', 'load_tf_weights_in_xlnet', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict= [ 'TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLNetForMultipleChoice', 'TFXLNetForQuestionAnsweringSimple', 'TFXLNetForSequenceClassification', 'TFXLNetForTokenClassification', 'TFXLNetLMHeadModel', 'TFXLNetMainLayer', 'TFXLNetModel', 'TFXLNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys A__ : int= _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
702
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> list[int]: """simple docstring""" UpperCamelCase__ = len(SCREAMING_SNAKE_CASE ) for i in range(SCREAMING_SNAKE_CASE ): for j in range(i + 1 , SCREAMING_SNAKE_CASE ): if numbers[j] < numbers[i]: UpperCamelCase__ , UpperCamelCase__ = numbers[j], numbers[i] return numbers if __name__ == "__main__": A__ : Union[str, Any]= input("""Enter numbers separated by a comma:\n""").strip() A__ : List[Any]= [int(item) for item in user_input.split(""",""")] print(exchange_sort(unsorted))
20
0
"""simple docstring""" from __future__ import annotations A__ : Tuple= """Muhammad Umer Farooq""" A__ : Any= """MIT""" A__ : Optional[Any]= """1.0.0""" A__ : Dict= """Muhammad Umer Farooq""" A__ : Optional[Any]= """contact@muhammadumerfarooq.me""" A__ : Union[str, Any]= """Alpha""" import re from html.parser import HTMLParser from urllib import parse import requests class __lowerCamelCase ( _UpperCAmelCase ): def __init__( self , snake_case_ ) -> List[str]: super().__init__() UpperCamelCase__ = [] UpperCamelCase__ = domain def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> List[str]: # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: UpperCamelCase__ = parse.urljoin(self.domain , lowercase__ ) self.urls.append(lowercase__ ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" return ".".join(get_sub_domain_name(SCREAMING_SNAKE_CASE__ ).split('.' )[-2:] ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" return parse.urlparse(SCREAMING_SNAKE_CASE__ ).netloc def lowerCAmelCase_( SCREAMING_SNAKE_CASE = "https://github.com" ) -> str: """simple docstring""" UpperCamelCase__ = get_domain_name(SCREAMING_SNAKE_CASE__ ) # Initialize the parser UpperCamelCase__ = Parser(SCREAMING_SNAKE_CASE__ ) try: # Open URL UpperCamelCase__ = requests.get(SCREAMING_SNAKE_CASE__ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through UpperCamelCase__ = set() for link in parser.urls: # open URL. # read = requests.get(link) try: UpperCamelCase__ = requests.get(SCREAMING_SNAKE_CASE__ ) # Get the valid email. UpperCamelCase__ = re.findall('[a-zA-Z0-9]+@' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(SCREAMING_SNAKE_CASE__ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": A__ : Any= emails_from_url("""https://github.com""") print(F"""{len(emails)} emails found:""") print("""\n""".join(sorted(emails)))
703
"""simple docstring""" import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("""9.1.0"""): A__ : str= { """linear""": PIL.Image.Resampling.BILINEAR, """bilinear""": PIL.Image.Resampling.BILINEAR, """bicubic""": PIL.Image.Resampling.BICUBIC, """lanczos""": PIL.Image.Resampling.LANCZOS, """nearest""": PIL.Image.Resampling.NEAREST, } else: A__ : str= { """linear""": PIL.Image.LINEAR, """bilinear""": PIL.Image.BILINEAR, """bicubic""": PIL.Image.BICUBIC, """lanczos""": PIL.Image.LANCZOS, """nearest""": PIL.Image.NEAREST, } def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = (images / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() UpperCamelCase__ = numpy_to_pil(SCREAMING_SNAKE_CASE ) return images def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if images.ndim == 3: UpperCamelCase__ = images[None, ...] UpperCamelCase__ = (images * 2_55).round().astype('uint8' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images UpperCamelCase__ = [Image.fromarray(image.squeeze() , mode='L' ) for image in images] else: UpperCamelCase__ = [Image.fromarray(SCREAMING_SNAKE_CASE ) for image in images] return pil_images
20
0
"""simple docstring""" import numpy as np from PIL import Image def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" UpperCamelCase__ = np.array(a_ ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = 0 # compute the shape of the output matrix UpperCamelCase__ = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape UpperCamelCase__ = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix UpperCamelCase__ = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 UpperCamelCase__ = 0 UpperCamelCase__ = 0 return updated_arr def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" UpperCamelCase__ = np.array(a_ ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = 0 # compute the shape of the output matrix UpperCamelCase__ = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape UpperCamelCase__ = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix UpperCamelCase__ = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 UpperCamelCase__ = 0 UpperCamelCase__ = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="""avgpooling""", verbose=True) # Loading the image A__ : Union[str, Any]= Image.open("""path_to_image""") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
704
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging A__ : Dict= logging.get_logger(__name__) A__ : str= {"""vocab_file""": """spiece.model"""} A__ : Union[str, Any]= { """vocab_file""": { """t5-small""": """https://huggingface.co/t5-small/resolve/main/spiece.model""", """t5-base""": """https://huggingface.co/t5-base/resolve/main/spiece.model""", """t5-large""": """https://huggingface.co/t5-large/resolve/main/spiece.model""", """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/spiece.model""", """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/spiece.model""", } } # TODO(PVP) - this should be removed in Transformers v5 A__ : Union[str, Any]= { """t5-small""": 5_12, """t5-base""": 5_12, """t5-large""": 5_12, """t5-3b""": 5_12, """t5-11b""": 5_12, } A__ : Optional[Any]= """▁""" class __lowerCamelCase ( _a ): a : Dict =VOCAB_FILES_NAMES a : str =PRETRAINED_VOCAB_FILES_MAP a : Union[str, Any] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : List[str] =["""input_ids""", """attention_mask"""] def __init__( self , snake_case_ , snake_case_="</s>" , snake_case_="<unk>" , snake_case_="<pad>" , snake_case_=100 , snake_case_=None , snake_case_ = None , snake_case_=True , **snake_case_ , ) -> None: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: UpperCamelCase__ = [F'<extra_id_{i}>' for i in range(snake_case_ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens UpperCamelCase__ = len(set(filter(lambda snake_case_ : bool('extra_id' in str(snake_case_ ) ) , snake_case_ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' ' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids' ' tokens' ) if legacy: logger.warning_once( F'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to' ' read the related pull request available at https://github.com/huggingface/transformers/pull/24565' ) UpperCamelCase__ = legacy UpperCamelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=snake_case_ , unk_token=snake_case_ , pad_token=snake_case_ , extra_ids=snake_case_ , additional_special_tokens=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , legacy=snake_case_ , **snake_case_ , ) UpperCamelCase__ = vocab_file UpperCamelCase__ = extra_ids UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: UpperCamelCase__ = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( 'This tokenizer was incorrectly instantiated with a model max length of' F' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' ' behavior is kept to avoid breaking backwards compatibility when padding/encoding with' ' `truncation is True`.\n- Be aware that you SHOULD NOT rely on' F' {pretrained_model_name_or_path} automatically truncating your input to' F' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' F' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' ' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please' ' instantiate this tokenizer with `model_max_length` set to your preferred value.' , snake_case_ , ) return max_model_length @property def SCREAMING_SNAKE_CASE__ ( self ) -> Any: return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = {self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case_ , token_ids_a=snake_case_ , already_has_special_tokens=snake_case_ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(snake_case_ )) + [1] return ([0] * len(snake_case_ )) + [1] + ([0] * len(snake_case_ )) + [1] def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return list( set(filter(lambda snake_case_ : bool(re.search(r'<extra_id_\d+>' , snake_case_ ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: return [self._convert_token_to_id(snake_case_ ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[int]: if len(snake_case_ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' ' eos tokens being added.' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = self._add_eos_if_not_present(snake_case_ ) if token_ids_a is None: return token_ids_a else: UpperCamelCase__ = self._add_eos_if_not_present(snake_case_ ) return token_ids_a + token_ids_a def __getstate__( self ) -> str: UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = None return state def __setstate__( self , snake_case_ ) -> Any: UpperCamelCase__ = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): UpperCamelCase__ = {} UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , **snake_case_ ) -> List[str]: # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: UpperCamelCase__ = SPIECE_UNDERLINE + text.replace(snake_case_ , ' ' ) return super().tokenize(snake_case_ , **snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , **snake_case_ ) -> List[Any]: if not self.legacy: UpperCamelCase__ = text.startswith(snake_case_ ) if is_first: UpperCamelCase__ = text[1:] UpperCamelCase__ = self.sp_model.encode(snake_case_ , out_type=snake_case_ ) if not self.legacy and not is_first and not text.startswith(' ' ) and tokens[0].startswith(snake_case_ ): UpperCamelCase__ = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: if token.startswith('<extra_id_' ): UpperCamelCase__ = re.match(r'<extra_id_(\d+)>' , snake_case_ ) UpperCamelCase__ = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Optional[int]: if index < self.sp_model.get_piece_size(): UpperCamelCase__ = self.sp_model.IdToPiece(snake_case_ ) else: UpperCamelCase__ = F'<extra_id_{self.vocab_size - 1 - index}>' return token def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: UpperCamelCase__ = [] UpperCamelCase__ = '' UpperCamelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(snake_case_ ) + token UpperCamelCase__ = True UpperCamelCase__ = [] else: current_sub_tokens.append(snake_case_ ) UpperCamelCase__ = False out_string += self.sp_model.decode(snake_case_ ) return out_string.strip() def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> Tuple[str]: if not os.path.isdir(snake_case_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase__ = os.path.join( snake_case_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case_ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case_ , 'wb' ) as fi: UpperCamelCase__ = self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,)
20
0
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging A__ : Tuple= logging.get_logger(__name__) A__ : Tuple= { """Helsinki-NLP/opus-mt-en-de""": """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json""", # See all Marian models at https://huggingface.co/models?filter=marian } class __lowerCamelCase ( _a ): a : Union[str, Any] ="marian" a : List[Any] =["past_key_values"] a : List[Any] ={"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , snake_case_=5_8101 , snake_case_=None , snake_case_=1024 , snake_case_=12 , snake_case_=4096 , snake_case_=16 , snake_case_=12 , snake_case_=4096 , snake_case_=16 , snake_case_=0.0 , snake_case_=0.0 , snake_case_=True , snake_case_=True , snake_case_="gelu" , snake_case_=1024 , snake_case_=0.1 , snake_case_=0.0 , snake_case_=0.0 , snake_case_=0.02 , snake_case_=5_8100 , snake_case_=False , snake_case_=5_8100 , snake_case_=0 , snake_case_=0 , snake_case_=True , **snake_case_ , ) -> Optional[int]: UpperCamelCase__ = vocab_size UpperCamelCase__ = decoder_vocab_size or vocab_size UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = d_model UpperCamelCase__ = encoder_ffn_dim UpperCamelCase__ = encoder_layers UpperCamelCase__ = encoder_attention_heads UpperCamelCase__ = decoder_ffn_dim UpperCamelCase__ = decoder_layers UpperCamelCase__ = decoder_attention_heads UpperCamelCase__ = dropout UpperCamelCase__ = attention_dropout UpperCamelCase__ = activation_dropout UpperCamelCase__ = activation_function UpperCamelCase__ = init_std UpperCamelCase__ = encoder_layerdrop UpperCamelCase__ = decoder_layerdrop UpperCamelCase__ = use_cache UpperCamelCase__ = encoder_layers UpperCamelCase__ = scale_embedding # scale factor will be sqrt(d_model) if True UpperCamelCase__ = share_encoder_decoder_embeddings super().__init__( pad_token_id=snake_case_ , eos_token_id=snake_case_ , is_encoder_decoder=snake_case_ , decoder_start_token_id=snake_case_ , forced_eos_token_id=snake_case_ , **snake_case_ , ) class __lowerCamelCase ( _a ): @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: if self.task in ["default", "seq2seq-lm"]: UpperCamelCase__ = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: UpperCamelCase__ = {0: 'batch'} UpperCamelCase__ = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: UpperCamelCase__ = {0: 'batch', 1: 'decoder_sequence'} UpperCamelCase__ = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(snake_case_ , direction='inputs' ) elif self.task == "causal-lm": # TODO: figure this case out. UpperCamelCase__ = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: UpperCamelCase__ , UpperCamelCase__ = self.num_layers for i in range(snake_case_ ): UpperCamelCase__ = {0: 'batch', 2: 'past_sequence + sequence'} UpperCamelCase__ = {0: 'batch', 2: 'past_sequence + sequence'} else: UpperCamelCase__ = OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}), ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}), ] ) return common_inputs @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: if self.task in ["default", "seq2seq-lm"]: UpperCamelCase__ = super().outputs else: UpperCamelCase__ = super(snake_case_ , self ).outputs if self.use_past: UpperCamelCase__ , UpperCamelCase__ = self.num_layers for i in range(snake_case_ ): UpperCamelCase__ = {0: 'batch', 2: 'past_sequence + sequence'} UpperCamelCase__ = {0: 'batch', 2: 'past_sequence + sequence'} return common_outputs def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , ) -> Mapping[str, Any]: UpperCamelCase__ = self._generate_dummy_inputs_for_encoder_and_decoder( snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) # Generate decoder inputs UpperCamelCase__ = seq_length if not self.use_past else 1 UpperCamelCase__ = self._generate_dummy_inputs_for_encoder_and_decoder( snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) UpperCamelCase__ = {F'decoder_{name}': tensor for name, tensor in decoder_inputs.items()} UpperCamelCase__ = dict(**snake_case_ , **snake_case_ ) if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch UpperCamelCase__ , UpperCamelCase__ = common_inputs['input_ids'].shape UpperCamelCase__ = common_inputs['decoder_input_ids'].shape[1] UpperCamelCase__ , UpperCamelCase__ = self.num_attention_heads UpperCamelCase__ = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase__ = decoder_seq_length + 3 UpperCamelCase__ = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) UpperCamelCase__ = torch.cat( [common_inputs['decoder_attention_mask'], torch.ones(snake_case_ , snake_case_ )] , dim=1 ) UpperCamelCase__ = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered UpperCamelCase__ , UpperCamelCase__ = self.num_layers UpperCamelCase__ = min(snake_case_ , snake_case_ ) UpperCamelCase__ = max(snake_case_ , snake_case_ ) - min_num_layers UpperCamelCase__ = 'encoder' if num_encoder_layers > num_decoder_layers else 'decoder' for _ in range(snake_case_ ): common_inputs["past_key_values"].append( ( torch.zeros(snake_case_ ), torch.zeros(snake_case_ ), torch.zeros(snake_case_ ), torch.zeros(snake_case_ ), ) ) # TODO: test this. UpperCamelCase__ = encoder_shape if remaining_side_name == 'encoder' else decoder_shape for _ in range(snake_case_ , snake_case_ ): common_inputs["past_key_values"].append((torch.zeros(snake_case_ ), torch.zeros(snake_case_ )) ) return common_inputs def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , ) -> Mapping[str, Any]: UpperCamelCase__ = self._generate_dummy_inputs_for_encoder_and_decoder( snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch UpperCamelCase__ , UpperCamelCase__ = common_inputs['input_ids'].shape # Not using the same length for past_key_values UpperCamelCase__ = seqlen + 2 UpperCamelCase__ , UpperCamelCase__ = self.num_layers UpperCamelCase__ , UpperCamelCase__ = self.num_attention_heads UpperCamelCase__ = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCamelCase__ = common_inputs['attention_mask'].dtype UpperCamelCase__ = torch.cat( [common_inputs['attention_mask'], torch.ones(snake_case_ , snake_case_ , dtype=snake_case_ )] , dim=1 ) UpperCamelCase__ = [ (torch.zeros(snake_case_ ), torch.zeros(snake_case_ )) for _ in range(snake_case_ ) ] return common_inputs def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , ) -> Mapping[str, Any]: UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase__ = tokenizer.num_special_tokens_to_add(snake_case_ ) UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case_ ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase__ = [' '.join([tokenizer.unk_token] ) * seq_length] * batch_size UpperCamelCase__ = dict(tokenizer(snake_case_ , return_tensors=snake_case_ ) ) return common_inputs def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , ) -> Mapping[str, Any]: if self.task in ["default", "seq2seq-lm"]: UpperCamelCase__ = self._generate_dummy_inputs_for_default_and_seqaseq_lm( snake_case_ , batch_size=snake_case_ , seq_length=snake_case_ , is_pair=snake_case_ , framework=snake_case_ ) else: UpperCamelCase__ = self._generate_dummy_inputs_for_causal_lm( snake_case_ , batch_size=snake_case_ , seq_length=snake_case_ , is_pair=snake_case_ , framework=snake_case_ ) return common_inputs def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: if self.task in ["default", "seq2seq-lm"]: UpperCamelCase__ = super()._flatten_past_key_values_(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) else: UpperCamelCase__ = super(snake_case_ , self )._flatten_past_key_values_( snake_case_ , snake_case_ , snake_case_ , snake_case_ ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: return 1E-4
705
"""simple docstring""" from __future__ import annotations from typing import Generic, TypeVar A__ : Any= TypeVar("""T""") class __lowerCamelCase ( Generic[T] ): def __init__( self , snake_case_ ) -> None: UpperCamelCase__ = data UpperCamelCase__ = self UpperCamelCase__ = 0 class __lowerCamelCase ( Generic[T] ): def __init__( self ) -> None: # map from node name to the node object UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: # create a new set with x as its member UpperCamelCase__ = DisjointSetTreeNode(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> DisjointSetTreeNode[T]: # find the set x belongs to (with path-compression) UpperCamelCase__ = self.map[data] if elem_ref != elem_ref.parent: UpperCamelCase__ = self.find_set(elem_ref.parent.data ) return elem_ref.parent def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: # helper function for union operation if nodea.rank > nodea.rank: UpperCamelCase__ = nodea else: UpperCamelCase__ = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: # merge 2 disjoint sets self.link(self.find_set(snake_case_ ) , self.find_set(snake_case_ ) ) class __lowerCamelCase ( Generic[T] ): def __init__( self ) -> None: # connections: map from the node to the neighbouring nodes (with weights) UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: # add a node ONLY if its not present in the graph if node not in self.connections: UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> None: # add an edge with the given weight self.add_node(snake_case_ ) self.add_node(snake_case_ ) UpperCamelCase__ = weight UpperCamelCase__ = weight def SCREAMING_SNAKE_CASE__ ( self ) -> GraphUndirectedWeighted[T]: UpperCamelCase__ = [] UpperCamelCase__ = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda snake_case_ : x[2] ) # creating the disjoint set UpperCamelCase__ = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(snake_case_ ) # MST generation UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = edges[index] index += 1 UpperCamelCase__ = disjoint_set.find_set(snake_case_ ) UpperCamelCase__ = disjoint_set.find_set(snake_case_ ) if parent_u != parent_v: num_edges += 1 graph.add_edge(snake_case_ , snake_case_ , snake_case_ ) disjoint_set.union(snake_case_ , snake_case_ ) return graph
20
0
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __lowerCamelCase ( _UpperCamelCase ): a : Any =["image_processor", "tokenizer"] a : Tuple ="CLIPImageProcessor" a : Optional[int] =("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self , snake_case_=None , snake_case_=None , **snake_case_ ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , __a , ) UpperCamelCase__ = kwargs.pop('feature_extractor' ) UpperCamelCase__ = 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__(__a , __a ) def __call__( self , snake_case_=None , snake_case_=None , snake_case_=None , **snake_case_ ) -> Union[str, Any]: '''simple docstring''' 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__ = self.tokenizer(__a , return_tensors=__a , **__a ) if images is not None: UpperCamelCase__ = self.image_processor(__a , return_tensors=__a , **__a ) if text is not None and images is not None: UpperCamelCase__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__a ) , tensor_type=__a ) def SCREAMING_SNAKE_CASE__ ( self , *snake_case_ , **snake_case_ ) -> int: '''simple docstring''' return self.tokenizer.batch_decode(*__a , **__a ) def SCREAMING_SNAKE_CASE__ ( self , *snake_case_ , **snake_case_ ) -> int: '''simple docstring''' return self.tokenizer.decode(*__a , **__a ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> str: '''simple docstring''' UpperCamelCase__ = self.tokenizer.model_input_names UpperCamelCase__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> str: '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , __a , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , __a , ) return self.image_processor
706
"""simple docstring""" A__ : Tuple= """Alexander Joslin""" import operator as op from .stack import Stack def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} UpperCamelCase__ = Stack() UpperCamelCase__ = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(SCREAMING_SNAKE_CASE ) ) elif i in operators: # RULE 2 operator_stack.push(SCREAMING_SNAKE_CASE ) elif i == ")": # RULE 4 UpperCamelCase__ = operator_stack.peek() operator_stack.pop() UpperCamelCase__ = operand_stack.peek() operand_stack.pop() UpperCamelCase__ = operand_stack.peek() operand_stack.pop() UpperCamelCase__ = operators[opr](SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) operand_stack.push(SCREAMING_SNAKE_CASE ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": A__ : int= """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
20
0
"""simple docstring""" import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __lowerCamelCase ( UpperCAmelCase_ , unittest.TestCase ): a : str =CTRLTokenizer a : Union[str, Any] =False a : Any =False def SCREAMING_SNAKE_CASE__ ( self ) -> str: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = ['adapt', 're@@', 'a@@', 'apt', 'c@@', 't', '<unk>'] UpperCamelCase__ = dict(zip(_snake_case , range(len(_snake_case ) ) ) ) UpperCamelCase__ = ['#version: 0.2', 'a p', 'ap t</w>', 'r e', 'a d', 'ad apt</w>', ''] UpperCamelCase__ = {'unk_token': '<unk>'} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_snake_case ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_snake_case ) ) def SCREAMING_SNAKE_CASE__ ( self , **snake_case_ ) -> Any: kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **_snake_case ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Union[str, Any]: UpperCamelCase__ = 'adapt react readapt apt' UpperCamelCase__ = 'adapt react readapt apt' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = 'adapt react readapt apt' UpperCamelCase__ = 'adapt re@@ a@@ c@@ t re@@ adapt apt'.split() UpperCamelCase__ = tokenizer.tokenize(_snake_case ) self.assertListEqual(_snake_case , _snake_case ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(_snake_case ) , _snake_case )
707
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py A__ : Any= """src/diffusers""" # Matches is_xxx_available() A__ : Tuple= re.compile(r"""is\_([a-z_]*)_available\(\)""") # Matches from xxx import bla A__ : Any= re.compile(r"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""") A__ : Optional[Any]= """ {0} = None """ A__ : List[Any]= """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) """ A__ : Dict= """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ = _re_backend.findall(SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) == 0: return None return "_and_".join(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( ) -> str: """simple docstring""" with open(os.path.join(SCREAMING_SNAKE_CASE , '__init__.py' ) , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.readlines() # Get to the point we do the actual imports for type checking UpperCamelCase__ = 0 UpperCamelCase__ = {} # Go through the end of the file while line_index < len(SCREAMING_SNAKE_CASE ): # If the line contains is_backend_available, we grab all objects associated with the `else` block UpperCamelCase__ = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('else:' ): line_index += 1 line_index += 1 UpperCamelCase__ = [] # Until we unindent, add backend objects to the list while line_index < len(SCREAMING_SNAKE_CASE ) and len(lines[line_index] ) > 1: UpperCamelCase__ = lines[line_index] UpperCamelCase__ = _re_single_line_import.search(SCREAMING_SNAKE_CASE ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(SCREAMING_SNAKE_CASE ) > 0: UpperCamelCase__ = objects else: line_index += 1 return backend_specific_objects def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if name.isupper(): return DUMMY_CONSTANT.format(SCREAMING_SNAKE_CASE ) elif name.islower(): return DUMMY_FUNCTION.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: return DUMMY_CLASS.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" if backend_specific_objects is None: UpperCamelCase__ = read_init() # For special correspondence backend to module name as used in the function requires_modulename UpperCamelCase__ = {} for backend, objects in backend_specific_objects.items(): UpperCamelCase__ = '[' + ', '.join(F'"{b}"' for b in backend.split('_and_' ) ) + ']' UpperCamelCase__ = '# This file is autogenerated by the command `make fix-copies`, do not edit.\n' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for o in objects] ) UpperCamelCase__ = dummy_file return dummy_files def lowerCAmelCase_( SCREAMING_SNAKE_CASE=False ) -> int: """simple docstring""" UpperCamelCase__ = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py UpperCamelCase__ = {'torch': 'pt'} # Locate actual dummy modules and read their content. UpperCamelCase__ = os.path.join(SCREAMING_SNAKE_CASE , 'utils' ) UpperCamelCase__ = { backend: os.path.join(SCREAMING_SNAKE_CASE , F'dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py' ) for backend in dummy_files.keys() } UpperCamelCase__ = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(SCREAMING_SNAKE_CASE ): with open(SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.read() else: UpperCamelCase__ = '' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( F'Updating diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py as the main ' '__init__ has new objects.' ) with open(dummy_file_paths[backend] , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( 'The main __init__ has objects that are not present in ' F'diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py. Run `make fix-copies` ' 'to fix this.' ) if __name__ == "__main__": A__ : Any= argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") A__ : Optional[int]= parser.parse_args() check_dummies(args.fix_and_overwrite)
20
0
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" if digit_amount > 0: return round(number - int(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) return number - int(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(decimal_isolate(1.5_3, 0)) print(decimal_isolate(35.3_45, 1)) print(decimal_isolate(35.3_45, 2)) print(decimal_isolate(35.3_45, 3)) print(decimal_isolate(-14.7_89, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.1_23, 1)) print(decimal_isolate(-14.1_23, 2)) print(decimal_isolate(-14.1_23, 3))
708
"""simple docstring""" # Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file A__ : Optional[Any]= """Run commands across TPU VMs for initial setup before running `accelerate launch`.""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> Dict: """simple docstring""" if subparsers is not None: UpperCamelCase__ = subparsers.add_parser('tpu-config' , description=_description ) else: UpperCamelCase__ = argparse.ArgumentParser('Accelerate tpu-config command' , description=_description ) # Core arguments UpperCamelCase__ = parser.add_argument_group( 'Config Arguments' , 'Arguments that can be configured through `accelerate config`.' ) config_args.add_argument( '--config_file' , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , help='Path to the config file to use for accelerate.' , ) config_args.add_argument( '--tpu_name' , default=SCREAMING_SNAKE_CASE , help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.' , ) config_args.add_argument( '--tpu_zone' , default=SCREAMING_SNAKE_CASE , help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.' , ) UpperCamelCase__ = parser.add_argument_group('TPU Arguments' , 'Arguments for options ran inside the TPU.' ) pod_args.add_argument( '--use_alpha' , action='store_true' , help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.' , ) pod_args.add_argument( '--command_file' , default=SCREAMING_SNAKE_CASE , help='The path to the file containing the commands to run on the pod on startup.' , ) pod_args.add_argument( '--command' , action='append' , nargs='+' , help='A command to run on the pod. Can be passed multiple times.' , ) pod_args.add_argument( '--install_accelerate' , action='store_true' , help='Whether to install accelerate on the pod. Defaults to False.' , ) pod_args.add_argument( '--accelerate_version' , default='latest' , help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.' , ) pod_args.add_argument( '--debug' , action='store_true' , help='If set, will print the command that would be run instead of running it.' ) if subparsers is not None: parser.set_defaults(func=SCREAMING_SNAKE_CASE ) return parser def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase__ = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: UpperCamelCase__ = defaults.command_file if not args.command and defaults.commands is not None: UpperCamelCase__ = defaults.commands if not args.tpu_name: UpperCamelCase__ = defaults.tpu_name if not args.tpu_zone: UpperCamelCase__ = defaults.tpu_zone if args.accelerate_version == "dev": UpperCamelCase__ = 'git+https://github.com/huggingface/accelerate.git' elif args.accelerate_version == "latest": UpperCamelCase__ = 'accelerate -U' elif isinstance(parse(args.accelerate_version ) , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = F'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError('You must specify either a command file or a command to run on the pod.' ) if args.command_file: with open(args.command_file , 'r' ) as f: UpperCamelCase__ = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate UpperCamelCase__ = ['cd /usr/share'] if args.install_accelerate: new_cmd += [F'pip install {args.accelerate_version}'] new_cmd += args.command UpperCamelCase__ = '; '.join(SCREAMING_SNAKE_CASE ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess UpperCamelCase__ = ['gcloud'] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'Running {" ".join(SCREAMING_SNAKE_CASE )}' ) return subprocess.run(SCREAMING_SNAKE_CASE ) print('Successfully setup pod.' ) def lowerCAmelCase_( ) -> int: """simple docstring""" UpperCamelCase__ = tpu_command_parser() UpperCamelCase__ = parser.parse_args() tpu_command_launcher(SCREAMING_SNAKE_CASE )
20
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = 1 UpperCamelCase__ = 3 UpperCamelCase__ = (32, 32) UpperCamelCase__ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_a ) return image @property def SCREAMING_SNAKE_CASE__ ( self ) -> str: torch.manual_seed(0 ) UpperCamelCase__ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) return model @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: torch.manual_seed(0 ) UpperCamelCase__ = 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 , ) return model @property def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: torch.manual_seed(0 ) UpperCamelCase__ = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5006 , ) return RobertaSeriesModelWithTransformation(_a ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: def extract(*snake_case_ , **snake_case_ ): class __lowerCamelCase : def __init__( self ) -> Any: UpperCamelCase__ = torch.ones([0] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Optional[Any]: self.pixel_values.to(_a ) return self return Out() return extract def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = """cpu""" # ensure determinism for the device-dependent torch.Generator UpperCamelCase__ = self.dummy_cond_unet UpperCamelCase__ = PNDMScheduler(skip_prk_steps=_a ) UpperCamelCase__ = self.dummy_vae UpperCamelCase__ = self.dummy_text_encoder UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta' ) UpperCamelCase__ = 77 UpperCamelCase__ = self.dummy_image.to(_a ) UpperCamelCase__ = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk UpperCamelCase__ = AltDiffusionImgaImgPipeline( unet=_a , scheduler=_a , vae=_a , text_encoder=_a , tokenizer=_a , safety_checker=_a , feature_extractor=self.dummy_extractor , ) UpperCamelCase__ = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=_a ) UpperCamelCase__ = alt_pipe.to(_a ) alt_pipe.set_progress_bar_config(disable=_a ) UpperCamelCase__ = """A painting of a squirrel eating a burger""" UpperCamelCase__ = torch.Generator(device=_a ).manual_seed(0 ) UpperCamelCase__ = alt_pipe( [prompt] , generator=_a , guidance_scale=6.0 , num_inference_steps=2 , output_type='np' , image=_a , ) UpperCamelCase__ = output.images UpperCamelCase__ = torch.Generator(device=_a ).manual_seed(0 ) UpperCamelCase__ = alt_pipe( [prompt] , generator=_a , guidance_scale=6.0 , num_inference_steps=2 , output_type='np' , image=_a , return_dict=_a , )[0] UpperCamelCase__ = image[0, -3:, -3:, -1] UpperCamelCase__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCamelCase__ = np.array([0.4_427, 0.3_731, 0.4_249, 0.4_941, 0.4_546, 0.4_148, 0.4_193, 0.4_666, 0.4_499] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5E-3 @unittest.skipIf(torch_device != 'cuda' , 'This test requires a GPU' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = self.dummy_cond_unet UpperCamelCase__ = PNDMScheduler(skip_prk_steps=_a ) UpperCamelCase__ = self.dummy_vae UpperCamelCase__ = self.dummy_text_encoder UpperCamelCase__ = XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta' ) UpperCamelCase__ = 77 UpperCamelCase__ = self.dummy_image.to(_a ) # put models in fp16 UpperCamelCase__ = unet.half() UpperCamelCase__ = vae.half() UpperCamelCase__ = bert.half() # make sure here that pndm scheduler skips prk UpperCamelCase__ = AltDiffusionImgaImgPipeline( unet=_a , scheduler=_a , vae=_a , text_encoder=_a , tokenizer=_a , safety_checker=_a , feature_extractor=self.dummy_extractor , ) UpperCamelCase__ = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=_a ) UpperCamelCase__ = alt_pipe.to(_a ) alt_pipe.set_progress_bar_config(disable=_a ) UpperCamelCase__ = """A painting of a squirrel eating a burger""" UpperCamelCase__ = torch.manual_seed(0 ) UpperCamelCase__ = alt_pipe( [prompt] , generator=_a , num_inference_steps=2 , output_type='np' , image=_a , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != 'cuda' , 'This test requires a GPU' ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) # resize to resolution that is divisible by 8 but not 16 or 32 UpperCamelCase__ = init_image.resize((760, 504) ) UpperCamelCase__ = """BAAI/AltDiffusion""" UpperCamelCase__ = AltDiffusionImgaImgPipeline.from_pretrained( _a , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() UpperCamelCase__ = """A fantasy landscape, trending on artstation""" UpperCamelCase__ = torch.manual_seed(0 ) UpperCamelCase__ = pipe( prompt=_a , image=_a , strength=0.75 , guidance_scale=7.5 , generator=_a , output_type='np' , ) UpperCamelCase__ = output.images[0] UpperCamelCase__ = image[255:258, 383:386, -1] assert image.shape == (504, 760, 3) UpperCamelCase__ = np.array([0.9_358, 0.9_397, 0.9_599, 0.9_901, 1.0_000, 1.0_000, 0.9_882, 1.0_000, 1.0_000] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) UpperCamelCase__ = init_image.resize((768, 512) ) UpperCamelCase__ = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy' ) UpperCamelCase__ = """BAAI/AltDiffusion""" UpperCamelCase__ = AltDiffusionImgaImgPipeline.from_pretrained( _a , safety_checker=_a , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() UpperCamelCase__ = """A fantasy landscape, trending on artstation""" UpperCamelCase__ = torch.manual_seed(0 ) UpperCamelCase__ = pipe( prompt=_a , image=_a , strength=0.75 , guidance_scale=7.5 , generator=_a , output_type='np' , ) UpperCamelCase__ = output.images[0] assert image.shape == (512, 768, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1E-2
709
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : List[str]= logging.get_logger(__name__) class __lowerCamelCase ( _a ): a : Optional[int] ="""timm_backbone""" def __init__( self , snake_case_=None , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=None , **snake_case_ , ) -> Dict: super().__init__(**snake_case_ ) UpperCamelCase__ = backbone UpperCamelCase__ = num_channels UpperCamelCase__ = features_only UpperCamelCase__ = use_pretrained_backbone UpperCamelCase__ = True UpperCamelCase__ = out_indices if out_indices is not None else (-1,)
20
0
"""simple docstring""" import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = np.max(_outputs , axis=-1 , keepdims=__UpperCamelCase ) UpperCamelCase__ = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=__UpperCamelCase ) class __lowerCamelCase ( SCREAMING_SNAKE_CASE_ ): a : List[Any] ="""sigmoid""" a : Tuple ="""softmax""" a : List[str] ="""none""" @add_end_docstrings( SCREAMING_SNAKE_CASE_ , R"""\n return_all_scores (`bool`, *optional*, defaults to `False`):\n Whether to return all prediction scores or just the one of the predicted class.\n function_to_apply (`str`, *optional*, defaults to `\"default\"`):\n The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n has several labels, will apply the softmax function on the output.\n - `\"sigmoid\"`: Applies the sigmoid function on the output.\n - `\"softmax\"`: Applies the softmax function on the output.\n - `\"none\"`: Does not apply any function on the output.\n """ , ) class __lowerCamelCase ( SCREAMING_SNAKE_CASE_ ): a : List[str] =False a : Dict =ClassificationFunction.NONE def __init__( self , **snake_case_ ) -> List[Any]: super().__init__(**UpperCamelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_=None , snake_case_=None , snake_case_="" , **snake_case_ ) -> Dict: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" UpperCamelCase__ = tokenizer_kwargs UpperCamelCase__ = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: UpperCamelCase__ = self.model.config.return_all_scores if isinstance(UpperCamelCase__ , UpperCamelCase__ ) or top_k is None: UpperCamelCase__ = top_k UpperCamelCase__ = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , UpperCamelCase__ , ) if return_all_scores: UpperCamelCase__ = None else: UpperCamelCase__ = 1 if isinstance(UpperCamelCase__ , UpperCamelCase__ ): UpperCamelCase__ = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: UpperCamelCase__ = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *snake_case_ , **snake_case_ ) -> int: UpperCamelCase__ = super().__call__(*UpperCamelCase__ , **UpperCamelCase__ ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. UpperCamelCase__ = '''top_k''' not in kwargs if isinstance(args[0] , UpperCamelCase__ ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , **snake_case_ ) -> Union[str, Any]: UpperCamelCase__ = self.framework if isinstance(UpperCamelCase__ , UpperCamelCase__ ): return self.tokenizer(**UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) elif isinstance(UpperCamelCase__ , UpperCamelCase__ ) and len(UpperCamelCase__ ) == 1 and isinstance(inputs[0] , UpperCamelCase__ ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) elif isinstance(UpperCamelCase__ , UpperCamelCase__ ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: return self.model(**UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_=None , snake_case_=1 , snake_case_=True ) -> str: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: UpperCamelCase__ = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: UpperCamelCase__ = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: UpperCamelCase__ = self.model.config.function_to_apply else: UpperCamelCase__ = ClassificationFunction.NONE UpperCamelCase__ = model_outputs['''logits'''][0] UpperCamelCase__ = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: UpperCamelCase__ = sigmoid(UpperCamelCase__ ) elif function_to_apply == ClassificationFunction.SOFTMAX: UpperCamelCase__ = softmax(UpperCamelCase__ ) elif function_to_apply == ClassificationFunction.NONE: UpperCamelCase__ = outputs else: raise ValueError(F'Unrecognized `function_to_apply` argument: {function_to_apply}' ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} UpperCamelCase__ = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(UpperCamelCase__ ) ] if not _legacy: dict_scores.sort(key=lambda snake_case_ : x["score"] , reverse=UpperCamelCase__ ) if top_k is not None: UpperCamelCase__ = dict_scores[:top_k] return dict_scores
710
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType A__ : Any= logging.get_logger(__name__) A__ : str= { """microsoft/layoutlmv3-base""": """https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json""", } class __lowerCamelCase ( _a ): a : List[str] ="""layoutlmv3""" def __init__( self , snake_case_=5_0265 , snake_case_=768 , snake_case_=12 , snake_case_=12 , snake_case_=3072 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=2 , snake_case_=0.02 , snake_case_=1E-5 , snake_case_=1 , snake_case_=0 , snake_case_=2 , snake_case_=1024 , snake_case_=128 , snake_case_=128 , snake_case_=True , snake_case_=32 , snake_case_=128 , snake_case_=64 , snake_case_=256 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=224 , snake_case_=3 , snake_case_=16 , snake_case_=None , **snake_case_ , ) -> Union[str, Any]: super().__init__( vocab_size=snake_case_ , hidden_size=snake_case_ , num_hidden_layers=snake_case_ , num_attention_heads=snake_case_ , intermediate_size=snake_case_ , hidden_act=snake_case_ , hidden_dropout_prob=snake_case_ , attention_probs_dropout_prob=snake_case_ , max_position_embeddings=snake_case_ , type_vocab_size=snake_case_ , initializer_range=snake_case_ , layer_norm_eps=snake_case_ , pad_token_id=snake_case_ , bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ , ) UpperCamelCase__ = max_ad_position_embeddings UpperCamelCase__ = coordinate_size UpperCamelCase__ = shape_size UpperCamelCase__ = has_relative_attention_bias UpperCamelCase__ = rel_pos_bins UpperCamelCase__ = max_rel_pos UpperCamelCase__ = has_spatial_attention_bias UpperCamelCase__ = rel_ad_pos_bins UpperCamelCase__ = max_rel_ad_pos UpperCamelCase__ = text_embed UpperCamelCase__ = visual_embed UpperCamelCase__ = input_size UpperCamelCase__ = num_channels UpperCamelCase__ = patch_size UpperCamelCase__ = classifier_dropout class __lowerCamelCase ( _a ): a : Tuple =version.parse("""1.12""" ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) else: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels'}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: return 12 def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , snake_case_ = 3 , snake_case_ = 40 , snake_case_ = 40 , ) -> Mapping[str, Any]: setattr(processor.image_processor , 'apply_ocr' , snake_case_ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase__ = processor.tokenizer.num_special_tokens_to_add(snake_case_ ) UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case_ ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase__ = [[' '.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes UpperCamelCase__ = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) UpperCamelCase__ = self._generate_dummy_images(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) UpperCamelCase__ = dict( processor( snake_case_ , text=snake_case_ , boxes=snake_case_ , return_tensors=snake_case_ , ) ) return inputs
20
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, ) A__= { """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: A__= ["""OwlViTFeatureExtractor"""] A__= ["""OwlViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__= [ """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 A__= _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
711
"""simple docstring""" from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class __lowerCamelCase : def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=2 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> Tuple: UpperCamelCase__ = parent UpperCamelCase__ = 13 UpperCamelCase__ = 7 UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = 99 UpperCamelCase__ = 384 UpperCamelCase__ = 2 UpperCamelCase__ = 4 UpperCamelCase__ = 37 UpperCamelCase__ = 'gelu' UpperCamelCase__ = 0.1 UpperCamelCase__ = 0.1 UpperCamelCase__ = 512 UpperCamelCase__ = 16 UpperCamelCase__ = 2 UpperCamelCase__ = 0.02 UpperCamelCase__ = 3 UpperCamelCase__ = 4 UpperCamelCase__ = 128 UpperCamelCase__ = 2 UpperCamelCase__ = 9 UpperCamelCase__ = 1 UpperCamelCase__ = None def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=snake_case_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertModel(config=snake_case_ ) UpperCamelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} UpperCamelCase__ = [input_ids, input_mask] UpperCamelCase__ = model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertForMaskedLM(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForSequenceClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = self.num_choices UpperCamelCase__ = TFConvBertForMultipleChoice(config=snake_case_ ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForTokenClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = TFConvBertForQuestionAnswering(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class __lowerCamelCase ( _a , _a , unittest.TestCase ): a : Any =( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) a : str =( { """feature-extraction""": TFConvBertModel, """fill-mask""": TFConvBertForMaskedLM, """question-answering""": TFConvBertForQuestionAnswering, """text-classification""": TFConvBertForSequenceClassification, """token-classification""": TFConvBertForTokenClassification, """zero-shot""": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) a : Any =False a : Dict =False a : str =False def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = TFConvBertModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = True if hasattr(snake_case_ , 'use_cache' ): UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) for model_class in self.all_model_classes: UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ ) UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = len(model(snake_case_ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(snake_case_ , saved_model=snake_case_ ) UpperCamelCase__ = os.path.join(snake_case_ , 'saved_model' , '1' ) UpperCamelCase__ = tf.keras.models.load_model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = outputs['encoder_hidden_states'] UpperCamelCase__ = outputs['encoder_attentions'] else: UpperCamelCase__ = outputs['hidden_states'] UpperCamelCase__ = outputs['attentions'] self.assertEqual(len(snake_case_ ) , snake_case_ ) UpperCamelCase__ = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(snake_case_ ) , snake_case_ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) def check_decoder_attentions_output(snake_case_ ): UpperCamelCase__ = len(snake_case_ ) self.assertEqual(out_len % 2 , 0 ) UpperCamelCase__ = outputs.decoder_attentions self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(snake_case_ ): UpperCamelCase__ = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: UpperCamelCase__ = True UpperCamelCase__ = False UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) UpperCamelCase__ = len(snake_case_ ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_decoder_attentions_output(snake_case_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) # Check attention is always last and order is fine UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(snake_case_ ) ) self.assertEqual(model.config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) @require_tf class __lowerCamelCase ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) UpperCamelCase__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase__ = model(snake_case_ )[0] UpperCamelCase__ = [1, 6, 768] self.assertEqual(output.shape , snake_case_ ) UpperCamelCase__ = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , snake_case_ , atol=1E-4 )
20
0
"""simple docstring""" import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class __lowerCamelCase ( pl.LightningModule ): def __init__( self , snake_case_ ) -> Dict: super().__init__() UpperCamelCase__ = model UpperCamelCase__ = 2 UpperCamelCase__ = nn.Linear(self.model.config.hidden_size , self.num_labels ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: pass def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase__ = LongformerModel.from_pretrained(__snake_case ) UpperCamelCase__ = LightningModel(__snake_case ) UpperCamelCase__ = torch.load(__snake_case , map_location=torch.device('cpu' ) ) lightning_model.load_state_dict(ckpt['state_dict'] ) # init longformer question answering model UpperCamelCase__ = LongformerForQuestionAnswering.from_pretrained(__snake_case ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(__snake_case ) print(F'Conversion successful. Model saved under {pytorch_dump_folder_path}' ) if __name__ == "__main__": A__ : Tuple= argparse.ArgumentParser() # Required parameters parser.add_argument( """--longformer_model""", default=None, type=str, required=True, help="""model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.""", ) parser.add_argument( """--longformer_question_answering_ckpt_path""", default=None, type=str, required=True, help="""Path the official PyTorch Lightning Checkpoint.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) A__ : Union[str, Any]= parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
712
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 1_00_00_00 , SCREAMING_SNAKE_CASE = 10 ) -> int: """simple docstring""" UpperCamelCase__ = defaultdict(SCREAMING_SNAKE_CASE ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: UpperCamelCase__ = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: UpperCamelCase__ = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(SCREAMING_SNAKE_CASE , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"""{solution() = }""")
20
0
from __future__ import annotations def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase__ = [] create_all_state(1 , a__ , a__ , [] , a__ ) return result def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> int: """simple docstring""" if level == 0: total_list.append(current_list[:] ) return for i in range(a__ , total_number - level + 2 ): current_list.append(a__ ) create_all_state(i + 1 , a__ , level - 1 , a__ , a__ ) current_list.pop() def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" for i in total_list: print(*a__ ) if __name__ == "__main__": A__ : Tuple= 4 A__ : Tuple= 2 A__ : Optional[int]= generate_all_combinations(n, k) print_all_state(total_list)
713
"""simple docstring""" import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __lowerCamelCase ( unittest.TestCase ): def __init__( self , snake_case_ , snake_case_=100 , snake_case_=13 , snake_case_=30 , snake_case_=2 , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=10 , snake_case_=0.02 , snake_case_=3 , ) -> Optional[int]: UpperCamelCase__ = parent UpperCamelCase__ = vocab_size UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = patch_size UpperCamelCase__ = num_channels UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCamelCase__ = (image_size // patch_size) ** 2 UpperCamelCase__ = num_patches + 1 def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=snake_case_ , initializer_range=self.initializer_range , ) return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = FlaxBeitModel(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = FlaxBeitForMaskedImageModeling(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.type_sequence_label_size UpperCamelCase__ = FlaxBeitForImageClassification(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase__ = 1 UpperCamelCase__ = FlaxBeitForImageClassification(snake_case_ ) UpperCamelCase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase__ = model(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class __lowerCamelCase ( _a , unittest.TestCase ): a : int =( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE__ ( self ) -> None: UpperCamelCase__ = FlaxBeitModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ['pixel_values'] self.assertListEqual(arg_names[:1] , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ ) UpperCamelCase__ = model_class(snake_case_ ) @jax.jit def model_jitted(snake_case_ , **snake_case_ ): return model(pixel_values=snake_case_ , **snake_case_ ) with self.subTest('JIT Enabled' ): UpperCamelCase__ = model_jitted(**snake_case_ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): UpperCamelCase__ = model_jitted(**snake_case_ ).to_tuple() self.assertEqual(len(snake_case_ ) , len(snake_case_ ) ) for jitted_output, output in zip(snake_case_ , snake_case_ ): self.assertEqual(jitted_output.shape , output.shape ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: for model_class_name in self.all_model_classes: UpperCamelCase__ = model_class_name.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase__ = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(snake_case_ ) def lowerCAmelCase_( ) -> Optional[int]: """simple docstring""" UpperCamelCase__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @require_flax class __lowerCamelCase ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = FlaxBeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ).pixel_values # prepare bool_masked_pos UpperCamelCase__ = np.ones((1, 196) , dtype=snake_case_ ) # forward pass UpperCamelCase__ = model(pixel_values=snake_case_ , bool_masked_pos=snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 196, 8192) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , snake_case_ , atol=1E-2 ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ) # forward pass UpperCamelCase__ = model(**snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 1000) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array([-1.2_385, -1.0_987, -1.0_108] ) self.assertTrue(np.allclose(logits[0, :3] , snake_case_ , atol=1E-4 ) ) UpperCamelCase__ = 281 self.assertEqual(logits.argmax(-1 ).item() , snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ) # forward pass UpperCamelCase__ = model(**snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 2_1841) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array([1.6_881, -0.2_787, 0.5_901] ) self.assertTrue(np.allclose(logits[0, :3] , snake_case_ , atol=1E-4 ) ) UpperCamelCase__ = 2396 self.assertEqual(logits.argmax(-1 ).item() , snake_case_ )
20
0
"""simple docstring""" import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import logging from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors from ..processors.utils import InputFeatures A__ : Optional[Any]= logging.get_logger(__name__) @dataclass class __lowerCamelCase : a : Optional[Any] =field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys() )} ) a : int =field( metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""} ) a : Any =field( default=1_2_8 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) a : Optional[Any] =field( default=UpperCamelCase__ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.task_name.lower() class __lowerCamelCase ( UpperCamelCase__ ): a : Optional[int] ="""train""" a : List[str] ="""dev""" a : List[Any] ="""test""" class __lowerCamelCase ( UpperCamelCase__ ): a : Optional[Any] =4_2 a : Optional[Any] =4_2 a : List[str] =4_2 def __init__( self , snake_case_ , snake_case_ , snake_case_ = None , snake_case_ = Split.train , snake_case_ = None , ) -> List[Any]: warnings.warn( 'This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets ' 'library. You can have a look at this example script for pointers: ' 'https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py' , __A , ) UpperCamelCase__ = args UpperCamelCase__ = glue_processors[args.task_name]() UpperCamelCase__ = glue_output_modes[args.task_name] if isinstance(__A , __A ): try: UpperCamelCase__ = Split[mode] except KeyError: raise KeyError('mode is not a valid split name' ) # Load data features from cache or dataset file UpperCamelCase__ = os.path.join( cache_dir if cache_dir is not None else args.data_dir , F'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}' , ) UpperCamelCase__ = self.processor.get_labels() if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in ( "RobertaTokenizer", "RobertaTokenizerFast", "XLMRobertaTokenizer", "BartTokenizer", "BartTokenizerFast", ): # HACK(label indices are swapped in RoBERTa pretrained model) UpperCamelCase__ , UpperCamelCase__ = label_list[2], label_list[1] UpperCamelCase__ = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. UpperCamelCase__ = cached_features_file + '.lock' with FileLock(__A ): if os.path.exists(__A ) and not args.overwrite_cache: UpperCamelCase__ = time.time() UpperCamelCase__ = torch.load(__A ) logger.info( F'Loading features from cached file {cached_features_file} [took %.3f s]' , time.time() - start ) else: logger.info(F'Creating features from dataset file at {args.data_dir}' ) if mode == Split.dev: UpperCamelCase__ = self.processor.get_dev_examples(args.data_dir ) elif mode == Split.test: UpperCamelCase__ = self.processor.get_test_examples(args.data_dir ) else: UpperCamelCase__ = self.processor.get_train_examples(args.data_dir ) if limit_length is not None: UpperCamelCase__ = examples[:limit_length] UpperCamelCase__ = glue_convert_examples_to_features( __A , __A , max_length=args.max_seq_length , label_list=__A , output_mode=self.output_mode , ) UpperCamelCase__ = time.time() torch.save(self.features , __A ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]' ) def __len__( self ) -> str: return len(self.features ) def __getitem__( self , snake_case_ ) -> InputFeatures: return self.features[i] def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: return self.label_list
714
"""simple docstring""" import sys from collections import defaultdict class __lowerCamelCase : def __init__( self ) -> Tuple: UpperCamelCase__ = [] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: return self.node_position[vertex] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Optional[int]: UpperCamelCase__ = pos def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: UpperCamelCase__ = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: UpperCamelCase__ = 2 * start + 1 else: UpperCamelCase__ = 2 * start + 2 if heap[smallest_child] < heap[start]: UpperCamelCase__ , UpperCamelCase__ = heap[smallest_child], positions[smallest_child] UpperCamelCase__ , UpperCamelCase__ = ( heap[start], positions[start], ) UpperCamelCase__ , UpperCamelCase__ = temp, tempa UpperCamelCase__ = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , snake_case_ ) self.top_to_bottom(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Any: UpperCamelCase__ = position[index] while index != 0: UpperCamelCase__ = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: UpperCamelCase__ = heap[parent] UpperCamelCase__ = position[parent] self.set_position(position[parent] , snake_case_ ) else: UpperCamelCase__ = val UpperCamelCase__ = temp self.set_position(snake_case_ , snake_case_ ) break UpperCamelCase__ = parent else: UpperCamelCase__ = val UpperCamelCase__ = temp self.set_position(snake_case_ , 0 ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Any: UpperCamelCase__ = len(snake_case_ ) // 2 - 1 for i in range(snake_case_ , -1 , -1 ): self.top_to_bottom(snake_case_ , snake_case_ , len(snake_case_ ) , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = positions[0] UpperCamelCase__ = sys.maxsize self.top_to_bottom(snake_case_ , 0 , len(snake_case_ ) , snake_case_ ) return temp def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = Heap() UpperCamelCase__ = [0] * len(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = [-1] * len(SCREAMING_SNAKE_CASE ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph UpperCamelCase__ = [] # Heap of Distance of vertices from their neighboring vertex UpperCamelCase__ = [] for vertex in range(len(SCREAMING_SNAKE_CASE ) ): distance_tv.append(sys.maxsize ) positions.append(SCREAMING_SNAKE_CASE ) heap.node_position.append(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = [] UpperCamelCase__ = 1 UpperCamelCase__ = sys.maxsize for neighbor, distance in adjacency_list[0]: UpperCamelCase__ = 0 UpperCamelCase__ = distance heap.heapify(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for _ in range(1 , len(SCREAMING_SNAKE_CASE ) ): UpperCamelCase__ = heap.delete_minimum(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) UpperCamelCase__ = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(SCREAMING_SNAKE_CASE )] ): UpperCamelCase__ = distance heap.bottom_to_top( SCREAMING_SNAKE_CASE , heap.get_position(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A__ : Dict= int(input("""Enter number of edges: """).strip()) A__ : Dict= defaultdict(list) for _ in range(edges_number): A__ : Dict= [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
20
0
"""simple docstring""" 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 __lowerCamelCase ( __UpperCAmelCase ): a : Union[str, Any] =['''image_processor''', '''tokenizer'''] a : List[str] ='''FlavaImageProcessor''' a : str =('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self , snake_case_=None , snake_case_=None , **snake_case_ ) -> Tuple: UpperCamelCase__ = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , __SCREAMING_SNAKE_CASE , ) UpperCamelCase__ = kwargs.pop('feature_extractor' ) UpperCamelCase__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) UpperCamelCase__ = self.image_processor def __call__( self , snake_case_ = None , snake_case_ = None , snake_case_ = True , snake_case_ = False , snake_case_ = False , snake_case_ = None , snake_case_ = 0 , snake_case_ = None , snake_case_ = None , snake_case_ = None , snake_case_ = None , snake_case_ = None , snake_case_ = False , snake_case_ = False , snake_case_ = False , snake_case_ = False , snake_case_ = True , snake_case_ = None , **snake_case_ , ) -> List[Any]: 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__ = self.tokenizer( text=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE , return_overflowing_tokens=__SCREAMING_SNAKE_CASE , return_special_tokens_mask=__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , return_length=__SCREAMING_SNAKE_CASE , verbose=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) if images is not None: UpperCamelCase__ = self.image_processor( __SCREAMING_SNAKE_CASE , return_image_mask=__SCREAMING_SNAKE_CASE , return_codebook_pixels=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) if text is not None and images is not None: encoding.update(__SCREAMING_SNAKE_CASE ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__SCREAMING_SNAKE_CASE ) , tensor_type=__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE__ ( self , *snake_case_ , **snake_case_ ) -> Tuple: return self.tokenizer.batch_decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE__ ( self , *snake_case_ , **snake_case_ ) -> List[str]: return self.tokenizer.decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.tokenizer.model_input_names UpperCamelCase__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , __SCREAMING_SNAKE_CASE , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE__ ( self ) -> Any: warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , __SCREAMING_SNAKE_CASE , ) return self.image_processor
715
"""simple docstring""" from copy import deepcopy class __lowerCamelCase : def __init__( self , snake_case_ = None , snake_case_ = None ) -> None: if arr is None and size is not None: UpperCamelCase__ = size UpperCamelCase__ = [0] * size elif arr is not None: self.init(snake_case_ ) else: raise ValueError('Either arr or size must be specified' ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: UpperCamelCase__ = len(snake_case_ ) UpperCamelCase__ = deepcopy(snake_case_ ) for i in range(1 , self.size ): UpperCamelCase__ = self.next_(snake_case_ ) if j < self.size: self.tree[j] += self.tree[i] def SCREAMING_SNAKE_CASE__ ( self ) -> list[int]: UpperCamelCase__ = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): UpperCamelCase__ = self.next_(snake_case_ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: return index + (index & (-index)) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> int: return index - (index & (-index)) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value UpperCamelCase__ = self.next_(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: self.add(snake_case_ , value - self.get(snake_case_ ) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: if right == 0: return 0 UpperCamelCase__ = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] UpperCamelCase__ = self.prev(snake_case_ ) return result def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> int: return self.prefix(snake_case_ ) - self.prefix(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: return self.query(snake_case_ , index + 1 ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: value -= self.tree[0] if value < 0: return -1 UpperCamelCase__ = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 UpperCamelCase__ = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
20
0
"""simple docstring""" import argparse import json import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( VideoMAEConfig, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEImageProcessor, ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = VideoMAEConfig() set_architecture_configs(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if "finetuned" not in model_name: UpperCamelCase__ = False if "finetuned" in model_name: UpperCamelCase__ = 'huggingface/label-files' if "kinetics" in model_name: UpperCamelCase__ = 4_00 UpperCamelCase__ = 'kinetics400-id2label.json' elif "ssv2" in model_name: UpperCamelCase__ = 1_74 UpperCamelCase__ = 'something-something-v2-id2label.json' else: raise ValueError('Model name should either contain \'kinetics\' or \'ssv2\' in case it\'s fine-tuned.' ) UpperCamelCase__ = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) UpperCamelCase__ = {int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} UpperCamelCase__ = idalabel UpperCamelCase__ = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if "small" in model_name: UpperCamelCase__ = 3_84 UpperCamelCase__ = 15_36 UpperCamelCase__ = 12 UpperCamelCase__ = 16 UpperCamelCase__ = 12 UpperCamelCase__ = 3 UpperCamelCase__ = 1_92 UpperCamelCase__ = 7_68 elif "large" in model_name: UpperCamelCase__ = 10_24 UpperCamelCase__ = 40_96 UpperCamelCase__ = 24 UpperCamelCase__ = 16 UpperCamelCase__ = 12 UpperCamelCase__ = 8 UpperCamelCase__ = 5_12 UpperCamelCase__ = 20_48 elif "huge" in model_name: UpperCamelCase__ = 12_80 UpperCamelCase__ = 51_20 UpperCamelCase__ = 32 UpperCamelCase__ = 16 UpperCamelCase__ = 12 UpperCamelCase__ = 8 UpperCamelCase__ = 6_40 UpperCamelCase__ = 25_60 elif "base" not in model_name: raise ValueError('Model name should include either "small", "base", "large", or "huge"' ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" if "encoder." in name: UpperCamelCase__ = name.replace('encoder.' , '' ) if "cls_token" in name: UpperCamelCase__ = name.replace('cls_token' , 'videomae.embeddings.cls_token' ) if "decoder_pos_embed" in name: UpperCamelCase__ = name.replace('decoder_pos_embed' , 'decoder.decoder_pos_embed' ) if "pos_embed" in name and "decoder" not in name: UpperCamelCase__ = name.replace('pos_embed' , 'videomae.embeddings.position_embeddings' ) if "patch_embed.proj" in name: UpperCamelCase__ = name.replace('patch_embed.proj' , 'videomae.embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: UpperCamelCase__ = name.replace('patch_embed.norm' , 'videomae.embeddings.norm' ) if "decoder.blocks" in name: UpperCamelCase__ = name.replace('decoder.blocks' , 'decoder.decoder_layers' ) if "blocks" in name: UpperCamelCase__ = name.replace('blocks' , 'videomae.encoder.layer' ) if "attn.proj" in name: UpperCamelCase__ = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name and "bias" not in name: UpperCamelCase__ = name.replace('attn' , 'attention.self' ) if "attn" in name: UpperCamelCase__ = name.replace('attn' , 'attention.attention' ) if "norm1" in name: UpperCamelCase__ = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: UpperCamelCase__ = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: UpperCamelCase__ = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: UpperCamelCase__ = name.replace('mlp.fc2' , 'output.dense' ) if "decoder_embed" in name: UpperCamelCase__ = name.replace('decoder_embed' , 'decoder.decoder_embed' ) if "decoder_norm" in name: UpperCamelCase__ = name.replace('decoder_norm' , 'decoder.decoder_norm' ) if "decoder_pred" in name: UpperCamelCase__ = name.replace('decoder_pred' , 'decoder.decoder_pred' ) if "norm.weight" in name and "decoder" not in name and "fc" not in name: UpperCamelCase__ = name.replace('norm.weight' , 'videomae.layernorm.weight' ) if "norm.bias" in name and "decoder" not in name and "fc" not in name: UpperCamelCase__ = name.replace('norm.bias' , 'videomae.layernorm.bias' ) if "head" in name and "decoder" not in name: UpperCamelCase__ = name.replace('head' , 'classifier' ) return name def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCamelCase__ = orig_state_dict.pop(SCREAMING_SNAKE_CASE ) if key.startswith('encoder.' ): UpperCamelCase__ = key.replace('encoder.' , '' ) if "qkv" in key: UpperCamelCase__ = key.split('.' ) if key.startswith('decoder.blocks' ): UpperCamelCase__ = config.decoder_hidden_size UpperCamelCase__ = int(key_split[2] ) UpperCamelCase__ = 'decoder.decoder_layers.' if "weight" in key: UpperCamelCase__ = val[:dim, :] UpperCamelCase__ = val[dim : dim * 2, :] UpperCamelCase__ = val[-dim:, :] else: UpperCamelCase__ = config.hidden_size UpperCamelCase__ = int(key_split[1] ) UpperCamelCase__ = 'videomae.encoder.layer.' if "weight" in key: UpperCamelCase__ = val[:dim, :] UpperCamelCase__ = val[dim : dim * 2, :] UpperCamelCase__ = val[-dim:, :] else: UpperCamelCase__ = val return orig_state_dict def lowerCAmelCase_( ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename='eating_spaghetti.npy' , repo_type='dataset' ) UpperCamelCase__ = np.load(SCREAMING_SNAKE_CASE ) return list(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = get_videomae_config(SCREAMING_SNAKE_CASE ) if "finetuned" in model_name: UpperCamelCase__ = VideoMAEForVideoClassification(SCREAMING_SNAKE_CASE ) else: UpperCamelCase__ = VideoMAEForPreTraining(SCREAMING_SNAKE_CASE ) # download original checkpoint, hosted on Google Drive UpperCamelCase__ = 'pytorch_model.bin' gdown.cached_download(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , quiet=SCREAMING_SNAKE_CASE ) UpperCamelCase__ = torch.load(SCREAMING_SNAKE_CASE , map_location='cpu' ) if "model" in files: UpperCamelCase__ = files['model'] else: UpperCamelCase__ = files['module'] UpperCamelCase__ = convert_state_dict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) model.load_state_dict(SCREAMING_SNAKE_CASE ) model.eval() # verify model on basic input UpperCamelCase__ = VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) UpperCamelCase__ = prepare_video() UpperCamelCase__ = image_processor(SCREAMING_SNAKE_CASE , return_tensors='pt' ) if "finetuned" not in model_name: UpperCamelCase__ = hf_hub_download(repo_id='hf-internal-testing/bool-masked-pos' , filename='bool_masked_pos.pt' ) UpperCamelCase__ = torch.load(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = model(**SCREAMING_SNAKE_CASE ) UpperCamelCase__ = outputs.logits UpperCamelCase__ = [ 'videomae-small-finetuned-kinetics', 'videomae-small-finetuned-ssv2', # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600) 'videomae-base-short', 'videomae-base-short-finetuned-kinetics', 'videomae-base', 'videomae-base-finetuned-kinetics', 'videomae-large', 'videomae-large-finetuned-kinetics', 'videomae-huge-finetuned-kinetics', # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400) 'videomae-base-short-ssv2', 'videomae-base-short-finetuned-ssv2', 'videomae-base-ssv2', 'videomae-base-finetuned-ssv2', ] # NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5] if model_name == "videomae-small-finetuned-kinetics": UpperCamelCase__ = torch.Size([1, 4_00] ) UpperCamelCase__ = torch.tensor([-0.9291, -0.4061, -0.9307] ) elif model_name == "videomae-small-finetuned-ssv2": UpperCamelCase__ = torch.Size([1, 1_74] ) UpperCamelCase__ = torch.tensor([0.2671, -0.4689, -0.8235] ) elif model_name == "videomae-base": UpperCamelCase__ = torch.Size([1, 14_08, 15_36] ) UpperCamelCase__ = torch.tensor([[0.7739, 0.7968, 0.7089], [0.6701, 0.7487, 0.6209], [0.4287, 0.5158, 0.4773]] ) elif model_name == "videomae-base-short": UpperCamelCase__ = torch.Size([1, 14_08, 15_36] ) UpperCamelCase__ = torch.tensor([[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]] ) # we verified the loss both for normalized and unnormalized targets for this one UpperCamelCase__ = torch.tensor([0.5142] ) if config.norm_pix_loss else torch.tensor([0.6469] ) elif model_name == "videomae-large": UpperCamelCase__ = torch.Size([1, 14_08, 15_36] ) UpperCamelCase__ = torch.tensor([[0.7149, 0.7997, 0.6966], [0.6768, 0.7869, 0.6948], [0.5139, 0.6221, 0.5605]] ) elif model_name == "videomae-large-finetuned-kinetics": UpperCamelCase__ = torch.Size([1, 4_00] ) UpperCamelCase__ = torch.tensor([0.0771, 0.0011, -0.3625] ) elif model_name == "videomae-huge-finetuned-kinetics": UpperCamelCase__ = torch.Size([1, 4_00] ) UpperCamelCase__ = torch.tensor([0.2433, 0.1632, -0.4894] ) elif model_name == "videomae-base-short-finetuned-kinetics": UpperCamelCase__ = torch.Size([1, 4_00] ) UpperCamelCase__ = torch.tensor([0.6588, 0.0990, -0.2493] ) elif model_name == "videomae-base-finetuned-kinetics": UpperCamelCase__ = torch.Size([1, 4_00] ) UpperCamelCase__ = torch.tensor([0.3669, -0.0688, -0.2421] ) elif model_name == "videomae-base-short-ssv2": UpperCamelCase__ = torch.Size([1, 14_08, 15_36] ) UpperCamelCase__ = torch.tensor([[0.4712, 0.5296, 0.5786], [0.2278, 0.2729, 0.4026], [0.0352, 0.0730, 0.2506]] ) elif model_name == "videomae-base-short-finetuned-ssv2": UpperCamelCase__ = torch.Size([1, 1_74] ) UpperCamelCase__ = torch.tensor([-0.0537, -0.1539, -0.3266] ) elif model_name == "videomae-base-ssv2": UpperCamelCase__ = torch.Size([1, 14_08, 15_36] ) UpperCamelCase__ = torch.tensor([[0.8131, 0.8727, 0.8546], [0.7366, 0.9377, 0.8870], [0.5935, 0.8874, 0.8564]] ) elif model_name == "videomae-base-finetuned-ssv2": UpperCamelCase__ = torch.Size([1, 1_74] ) UpperCamelCase__ = torch.tensor([0.1961, -0.8337, -0.6389] ) else: raise ValueError(F'Model name not supported. Should be one of {model_names}' ) # verify logits assert logits.shape == expected_shape if "finetuned" in model_name: assert torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1E-4 ) else: print('Logits:' , logits[0, :3, :3] ) assert torch.allclose(logits[0, :3, :3] , SCREAMING_SNAKE_CASE , atol=1E-4 ) print('Logits ok!' ) # verify loss, if applicable if model_name == "videomae-base-short": UpperCamelCase__ = outputs.loss assert torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1E-4 ) print('Loss ok!' ) if pytorch_dump_folder_path is not None: print(F'Saving model and image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE ) model.save_pretrained(SCREAMING_SNAKE_CASE ) if push_to_hub: print('Pushing to the hub...' ) model.push_to_hub(SCREAMING_SNAKE_CASE , organization='nielsr' ) if __name__ == "__main__": A__ : Optional[Any]= argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&amp;export=download&amp;confirm=t&amp;uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4""", type=str, help=( """URL of the original PyTorch checkpoint (on Google Drive) you\'d like to convert. Should be a direct""" """ download link.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default="""/Users/nielsrogge/Documents/VideoMAE/Test""", type=str, help="""Path to the output PyTorch model directory.""", ) parser.add_argument("""--model_name""", default="""videomae-base""", type=str, help="""Name of the model.""") parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) A__ : Optional[Any]= parser.parse_args() convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
716
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow A__ : Union[str, Any]= logging.getLogger() @unittest.skip("""Temporarily disable the doc tests.""" ) @require_torch @require_tf @slow class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = None , snake_case_ = None , snake_case_ = True , ) -> Tuple: UpperCamelCase__ = [file for file in os.listdir(snake_case_ ) if os.path.isfile(os.path.join(snake_case_ , snake_case_ ) )] if identifier is not None: UpperCamelCase__ = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(snake_case_ , snake_case_ ): for n_ in n_identifier: UpperCamelCase__ = [file for file in files if n_ not in file] else: UpperCamelCase__ = [file for file in files if n_identifier not in file] UpperCamelCase__ = ignore_files or [] ignore_files.append('__init__.py' ) UpperCamelCase__ = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' , snake_case_ ) if only_modules: UpperCamelCase__ = file.split('.' )[0] try: UpperCamelCase__ = getattr(snake_case_ , snake_case_ ) UpperCamelCase__ = doctest.DocTestSuite(snake_case_ ) UpperCamelCase__ = unittest.TextTestRunner().run(snake_case_ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'{module_identifier} is not a module.' ) else: UpperCamelCase__ = doctest.testfile(str('..' / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'modeling' UpperCamelCase__ = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(snake_case_ , identifier=snake_case_ , ignore_files=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'tokenization' self.analyze_directory(snake_case_ , identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = 'configuration' self.analyze_directory(snake_case_ , identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = Path('src/transformers' ) UpperCamelCase__ = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(snake_case_ , n_identifier=snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = Path('docs/source' ) UpperCamelCase__ = ['favicon.ico'] self.analyze_directory(snake_case_ , ignore_files=snake_case_ , only_modules=snake_case_ )
20
0
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __lowerCamelCase ( _a , unittest.TestCase ): a : List[str] =LayoutLMTokenizer a : Optional[Any] =LayoutLMTokenizerFast a : List[str] =True a : Optional[int] =True def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: super().setUp() UpperCamelCase__ = [ '[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE__ ( self , **snake_case_ ) -> Optional[Any]: return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **__A ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: UpperCamelCase__ = 'UNwant\u00E9d,running' UpperCamelCase__ = 'unwanted, running' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = self.tokenizer_class(self.vocab_file ) UpperCamelCase__ = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [7, 4, 5, 10, 8, 9] ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: pass
717
"""simple docstring""" import warnings 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 A__ : str= logging.get_logger(__name__) A__ : List[Any]= { """nvidia/segformer-b0-finetuned-ade-512-512""": ( """https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json""" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class __lowerCamelCase ( _a ): a : Any ="""segformer""" def __init__( self , snake_case_=3 , snake_case_=4 , snake_case_=[2, 2, 2, 2] , snake_case_=[8, 4, 2, 1] , snake_case_=[32, 64, 160, 256] , snake_case_=[7, 3, 3, 3] , snake_case_=[4, 2, 2, 2] , snake_case_=[1, 2, 5, 8] , snake_case_=[4, 4, 4, 4] , snake_case_="gelu" , snake_case_=0.0 , snake_case_=0.0 , snake_case_=0.1 , snake_case_=0.02 , snake_case_=0.1 , snake_case_=1E-6 , snake_case_=256 , snake_case_=255 , **snake_case_ , ) -> Tuple: super().__init__(**snake_case_ ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( 'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be' ' removed, as the behaviour will default to that of reshape_last_stage = True.' , snake_case_ , ) UpperCamelCase__ = num_channels UpperCamelCase__ = num_encoder_blocks UpperCamelCase__ = depths UpperCamelCase__ = sr_ratios UpperCamelCase__ = hidden_sizes UpperCamelCase__ = patch_sizes UpperCamelCase__ = strides UpperCamelCase__ = mlp_ratios UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = classifier_dropout_prob UpperCamelCase__ = initializer_range UpperCamelCase__ = drop_path_rate UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = decoder_hidden_size UpperCamelCase__ = kwargs.get('reshape_last_stage' , snake_case_ ) UpperCamelCase__ = semantic_loss_ignore_index class __lowerCamelCase ( _a ): a : Any =version.parse("""1.11""" ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: return 1E-4 @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: return 12
20
0
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging A__ : Dict= logging.get_logger(__name__) A__ : Optional[int]= { """Visual-Attention-Network/van-base""": ( """https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json""" ), } class __lowerCamelCase ( __snake_case ): a : Dict ="""van""" def __init__( self , snake_case_=224 , snake_case_=3 , snake_case_=[7, 3, 3, 3] , snake_case_=[4, 2, 2, 2] , snake_case_=[64, 128, 320, 512] , snake_case_=[3, 3, 12, 3] , snake_case_=[8, 8, 4, 4] , snake_case_="gelu" , snake_case_=0.02 , snake_case_=1E-6 , snake_case_=1E-2 , snake_case_=0.0 , snake_case_=0.0 , **snake_case_ , ) -> Optional[int]: super().__init__(**_lowercase ) UpperCamelCase__ = image_size UpperCamelCase__ = num_channels UpperCamelCase__ = patch_sizes UpperCamelCase__ = strides UpperCamelCase__ = hidden_sizes UpperCamelCase__ = depths UpperCamelCase__ = mlp_ratios UpperCamelCase__ = hidden_act UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = layer_scale_init_value UpperCamelCase__ = drop_path_rate UpperCamelCase__ = dropout_rate
718
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class __lowerCamelCase ( _a ): @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Union[str, Any]: UpperCamelCase__ = parser.add_parser('download' ) download_parser.add_argument( '--cache-dir' , type=snake_case_ , default=snake_case_ , help='Path to location to store the models' ) download_parser.add_argument( '--force' , action='store_true' , help='Force the model to be download even if already in cache-dir' ) download_parser.add_argument( '--trust-remote-code' , action='store_true' , help='Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine' , ) download_parser.add_argument('model' , type=snake_case_ , help='Name of the model to download' ) download_parser.set_defaults(func=snake_case_ ) def __init__( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: UpperCamelCase__ = model UpperCamelCase__ = cache UpperCamelCase__ = force UpperCamelCase__ = trust_remote_code def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
20
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__ : Optional[int]= { 'configuration_poolformer': [ 'POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PoolFormerConfig', 'PoolFormerOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Union[str, Any]= ['PoolFormerFeatureExtractor'] A__ : int= ['PoolFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple= [ 'POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'PoolFormerForImageClassification', 'PoolFormerModel', 'PoolFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys A__ : Dict= _LazyModule(__name__, globals()["""__file__"""], _import_structure)
719
"""simple docstring""" import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCamelCase ( _a ): def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=False , snake_case_=True , snake_case_="None" , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> str: UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = relative_attention UpperCamelCase__ = position_biased_input UpperCamelCase__ = pos_att_type UpperCamelCase__ = scope def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Any: self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: UpperCamelCase__ = DebertaVaModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ )[0] UpperCamelCase__ = model(snake_case_ , token_type_ids=snake_case_ )[0] UpperCamelCase__ = model(snake_case_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: UpperCamelCase__ = DebertaVaForMaskedLM(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Dict: UpperCamelCase__ = self.num_labels UpperCamelCase__ = DebertaVaForSequenceClassification(snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[int]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = DebertaVaForTokenClassification(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = DebertaVaForQuestionAnswering(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , start_positions=snake_case_ , end_positions=snake_case_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = DebertaVaForMultipleChoice(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __lowerCamelCase ( _a , _a , unittest.TestCase ): a : Any =( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) a : Dict =( { """feature-extraction""": DebertaVaModel, """fill-mask""": DebertaVaForMaskedLM, """question-answering""": DebertaVaForQuestionAnswering, """text-classification""": DebertaVaForSequenceClassification, """token-classification""": DebertaVaForTokenClassification, """zero-shot""": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) a : Tuple =True a : Union[str, Any] =False a : Tuple =False a : Union[str, Any] =False a : Dict =False def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = DebertaVaModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = DebertaVaModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) @require_torch @require_sentencepiece @require_tokenizers class __lowerCamelCase ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: pass @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = DebertaVaModel.from_pretrained('microsoft/deberta-v2-xlarge' ) UpperCamelCase__ = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) UpperCamelCase__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCamelCase__ = model(snake_case_ , attention_mask=snake_case_ )[0] # compare the actual values for a slice. UpperCamelCase__ = torch.tensor( [[[0.2_356, 0.1_948, 0.0_369], [-0.1_063, 0.3_586, -0.5_152], [-0.6_399, -0.0_259, -0.2_525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , snake_case_ , atol=1E-4 ) , F'{output[:, 1:4, 1:4]}' )
20
0
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> list: """simple docstring""" if len(lowerCAmelCase__ ) < 2: return collection def circle_sort_util(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> bool: UpperCamelCase__ = False if low == high: return swapped UpperCamelCase__ = low UpperCamelCase__ = high while left < right: if collection[left] > collection[right]: UpperCamelCase__ , UpperCamelCase__ = ( collection[right], collection[left], ) UpperCamelCase__ = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: UpperCamelCase__ , UpperCamelCase__ = ( collection[right + 1], collection[left], ) UpperCamelCase__ = True UpperCamelCase__ = low + int((high - low) / 2 ) UpperCamelCase__ = circle_sort_util(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) UpperCamelCase__ = circle_sort_util(lowerCAmelCase__ , mid + 1 , lowerCAmelCase__ ) return swapped or left_swap or right_swap UpperCamelCase__ = True while is_not_sorted is True: UpperCamelCase__ = circle_sort_util(lowerCAmelCase__ , 0 , len(lowerCAmelCase__ ) - 1 ) return collection if __name__ == "__main__": A__ : Tuple= input("""Enter numbers separated by a comma:\n""").strip() A__ : List[str]= [int(item) for item in user_input.split(""",""")] print(circle_sort(unsorted))
720
"""simple docstring""" 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 lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = SwinConfig() UpperCamelCase__ = swin_name.split('_' ) UpperCamelCase__ = name_split[1] UpperCamelCase__ = int(name_split[4] ) UpperCamelCase__ = int(name_split[3][-1] ) if model_size == "tiny": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 6, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "small": UpperCamelCase__ = 96 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (3, 6, 12, 24) elif model_size == "base": UpperCamelCase__ = 1_28 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (4, 8, 16, 32) else: UpperCamelCase__ = 1_92 UpperCamelCase__ = (2, 2, 18, 2) UpperCamelCase__ = (6, 12, 24, 48) if "in22k" in swin_name: UpperCamelCase__ = 2_18_41 else: UpperCamelCase__ = 10_00 UpperCamelCase__ = 'huggingface/label-files' UpperCamelCase__ = 'imagenet-1k-id2label.json' UpperCamelCase__ = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) ) UpperCamelCase__ = {int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} UpperCamelCase__ = idalabel UpperCamelCase__ = {v: k for k, v in idalabel.items()} UpperCamelCase__ = img_size UpperCamelCase__ = num_classes UpperCamelCase__ = embed_dim UpperCamelCase__ = depths UpperCamelCase__ = num_heads UpperCamelCase__ = window_size return config def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" if "patch_embed.proj" in name: UpperCamelCase__ = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: UpperCamelCase__ = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: UpperCamelCase__ = 'encoder.' + name if "attn.proj" in name: UpperCamelCase__ = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: UpperCamelCase__ = name.replace('attn' , 'attention.self' ) if "norm1" in name: UpperCamelCase__ = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: UpperCamelCase__ = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: UpperCamelCase__ = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: UpperCamelCase__ = name.replace('mlp.fc2' , 'output.dense' ) if name == "norm.weight": UpperCamelCase__ = 'layernorm.weight' if name == "norm.bias": UpperCamelCase__ = 'layernorm.bias' if "head" in name: UpperCamelCase__ = name.replace('head' , 'classifier' ) else: UpperCamelCase__ = 'swin.' + name return name def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCamelCase__ = orig_state_dict.pop(SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: UpperCamelCase__ = key.split('.' ) UpperCamelCase__ = int(key_split[1] ) UpperCamelCase__ = int(key_split[3] ) UpperCamelCase__ = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: UpperCamelCase__ = val[:dim, :] UpperCamelCase__ = val[ dim : dim * 2, : ] UpperCamelCase__ = val[-dim:, :] else: UpperCamelCase__ = val[ :dim ] UpperCamelCase__ = val[ dim : dim * 2 ] UpperCamelCase__ = val[ -dim: ] else: UpperCamelCase__ = val return orig_state_dict def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = timm.create_model(SCREAMING_SNAKE_CASE , pretrained=SCREAMING_SNAKE_CASE ) timm_model.eval() UpperCamelCase__ = get_swin_config(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = SwinForImageClassification(SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase__ = convert_state_dict(timm_model.state_dict() , SCREAMING_SNAKE_CASE ) model.load_state_dict(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = 'http://images.cocodataset.org/val2017/000000039769.jpg' UpperCamelCase__ = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swin_name.replace('_' , '-' ) ) ) UpperCamelCase__ = Image.open(requests.get(SCREAMING_SNAKE_CASE , stream=SCREAMING_SNAKE_CASE ).raw ) UpperCamelCase__ = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors='pt' ) UpperCamelCase__ = timm_model(inputs['pixel_values'] ) UpperCamelCase__ = 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__": A__ : Optional[Any]= 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.""" ) A__ : Tuple= parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
20
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A__ : Union[str, Any]= { """configuration_convnext""": ["""CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvNextConfig""", """ConvNextOnnxConfig"""] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int]= ["""ConvNextFeatureExtractor"""] A__ : Optional[int]= ["""ConvNextImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple= [ """CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ConvNextForImageClassification""", """ConvNextModel""", """ConvNextPreTrainedModel""", """ConvNextBackbone""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[Any]= [ """TFConvNextForImageClassification""", """TFConvNextModel""", """TFConvNextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys A__ : List[Any]= _LazyModule(__name__, globals()["""__file__"""], _import_structure)
721
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" UpperCamelCase__ = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 50_00 ) -> int: """simple docstring""" UpperCamelCase__ = [(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 ) ): UpperCamelCase__ = pentagonal_nums[j] UpperCamelCase__ = pentagonal_i + pentagonal_j UpperCamelCase__ = 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() = }""")
20
0
"""simple docstring""" import os from pathlib import Path def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase__ = { 'en': 'Machine learning is great, isn\'t it?', 'ru': 'Машинное обучение - это здорово, не так ли?', 'de': 'Maschinelles Lernen ist großartig, nicht wahr?', } # BLUE scores as follows: # "pair": [fairseq, transformers] UpperCamelCase__ = { 'wmt16-en-de-dist-12-1': [28.3, 27.52], 'wmt16-en-de-dist-6-1': [27.4, 27.11], 'wmt16-en-de-12-1': [26.9, 25.75], } UpperCamelCase__ = F'{src_lang}-{tgt_lang}' UpperCamelCase__ = F'\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"allenai/{model_name}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel | fairseq | transformers\n-------|---------|----------\n{model_name} | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don\'t use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n year={{2020}},\n eprint={{2006.10369}},\n archivePrefix={{arXiv}},\n primaryClass={{cs.CL}}\n}}\n```\n\n' model_card_dir.mkdir(parents=SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) UpperCamelCase__ = os.path.join(SCREAMING_SNAKE_CASE , 'README.md' ) print(F'Generating {path}' ) with open(SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as f: f.write(SCREAMING_SNAKE_CASE ) # make sure we are under the root of the project A__ : List[str]= Path(__file__).resolve().parent.parent.parent A__ : Dict= repo_dir / """model_cards""" for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: A__ : Optional[Any]= model_cards_dir / """allenai""" / model_name write_model_card(model_card_dir, src_lang="""en""", tgt_lang="""de""", model_name=model_name)
700
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 50_00_00_00 ) -> int: """simple docstring""" UpperCamelCase__ = set() UpperCamelCase__ = int((limit - 24) ** (1 / 2) ) UpperCamelCase__ = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , SCREAMING_SNAKE_CASE ) ) ) for primea in primes: UpperCamelCase__ = primea * primea for primea in primes: UpperCamelCase__ = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: UpperCamelCase__ = primea * primea * primea * primea UpperCamelCase__ = square + cube + tetr if total >= limit: break ret.add(SCREAMING_SNAKE_CASE ) return len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(F"""{solution() = }""")
20
0
"""simple docstring""" from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake A__ : str= numpy.array([0, 0]) A__ : Optional[int]= numpy.array([0.5, 0.8_6_6_0_2_5_4]) A__ : Dict= numpy.array([1, 0]) A__ : Tuple= [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> list[numpy.ndarray]: """simple docstring""" UpperCamelCase__ = initial_vectors for _ in range(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = iteration_step(SCREAMING_SNAKE_CASE_ ) return vectors def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> list[numpy.ndarray]: """simple docstring""" UpperCamelCase__ = [] for i, start_vector in enumerate(vectors[:-1] ): UpperCamelCase__ = vectors[i + 1] new_vectors.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3 ) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 60 ) ) new_vectors.append(start_vector + difference_vector * 2 / 3 ) new_vectors.append(vectors[-1] ) return new_vectors def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> numpy.ndarray: """simple docstring""" UpperCamelCase__ = numpy.radians(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = numpy.cos(SCREAMING_SNAKE_CASE_ ), numpy.sin(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = numpy.array(((c, -s), (s, c)) ) return numpy.dot(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" UpperCamelCase__ = plt.gca() axes.set_aspect('equal' ) # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() UpperCamelCase__ = zip(*SCREAMING_SNAKE_CASE_ ) plt.plot(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() A__ : List[str]= iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
701
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer A__ : List[Any]= ["""bert-base-uncased""", """bert-base-cased"""] A__ : Optional[int]= """hf-internal-testing/tiny-bert-tf-only""" if is_tf_available(): class __lowerCamelCase ( tf.keras.Model ): def __init__( self , snake_case_ ) -> Optional[int]: super().__init__() UpperCamelCase__ = tokenizer UpperCamelCase__ = AutoConfig.from_pretrained(snake_case_ ) UpperCamelCase__ = TFAutoModel.from_config(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: UpperCamelCase__ = self.tokenizer(snake_case_ ) UpperCamelCase__ = self.bert(**snake_case_ ) return out["pooler_output"] @require_tf @require_tensorflow_text class __lowerCamelCase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ) -> str: super().setUp() UpperCamelCase__ = [ BertTokenizer.from_pretrained(snake_case_ ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false UpperCamelCase__ = [TFBertTokenizer.from_pretrained(snake_case_ ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(snake_case_ , use_fast_bert_tokenizer=snake_case_ ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) UpperCamelCase__ = [ 'This is a straightforward English test sentence.', 'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.', 'Now we\'re going to add some Chinese: 一 二 三 一二三', 'And some much more rare Chinese: 齉 堃 齉堃', 'Je vais aussi écrire en français pour tester les accents', 'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ', ] UpperCamelCase__ = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase__ = tokenizer(snake_case_ , return_tensors='tf' , padding='longest' ) UpperCamelCase__ = tf_tokenizer(snake_case_ ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> str: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = tf_tokenizer(self.paired_sentences ) UpperCamelCase__ = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = tf.function(snake_case_ ) for test_inputs in (self.test_sentences, self.paired_sentences): UpperCamelCase__ = tf.constant(snake_case_ ) UpperCamelCase__ = compiled_tokenizer(snake_case_ ) UpperCamelCase__ = tf_tokenizer(snake_case_ ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: for tf_tokenizer in self.tf_tokenizers: UpperCamelCase__ = ModelToSave(tokenizer=snake_case_ ) UpperCamelCase__ = tf.convert_to_tensor(self.test_sentences ) UpperCamelCase__ = model(snake_case_ ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: UpperCamelCase__ = Path(snake_case_ ) / 'saved.model' model.save(snake_case_ ) UpperCamelCase__ = tf.keras.models.load_model(snake_case_ ) UpperCamelCase__ = loaded_model(snake_case_ ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
20
0
"""simple docstring""" import random def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = False ) -> dict: """simple docstring""" UpperCamelCase__ = {i: [] for i in range(SCREAMING_SNAKE_CASE_ )} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(SCREAMING_SNAKE_CASE_ ) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if random.random() < probability: graph[i].append(SCREAMING_SNAKE_CASE_ ) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(SCREAMING_SNAKE_CASE_ ) return graph def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> dict: """simple docstring""" return { i: [j for j in range(SCREAMING_SNAKE_CASE_ ) if i != j] for i in range(SCREAMING_SNAKE_CASE_ ) } if __name__ == "__main__": import doctest doctest.testmod()
702
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> list[int]: """simple docstring""" UpperCamelCase__ = len(SCREAMING_SNAKE_CASE ) for i in range(SCREAMING_SNAKE_CASE ): for j in range(i + 1 , SCREAMING_SNAKE_CASE ): if numbers[j] < numbers[i]: UpperCamelCase__ , UpperCamelCase__ = numbers[j], numbers[i] return numbers if __name__ == "__main__": A__ : Union[str, Any]= input("""Enter numbers separated by a comma:\n""").strip() A__ : List[Any]= [int(item) for item in user_input.split(""",""")] print(exchange_sort(unsorted))
20
0
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version A__ : Optional[int]= logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""") A__ : int= list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) A__ : List[str]= tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class __lowerCamelCase : a : str =field( default="""cifar10""" , metadata={"""help""": """Name of a dataset from the datasets package"""} ) a : Optional[int] =field( default=__A , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} ) a : int =field( default=__A , metadata={"""help""": """The column name of the images in the files. If not set, will try to use \'image\' or \'img\'."""} , ) a : List[Any] =field(default=__A , metadata={"""help""": """A folder containing the training data."""} ) a : Any =field(default=__A , metadata={"""help""": """A folder containing the validation data."""} ) a : List[Any] =field( default=0.15 , metadata={"""help""": """Percent to split off of train for validation."""} ) a : str =field(default=3_2 , metadata={"""help""": """The size of the square patches to use for masking."""} ) a : Union[str, Any] =field( default=0.6 , metadata={"""help""": """Percentage of patches to mask."""} , ) a : int =field( default=__A , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) a : int =field( default=__A , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: UpperCamelCase__ = {} if self.train_dir is not None: UpperCamelCase__ = self.train_dir if self.validation_dir is not None: UpperCamelCase__ = self.validation_dir UpperCamelCase__ = data_files if data_files else None @dataclass class __lowerCamelCase : a : str =field( default=__A , metadata={ """help""": ( """The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a """ """checkpoint identifier on the hub. """ """Don\'t set if you want to train a model from scratch.""" ) } , ) a : Optional[Any] =field( default=__A , metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(__A )} , ) a : str =field( default=__A , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) a : List[Any] =field( default=__A , metadata={ """help""": ( """Override some existing default config settings when a model is trained from scratch. Example: """ """n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index""" ) } , ) a : List[Any] =field( default=__A , metadata={"""help""": """Where do you want to store (cache) the pretrained models/datasets downloaded from the hub"""} , ) a : int =field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) a : int =field(default=__A , metadata={"""help""": """Name or path of preprocessor config."""} ) a : Any =field( default=__A , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) a : int =field( default=__A , metadata={ """help""": ( """The size (resolution) of each image. If not specified, will use `image_size` of the configuration.""" ) } , ) a : List[Any] =field( default=__A , metadata={ """help""": ( """The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration.""" ) } , ) a : Tuple =field( default=__A , metadata={"""help""": """Stride to use for the encoder."""} , ) class __lowerCamelCase : def __init__( self , snake_case_=192 , snake_case_=32 , snake_case_=4 , snake_case_=0.6 ) -> List[Any]: UpperCamelCase__ = input_size UpperCamelCase__ = mask_patch_size UpperCamelCase__ = model_patch_size UpperCamelCase__ = mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError('Input size must be divisible by mask patch size' ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError('Mask patch size must be divisible by model patch size' ) UpperCamelCase__ = self.input_size // self.mask_patch_size UpperCamelCase__ = self.mask_patch_size // self.model_patch_size UpperCamelCase__ = self.rand_size**2 UpperCamelCase__ = int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self ) -> str: UpperCamelCase__ = np.random.permutation(self.token_count )[: self.mask_count] UpperCamelCase__ = np.zeros(self.token_count , dtype=snake_case_ ) UpperCamelCase__ = 1 UpperCamelCase__ = mask.reshape((self.rand_size, self.rand_size) ) UpperCamelCase__ = mask.repeat(self.scale , axis=0 ).repeat(self.scale , axis=1 ) return torch.tensor(mask.flatten() ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ = torch.stack([example['pixel_values'] for example in examples] ) UpperCamelCase__ = torch.stack([example['mask'] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def lowerCAmelCase_( ) -> Any: """simple docstring""" UpperCamelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCamelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCamelCase__ = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_mim' , __lowercase , __lowercase ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() UpperCamelCase__ = training_args.get_process_log_level() logger.setLevel(__lowercase ) transformers.utils.logging.set_verbosity(__lowercase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. UpperCamelCase__ = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: UpperCamelCase__ = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Initialize our dataset. UpperCamelCase__ = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. UpperCamelCase__ = None if 'validation' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __lowercase ) and data_args.train_val_split > 0.0: UpperCamelCase__ = ds['train'].train_test_split(data_args.train_val_split ) UpperCamelCase__ = split['train'] UpperCamelCase__ = split['test'] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCamelCase__ = { 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name_or_path: UpperCamelCase__ = AutoConfig.from_pretrained(model_args.config_name_or_path , **__lowercase ) elif model_args.model_name_or_path: UpperCamelCase__ = AutoConfig.from_pretrained(model_args.model_name_or_path , **__lowercase ) else: UpperCamelCase__ = CONFIG_MAPPING[model_args.model_type]() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(__lowercase , 'decoder_type' ): UpperCamelCase__ = 'simmim' # adapt config UpperCamelCase__ = model_args.image_size if model_args.image_size is not None else config.image_size UpperCamelCase__ = model_args.patch_size if model_args.patch_size is not None else config.patch_size UpperCamelCase__ = ( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { 'image_size': model_args.image_size, 'patch_size': model_args.patch_size, 'encoder_stride': model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: UpperCamelCase__ = AutoImageProcessor.from_pretrained(model_args.image_processor_name , **__lowercase ) elif model_args.model_name_or_path: UpperCamelCase__ = AutoImageProcessor.from_pretrained(model_args.model_name_or_path , **__lowercase ) else: UpperCamelCase__ = { conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } UpperCamelCase__ = IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: UpperCamelCase__ = AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=__lowercase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch' ) UpperCamelCase__ = AutoModelForMaskedImageModeling.from_config(__lowercase ) if training_args.do_train: UpperCamelCase__ = ds['train'].column_names else: UpperCamelCase__ = ds['validation'].column_names if data_args.image_column_name is not None: UpperCamelCase__ = data_args.image_column_name elif "image" in column_names: UpperCamelCase__ = 'image' elif "img" in column_names: UpperCamelCase__ = 'img' else: UpperCamelCase__ = column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py UpperCamelCase__ = Compose( [ Lambda(lambda SCREAMING_SNAKE_CASE : img.convert('RGB' ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size , scale=(0.67, 1.0) , ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) # create mask generator UpperCamelCase__ = MaskGenerator( input_size=model_args.image_size , mask_patch_size=data_args.mask_patch_size , model_patch_size=model_args.patch_size , mask_ratio=data_args.mask_ratio , ) def preprocess_images(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = [transforms(__lowercase ) for image in examples[image_column_name]] UpperCamelCase__ = [mask_generator() for i in range(len(examples[image_column_name] ) )] return examples if training_args.do_train: if "train" not in ds: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: UpperCamelCase__ = ds['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__lowercase ) if training_args.do_eval: if "validation" not in ds: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: UpperCamelCase__ = ( ds['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__lowercase ) # Initialize our trainer UpperCamelCase__ = Trainer( model=__lowercase , args=__lowercase , train_dataset=ds['train'] if training_args.do_train else None , eval_dataset=ds['validation'] if training_args.do_eval else None , tokenizer=__lowercase , data_collator=__lowercase , ) # Training if training_args.do_train: UpperCamelCase__ = None if training_args.resume_from_checkpoint is not None: UpperCamelCase__ = training_args.resume_from_checkpoint elif last_checkpoint is not None: UpperCamelCase__ = last_checkpoint UpperCamelCase__ = trainer.train(resume_from_checkpoint=__lowercase ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: UpperCamelCase__ = trainer.evaluate() trainer.log_metrics('eval' , __lowercase ) trainer.save_metrics('eval' , __lowercase ) # Write model card and (optionally) push to hub UpperCamelCase__ = { 'finetuned_from': model_args.model_name_or_path, 'tasks': 'masked-image-modeling', 'dataset': data_args.dataset_name, 'tags': ['masked-image-modeling'], } if training_args.push_to_hub: trainer.push_to_hub(**__lowercase ) else: trainer.create_model_card(**__lowercase ) if __name__ == "__main__": main()
703
"""simple docstring""" import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("""9.1.0"""): A__ : str= { """linear""": PIL.Image.Resampling.BILINEAR, """bilinear""": PIL.Image.Resampling.BILINEAR, """bicubic""": PIL.Image.Resampling.BICUBIC, """lanczos""": PIL.Image.Resampling.LANCZOS, """nearest""": PIL.Image.Resampling.NEAREST, } else: A__ : str= { """linear""": PIL.Image.LINEAR, """bilinear""": PIL.Image.BILINEAR, """bicubic""": PIL.Image.BICUBIC, """lanczos""": PIL.Image.LANCZOS, """nearest""": PIL.Image.NEAREST, } def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = (images / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() UpperCamelCase__ = numpy_to_pil(SCREAMING_SNAKE_CASE ) return images def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if images.ndim == 3: UpperCamelCase__ = images[None, ...] UpperCamelCase__ = (images * 2_55).round().astype('uint8' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images UpperCamelCase__ = [Image.fromarray(image.squeeze() , mode='L' ) for image in images] else: UpperCamelCase__ = [Image.fromarray(SCREAMING_SNAKE_CASE ) for image in images] return pil_images
20
0
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Any= logging.get_logger(__name__) A__ : List[Any]= { """google/pix2struct-textcaps-base""": ( """https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json""" ), } class __lowerCamelCase ( __lowercase ): a : List[Any] ="""pix2struct_text_model""" a : List[Any] =["""past_key_values"""] a : Union[str, Any] ={ """hidden_size""": """hidden_size""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , snake_case_=5_0244 , snake_case_=768 , snake_case_=64 , snake_case_=2048 , snake_case_=12 , snake_case_=12 , snake_case_=32 , snake_case_=128 , snake_case_=0.1 , snake_case_=1E-6 , snake_case_=1.0 , snake_case_="gelu_new" , snake_case_=0 , snake_case_=False , snake_case_=0 , snake_case_=1 , snake_case_=False , snake_case_=True , **snake_case_ , ) -> Dict: UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = d_kv UpperCamelCase__ = d_ff UpperCamelCase__ = num_layers UpperCamelCase__ = num_heads UpperCamelCase__ = relative_attention_num_buckets UpperCamelCase__ = relative_attention_max_distance UpperCamelCase__ = dropout_rate UpperCamelCase__ = layer_norm_epsilon UpperCamelCase__ = initializer_factor UpperCamelCase__ = use_cache UpperCamelCase__ = eos_token_id UpperCamelCase__ = decoder_start_token_id # for backwards compatibility UpperCamelCase__ = dense_act_fn super().__init__( pad_token_id=_A , eos_token_id=_A , decoder_start_token_id=_A , tie_word_embeddings=_A , is_decoder=_A , **_A , ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , snake_case_ , **snake_case_ ) -> Optional[Any]: cls._set_token_in_kwargs(_A ) UpperCamelCase__ , UpperCamelCase__ = cls.get_config_dict(_A , **_A ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('model_type' ) == "pix2struct": UpperCamelCase__ = config_dict['text_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(_A , **_A ) class __lowerCamelCase ( __lowercase ): a : List[str] ="""pix2struct_vision_model""" def __init__( self , snake_case_=768 , snake_case_=768 , snake_case_=2048 , snake_case_=64 , snake_case_=12 , snake_case_=12 , snake_case_="gelu_new" , snake_case_=1E-6 , snake_case_=0.0 , snake_case_=0.0 , snake_case_=1E-10 , snake_case_=1.0 , snake_case_=4096 , snake_case_=32 , snake_case_=128 , **snake_case_ , ) -> Tuple: super().__init__(**_A ) UpperCamelCase__ = hidden_size UpperCamelCase__ = patch_embed_hidden_size UpperCamelCase__ = d_ff UpperCamelCase__ = dropout_rate UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = initializer_range UpperCamelCase__ = initializer_factor UpperCamelCase__ = attention_dropout UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = dense_act_fn UpperCamelCase__ = seq_len UpperCamelCase__ = relative_attention_num_buckets UpperCamelCase__ = relative_attention_max_distance UpperCamelCase__ = d_kv @classmethod def SCREAMING_SNAKE_CASE__ ( cls , snake_case_ , **snake_case_ ) -> Optional[Any]: cls._set_token_in_kwargs(_A ) UpperCamelCase__ , UpperCamelCase__ = cls.get_config_dict(_A , **_A ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('model_type' ) == "pix2struct": UpperCamelCase__ = 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(_A , **_A ) class __lowerCamelCase ( __lowercase ): a : Union[str, Any] ="""pix2struct""" a : int =True def __init__( self , snake_case_=None , snake_case_=None , snake_case_=1.0 , snake_case_=0.02 , snake_case_=False , snake_case_=False , snake_case_=True , **snake_case_ , ) -> Any: super().__init__(tie_word_embeddings=_A , is_encoder_decoder=_A , **_A ) if text_config is None: UpperCamelCase__ = {} logger.info('text_config is None. Initializing the Pix2StructTextConfig with default values.' ) if vision_config is None: UpperCamelCase__ = {} logger.info('vision_config is None. Initializing the Pix2StructVisionConfig with default values.' ) UpperCamelCase__ = PixaStructTextConfig(**_A ) UpperCamelCase__ = PixaStructVisionConfig(**_A ) UpperCamelCase__ = self.text_config.decoder_start_token_id UpperCamelCase__ = self.text_config.pad_token_id UpperCamelCase__ = self.text_config.eos_token_id UpperCamelCase__ = initializer_factor UpperCamelCase__ = initializer_range UpperCamelCase__ = self.initializer_range UpperCamelCase__ = self.initializer_range UpperCamelCase__ = is_vqa @classmethod def SCREAMING_SNAKE_CASE__ ( cls , snake_case_ , snake_case_ , **snake_case_ ) -> Optional[Any]: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_A ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = copy.deepcopy(self.__dict__ ) UpperCamelCase__ = self.text_config.to_dict() UpperCamelCase__ = self.vision_config.to_dict() UpperCamelCase__ = self.__class__.model_type return output
704
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging A__ : Dict= logging.get_logger(__name__) A__ : str= {"""vocab_file""": """spiece.model"""} A__ : Union[str, Any]= { """vocab_file""": { """t5-small""": """https://huggingface.co/t5-small/resolve/main/spiece.model""", """t5-base""": """https://huggingface.co/t5-base/resolve/main/spiece.model""", """t5-large""": """https://huggingface.co/t5-large/resolve/main/spiece.model""", """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/spiece.model""", """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/spiece.model""", } } # TODO(PVP) - this should be removed in Transformers v5 A__ : Union[str, Any]= { """t5-small""": 5_12, """t5-base""": 5_12, """t5-large""": 5_12, """t5-3b""": 5_12, """t5-11b""": 5_12, } A__ : Optional[Any]= """▁""" class __lowerCamelCase ( _a ): a : Dict =VOCAB_FILES_NAMES a : str =PRETRAINED_VOCAB_FILES_MAP a : Union[str, Any] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : List[str] =["""input_ids""", """attention_mask"""] def __init__( self , snake_case_ , snake_case_="</s>" , snake_case_="<unk>" , snake_case_="<pad>" , snake_case_=100 , snake_case_=None , snake_case_ = None , snake_case_=True , **snake_case_ , ) -> None: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: UpperCamelCase__ = [F'<extra_id_{i}>' for i in range(snake_case_ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens UpperCamelCase__ = len(set(filter(lambda snake_case_ : bool('extra_id' in str(snake_case_ ) ) , snake_case_ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' ' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids' ' tokens' ) if legacy: logger.warning_once( F'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to' ' read the related pull request available at https://github.com/huggingface/transformers/pull/24565' ) UpperCamelCase__ = legacy UpperCamelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=snake_case_ , unk_token=snake_case_ , pad_token=snake_case_ , extra_ids=snake_case_ , additional_special_tokens=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , legacy=snake_case_ , **snake_case_ , ) UpperCamelCase__ = vocab_file UpperCamelCase__ = extra_ids UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) @staticmethod def SCREAMING_SNAKE_CASE__ ( snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: UpperCamelCase__ = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( 'This tokenizer was incorrectly instantiated with a model max length of' F' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' ' behavior is kept to avoid breaking backwards compatibility when padding/encoding with' ' `truncation is True`.\n- Be aware that you SHOULD NOT rely on' F' {pretrained_model_name_or_path} automatically truncating your input to' F' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' F' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' ' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please' ' instantiate this tokenizer with `model_max_length` set to your preferred value.' , snake_case_ , ) return max_model_length @property def SCREAMING_SNAKE_CASE__ ( self ) -> Any: return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = {self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None , snake_case_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case_ , token_ids_a=snake_case_ , already_has_special_tokens=snake_case_ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(snake_case_ )) + [1] return ([0] * len(snake_case_ )) + [1] + ([0] * len(snake_case_ )) + [1] def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return list( set(filter(lambda snake_case_ : bool(re.search(r'<extra_id_\d+>' , snake_case_ ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: return [self._convert_token_to_id(snake_case_ ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[int]: if len(snake_case_ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' ' eos tokens being added.' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> List[int]: UpperCamelCase__ = self._add_eos_if_not_present(snake_case_ ) if token_ids_a is None: return token_ids_a else: UpperCamelCase__ = self._add_eos_if_not_present(snake_case_ ) return token_ids_a + token_ids_a def __getstate__( self ) -> str: UpperCamelCase__ = self.__dict__.copy() UpperCamelCase__ = None return state def __setstate__( self , snake_case_ ) -> Any: UpperCamelCase__ = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): UpperCamelCase__ = {} UpperCamelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , **snake_case_ ) -> List[str]: # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: UpperCamelCase__ = SPIECE_UNDERLINE + text.replace(snake_case_ , ' ' ) return super().tokenize(snake_case_ , **snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , **snake_case_ ) -> List[Any]: if not self.legacy: UpperCamelCase__ = text.startswith(snake_case_ ) if is_first: UpperCamelCase__ = text[1:] UpperCamelCase__ = self.sp_model.encode(snake_case_ , out_type=snake_case_ ) if not self.legacy and not is_first and not text.startswith(' ' ) and tokens[0].startswith(snake_case_ ): UpperCamelCase__ = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: if token.startswith('<extra_id_' ): UpperCamelCase__ = re.match(r'<extra_id_(\d+)>' , snake_case_ ) UpperCamelCase__ = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Optional[int]: if index < self.sp_model.get_piece_size(): UpperCamelCase__ = self.sp_model.IdToPiece(snake_case_ ) else: UpperCamelCase__ = F'<extra_id_{self.vocab_size - 1 - index}>' return token def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: UpperCamelCase__ = [] UpperCamelCase__ = '' UpperCamelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(snake_case_ ) + token UpperCamelCase__ = True UpperCamelCase__ = [] else: current_sub_tokens.append(snake_case_ ) UpperCamelCase__ = False out_string += self.sp_model.decode(snake_case_ ) return out_string.strip() def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> Tuple[str]: if not os.path.isdir(snake_case_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase__ = os.path.join( snake_case_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case_ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case_ , 'wb' ) as fi: UpperCamelCase__ = self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,)
20
0
"""simple docstring""" import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging A__ : List[Any]= logging.get_logger(__name__) A__ : Any= { '''vocab_file''': '''vocab.json''', '''tokenizer_config_file''': '''tokenizer_config.json''', '''merges_file''': '''merges.txt''', } A__ : Optional[Any]= { '''vocab_file''': { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json''' ), }, '''tokenizer_config_file''': { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json''' ), }, '''merges_file''': { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt''' ), }, } A__ : Optional[Any]= '''</w>''' A__ : Union[str, Any]= '''@@ ''' def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" UpperCamelCase__ = set() UpperCamelCase__ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCamelCase__ = char return pairs # Speech2Text2 has no max input length A__ : int= {'''facebook/s2t-wav2vec2-large-en-de''': 10_24} class __lowerCamelCase ( __a ): a : str =VOCAB_FILES_NAMES a : List[str] =PRETRAINED_VOCAB_FILES_MAP a : Optional[int] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : str =['''input_ids''', '''attention_mask'''] def __init__( self , snake_case_ , snake_case_="<s>" , snake_case_="<pad>" , snake_case_="</s>" , snake_case_="<unk>" , snake_case_=False , snake_case_=None , **snake_case_ , ) -> Optional[Any]: super().__init__( unk_token=snake_case__ , bos_token=snake_case__ , eos_token=snake_case__ , pad_token=snake_case__ , do_lower_case=snake_case__ , **snake_case__ , ) UpperCamelCase__ = do_lower_case with open(snake_case__ , encoding='utf-8' ) as vocab_handle: UpperCamelCase__ = json.load(snake_case__ ) UpperCamelCase__ = {v: k for k, v in self.encoder.items()} if merges_file is None: logger.info(F'No merges files provided. {self.__class__.__name__} can only be used for decoding.' ) UpperCamelCase__ = None UpperCamelCase__ = None else: with open(snake_case__ , encoding='utf-8' ) as merges_handle: UpperCamelCase__ = merges_handle.read().split('\n' )[:-1] UpperCamelCase__ = [tuple(merge.split()[:2] ) for merge in merges] UpperCamelCase__ = dict(zip(snake_case__ , range(len(snake_case__ ) ) ) ) UpperCamelCase__ = {} @property def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: return len(self.decoder ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Any: UpperCamelCase__ = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,) if token in self.cache: return self.cache[token] UpperCamelCase__ = get_pairs(snake_case__ ) if not pairs: return token while True: UpperCamelCase__ = min(snake_case__ , key=lambda snake_case_ : self.bpe_ranks.get(snake_case__ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break UpperCamelCase__ , UpperCamelCase__ = bigram UpperCamelCase__ = [] UpperCamelCase__ = 0 while i < len(snake_case__ ): try: UpperCamelCase__ = word.index(snake_case__ , snake_case__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) UpperCamelCase__ = j if word[i] == first and i < len(snake_case__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 UpperCamelCase__ = tuple(snake_case__ ) UpperCamelCase__ = new_word if len(snake_case__ ) == 1: break else: UpperCamelCase__ = get_pairs(snake_case__ ) UpperCamelCase__ = ' '.join(snake_case__ ) if word == "\n " + BPE_TOKEN_MERGES: UpperCamelCase__ = '\n' + BPE_TOKEN_MERGES if word.endswith(snake_case__ ): UpperCamelCase__ = word.replace(snake_case__ , '' ) UpperCamelCase__ = word.replace(' ' , snake_case__ ) UpperCamelCase__ = word return word def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Dict: if self.bpe_ranks is None: raise ValueError( 'This tokenizer was instantiated without a `merges.txt` file, so' ' that it can only be used for decoding, not for encoding.' 'Make sure to provide `merges.txt` file at instantiation to enable ' 'encoding.' ) if self.do_lower_case: UpperCamelCase__ = text.lower() UpperCamelCase__ = text.split() UpperCamelCase__ = [] for token in text: if token: split_tokens.extend(list(self.bpe(snake_case__ ).split(' ' ) ) ) return split_tokens def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: return self.encoder.get(snake_case__ , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Any: UpperCamelCase__ = self.decoder.get(snake_case__ , self.unk_token ) return result def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: UpperCamelCase__ = ' '.join(snake_case__ ) # make sure @@ tokens are concatenated UpperCamelCase__ = ''.join(string.split(snake_case__ ) ) return string def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = None ) -> Tuple: if not os.path.isdir(snake_case__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return UpperCamelCase__ = os.path.join( snake_case__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase__ = os.path.join( snake_case__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(snake_case__ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=snake_case__ , ensure_ascii=snake_case__ ) + '\n' ) UpperCamelCase__ = 0 if self.bpe_ranks is None: return (vocab_file,) with open(snake_case__ , 'w' , encoding='utf-8' ) as writer: for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda snake_case_ : kv[1] ): if index != token_index: logger.warning( F'Saving vocabulary to {merges_file}: BPE merge indices are not consecutive.' ' Please check that the tokenizer is not corrupted!' ) UpperCamelCase__ = token_index writer.write(' '.join(snake_case__ ) + '\n' ) index += 1 return (vocab_file, merges_file)
705
"""simple docstring""" from __future__ import annotations from typing import Generic, TypeVar A__ : Any= TypeVar("""T""") class __lowerCamelCase ( Generic[T] ): def __init__( self , snake_case_ ) -> None: UpperCamelCase__ = data UpperCamelCase__ = self UpperCamelCase__ = 0 class __lowerCamelCase ( Generic[T] ): def __init__( self ) -> None: # map from node name to the node object UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: # create a new set with x as its member UpperCamelCase__ = DisjointSetTreeNode(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> DisjointSetTreeNode[T]: # find the set x belongs to (with path-compression) UpperCamelCase__ = self.map[data] if elem_ref != elem_ref.parent: UpperCamelCase__ = self.find_set(elem_ref.parent.data ) return elem_ref.parent def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: # helper function for union operation if nodea.rank > nodea.rank: UpperCamelCase__ = nodea else: UpperCamelCase__ = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> None: # merge 2 disjoint sets self.link(self.find_set(snake_case_ ) , self.find_set(snake_case_ ) ) class __lowerCamelCase ( Generic[T] ): def __init__( self ) -> None: # connections: map from the node to the neighbouring nodes (with weights) UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> None: # add a node ONLY if its not present in the graph if node not in self.connections: UpperCamelCase__ = {} def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> None: # add an edge with the given weight self.add_node(snake_case_ ) self.add_node(snake_case_ ) UpperCamelCase__ = weight UpperCamelCase__ = weight def SCREAMING_SNAKE_CASE__ ( self ) -> GraphUndirectedWeighted[T]: UpperCamelCase__ = [] UpperCamelCase__ = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda snake_case_ : x[2] ) # creating the disjoint set UpperCamelCase__ = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(snake_case_ ) # MST generation UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = edges[index] index += 1 UpperCamelCase__ = disjoint_set.find_set(snake_case_ ) UpperCamelCase__ = disjoint_set.find_set(snake_case_ ) if parent_u != parent_v: num_edges += 1 graph.add_edge(snake_case_ , snake_case_ , snake_case_ ) disjoint_set.union(snake_case_ , snake_case_ ) return graph
20
0
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" UpperCamelCase__ = [] create_all_state(1 , lowerCAmelCase_ , lowerCAmelCase_ , [] , lowerCAmelCase_ ) return result def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" if level == 0: total_list.append(current_list[:] ) return for i in range(lowerCAmelCase_ , total_number - level + 2 ): current_list.append(lowerCAmelCase_ ) create_all_state(i + 1 , lowerCAmelCase_ , level - 1 , lowerCAmelCase_ , lowerCAmelCase_ ) current_list.pop() def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" for i in total_list: print(*lowerCAmelCase_ ) if __name__ == "__main__": A__ : str= 4 A__ : int= 2 A__ : int= generate_all_combinations(n, k) print_all_state(total_list)
706
"""simple docstring""" A__ : Tuple= """Alexander Joslin""" import operator as op from .stack import Stack def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" UpperCamelCase__ = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} UpperCamelCase__ = Stack() UpperCamelCase__ = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(SCREAMING_SNAKE_CASE ) ) elif i in operators: # RULE 2 operator_stack.push(SCREAMING_SNAKE_CASE ) elif i == ")": # RULE 4 UpperCamelCase__ = operator_stack.peek() operator_stack.pop() UpperCamelCase__ = operand_stack.peek() operand_stack.pop() UpperCamelCase__ = operand_stack.peek() operand_stack.pop() UpperCamelCase__ = operators[opr](SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) operand_stack.push(SCREAMING_SNAKE_CASE ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": A__ : int= """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
20
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Dict= logging.get_logger(__name__) A__ : Any= { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/config.json""", """funnel-transformer/small-base""": """https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json""", """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/config.json""", """funnel-transformer/medium-base""": """https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json""", """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/config.json""", """funnel-transformer/large-base""": """https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json""", """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json""", """funnel-transformer/xlarge-base""": """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json""", } class __lowerCamelCase ( _a ): a : Any ="""funnel""" a : Any ={ """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", } def __init__( self , snake_case_=3_0522 , snake_case_=[4, 4, 4] , snake_case_=None , snake_case_=2 , snake_case_=768 , snake_case_=12 , snake_case_=64 , snake_case_=3072 , snake_case_="gelu_new" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=0.0 , snake_case_=0.1 , snake_case_=None , snake_case_=1E-9 , snake_case_="mean" , snake_case_="relative_shift" , snake_case_=True , snake_case_=True , snake_case_=True , **snake_case_ , ) -> Union[str, Any]: UpperCamelCase__ = vocab_size UpperCamelCase__ = block_sizes UpperCamelCase__ = [1] * len(snake_case_ ) if block_repeats is None else block_repeats assert len(snake_case_ ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." UpperCamelCase__ = num_decoder_layers UpperCamelCase__ = d_model UpperCamelCase__ = n_head UpperCamelCase__ = d_head UpperCamelCase__ = d_inner UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout UpperCamelCase__ = attention_dropout UpperCamelCase__ = activation_dropout UpperCamelCase__ = initializer_range UpperCamelCase__ = initializer_std UpperCamelCase__ = layer_norm_eps assert pooling_type in [ "mean", "max", ], F'Got {pooling_type} for `pooling_type` but only \'mean\' and \'max\' are supported.' UpperCamelCase__ = pooling_type assert attention_type in [ "relative_shift", "factorized", ], F'Got {attention_type} for `attention_type` but only \'relative_shift\' and \'factorized\' are supported.' UpperCamelCase__ = attention_type UpperCamelCase__ = separate_cls UpperCamelCase__ = truncate_seq UpperCamelCase__ = pool_q_only super().__init__(**snake_case_ ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return sum(self.block_sizes ) @num_hidden_layers.setter def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> int: raise NotImplementedError( 'This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.' ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: return len(self.block_sizes ) @num_blocks.setter def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> Dict: raise NotImplementedError('This model does not support the setting of `num_blocks`. Please set `block_sizes`.' )
707
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py A__ : Any= """src/diffusers""" # Matches is_xxx_available() A__ : Tuple= re.compile(r"""is\_([a-z_]*)_available\(\)""") # Matches from xxx import bla A__ : Any= re.compile(r"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""") A__ : Optional[Any]= """ {0} = None """ A__ : List[Any]= """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) """ A__ : Dict= """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ = _re_backend.findall(SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) == 0: return None return "_and_".join(SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( ) -> str: """simple docstring""" with open(os.path.join(SCREAMING_SNAKE_CASE , '__init__.py' ) , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.readlines() # Get to the point we do the actual imports for type checking UpperCamelCase__ = 0 UpperCamelCase__ = {} # Go through the end of the file while line_index < len(SCREAMING_SNAKE_CASE ): # If the line contains is_backend_available, we grab all objects associated with the `else` block UpperCamelCase__ = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('else:' ): line_index += 1 line_index += 1 UpperCamelCase__ = [] # Until we unindent, add backend objects to the list while line_index < len(SCREAMING_SNAKE_CASE ) and len(lines[line_index] ) > 1: UpperCamelCase__ = lines[line_index] UpperCamelCase__ = _re_single_line_import.search(SCREAMING_SNAKE_CASE ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(SCREAMING_SNAKE_CASE ) > 0: UpperCamelCase__ = objects else: line_index += 1 return backend_specific_objects def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if name.isupper(): return DUMMY_CONSTANT.format(SCREAMING_SNAKE_CASE ) elif name.islower(): return DUMMY_FUNCTION.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: return DUMMY_CLASS.format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" if backend_specific_objects is None: UpperCamelCase__ = read_init() # For special correspondence backend to module name as used in the function requires_modulename UpperCamelCase__ = {} for backend, objects in backend_specific_objects.items(): UpperCamelCase__ = '[' + ', '.join(F'"{b}"' for b in backend.split('_and_' ) ) + ']' UpperCamelCase__ = '# This file is autogenerated by the command `make fix-copies`, do not edit.\n' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for o in objects] ) UpperCamelCase__ = dummy_file return dummy_files def lowerCAmelCase_( SCREAMING_SNAKE_CASE=False ) -> int: """simple docstring""" UpperCamelCase__ = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py UpperCamelCase__ = {'torch': 'pt'} # Locate actual dummy modules and read their content. UpperCamelCase__ = os.path.join(SCREAMING_SNAKE_CASE , 'utils' ) UpperCamelCase__ = { backend: os.path.join(SCREAMING_SNAKE_CASE , F'dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py' ) for backend in dummy_files.keys() } UpperCamelCase__ = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(SCREAMING_SNAKE_CASE ): with open(SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase__ = f.read() else: UpperCamelCase__ = '' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( F'Updating diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py as the main ' '__init__ has new objects.' ) with open(dummy_file_paths[backend] , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( 'The main __init__ has objects that are not present in ' F'diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )}_objects.py. Run `make fix-copies` ' 'to fix this.' ) if __name__ == "__main__": A__ : Any= argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") A__ : Optional[int]= parser.parse_args() check_dummies(args.fix_and_overwrite)
20
0
"""simple docstring""" import inspect import unittest from transformers import DecisionTransformerConfig, 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, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class __lowerCamelCase : def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=6 , snake_case_=17 , snake_case_=23 , snake_case_=11 , snake_case_=True , ) -> List[str]: UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = act_dim UpperCamelCase__ = state_dim UpperCamelCase__ = hidden_size UpperCamelCase__ = max_length UpperCamelCase__ = is_training def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) UpperCamelCase__ = floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) UpperCamelCase__ = floats_tensor((self.batch_size, self.seq_length, 1) ) UpperCamelCase__ = floats_tensor((self.batch_size, self.seq_length, 1) ) UpperCamelCase__ = ids_tensor((self.batch_size, self.seq_length) , vocab_size=1000 ) UpperCamelCase__ = random_attention_mask((self.batch_size, self.seq_length) ) UpperCamelCase__ = self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , ) -> str: UpperCamelCase__ = DecisionTransformerModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCamelCase__ = model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = { 'states': states, 'actions': actions, 'rewards': rewards, 'returns_to_go': returns_to_go, 'timesteps': timesteps, 'attention_mask': attention_mask, } return config, inputs_dict @require_torch class __lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): a : Tuple =(DecisionTransformerModel,) if is_torch_available() else () a : Union[str, Any] =() a : List[str] ={"feature-extraction": DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids a : Optional[int] =False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features a : List[Any] =False a : Optional[Any] =False a : Tuple =False a : str =False a : Dict =False a : List[str] =False a : Any =False a : Any =False a : Dict =False def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ = DecisionTransformerModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = DecisionTransformerModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(_SCREAMING_SNAKE_CASE ) UpperCamelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = [ 'states', 'actions', 'rewards', 'returns_to_go', 'timesteps', 'attention_mask', ] self.assertListEqual(arg_names[: len(_SCREAMING_SNAKE_CASE )] , _SCREAMING_SNAKE_CASE ) @require_torch class __lowerCamelCase ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = 2 # number of steps of autoregressive prediction we will perform UpperCamelCase__ = 10 # defined by the RL environment, may be normalized UpperCamelCase__ = DecisionTransformerModel.from_pretrained('edbeeching/decision-transformer-gym-hopper-expert' ) UpperCamelCase__ = model.to(_SCREAMING_SNAKE_CASE ) UpperCamelCase__ = model.config torch.manual_seed(0 ) UpperCamelCase__ = torch.randn(1 , 1 , config.state_dim ).to(device=_SCREAMING_SNAKE_CASE , dtype=torch.floataa ) # env.reset() UpperCamelCase__ = torch.tensor( [[0.242_793, -0.28_693_074, 0.8_742_613], [0.67_815_274, -0.08_101_085, -0.12_952_147]] , device=_SCREAMING_SNAKE_CASE ) UpperCamelCase__ = torch.tensor(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=torch.floataa ).reshape(1 , 1 , 1 ) UpperCamelCase__ = state UpperCamelCase__ = torch.zeros(1 , 0 , config.act_dim , device=_SCREAMING_SNAKE_CASE , dtype=torch.floataa ) UpperCamelCase__ = torch.zeros(1 , 0 , device=_SCREAMING_SNAKE_CASE , dtype=torch.floataa ) UpperCamelCase__ = torch.tensor(0 , device=_SCREAMING_SNAKE_CASE , dtype=torch.long ).reshape(1 , 1 ) for step in range(_SCREAMING_SNAKE_CASE ): UpperCamelCase__ = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=_SCREAMING_SNAKE_CASE )] , dim=1 ) UpperCamelCase__ = torch.cat([rewards, torch.zeros(1 , 1 , device=_SCREAMING_SNAKE_CASE )] , dim=1 ) UpperCamelCase__ = torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = model( states=_SCREAMING_SNAKE_CASE , actions=_SCREAMING_SNAKE_CASE , rewards=_SCREAMING_SNAKE_CASE , returns_to_go=_SCREAMING_SNAKE_CASE , timesteps=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1E-4 ) ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = ( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=_SCREAMING_SNAKE_CASE , dtype=torch.floataa ), 1.0, False, {}, ) UpperCamelCase__ = action_pred[0, -1] UpperCamelCase__ = torch.cat([states, state] , dim=1 ) UpperCamelCase__ = returns_to_go[0, -1] - reward UpperCamelCase__ = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) UpperCamelCase__ = torch.cat( [timesteps, torch.ones((1, 1) , device=_SCREAMING_SNAKE_CASE , dtype=torch.long ) * (step + 1)] , dim=1 )
708
"""simple docstring""" # Copyright 2022 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. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file A__ : Optional[Any]= """Run commands across TPU VMs for initial setup before running `accelerate launch`.""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE=None ) -> Dict: """simple docstring""" if subparsers is not None: UpperCamelCase__ = subparsers.add_parser('tpu-config' , description=_description ) else: UpperCamelCase__ = argparse.ArgumentParser('Accelerate tpu-config command' , description=_description ) # Core arguments UpperCamelCase__ = parser.add_argument_group( 'Config Arguments' , 'Arguments that can be configured through `accelerate config`.' ) config_args.add_argument( '--config_file' , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , help='Path to the config file to use for accelerate.' , ) config_args.add_argument( '--tpu_name' , default=SCREAMING_SNAKE_CASE , help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.' , ) config_args.add_argument( '--tpu_zone' , default=SCREAMING_SNAKE_CASE , help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.' , ) UpperCamelCase__ = parser.add_argument_group('TPU Arguments' , 'Arguments for options ran inside the TPU.' ) pod_args.add_argument( '--use_alpha' , action='store_true' , help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.' , ) pod_args.add_argument( '--command_file' , default=SCREAMING_SNAKE_CASE , help='The path to the file containing the commands to run on the pod on startup.' , ) pod_args.add_argument( '--command' , action='append' , nargs='+' , help='A command to run on the pod. Can be passed multiple times.' , ) pod_args.add_argument( '--install_accelerate' , action='store_true' , help='Whether to install accelerate on the pod. Defaults to False.' , ) pod_args.add_argument( '--accelerate_version' , default='latest' , help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.' , ) pod_args.add_argument( '--debug' , action='store_true' , help='If set, will print the command that would be run instead of running it.' ) if subparsers is not None: parser.set_defaults(func=SCREAMING_SNAKE_CASE ) return parser def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" UpperCamelCase__ = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(SCREAMING_SNAKE_CASE ): UpperCamelCase__ = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: UpperCamelCase__ = defaults.command_file if not args.command and defaults.commands is not None: UpperCamelCase__ = defaults.commands if not args.tpu_name: UpperCamelCase__ = defaults.tpu_name if not args.tpu_zone: UpperCamelCase__ = defaults.tpu_zone if args.accelerate_version == "dev": UpperCamelCase__ = 'git+https://github.com/huggingface/accelerate.git' elif args.accelerate_version == "latest": UpperCamelCase__ = 'accelerate -U' elif isinstance(parse(args.accelerate_version ) , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = F'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError('You must specify either a command file or a command to run on the pod.' ) if args.command_file: with open(args.command_file , 'r' ) as f: UpperCamelCase__ = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , SCREAMING_SNAKE_CASE ): UpperCamelCase__ = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate UpperCamelCase__ = ['cd /usr/share'] if args.install_accelerate: new_cmd += [F'pip install {args.accelerate_version}'] new_cmd += args.command UpperCamelCase__ = '; '.join(SCREAMING_SNAKE_CASE ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess UpperCamelCase__ = ['gcloud'] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'Running {" ".join(SCREAMING_SNAKE_CASE )}' ) return subprocess.run(SCREAMING_SNAKE_CASE ) print('Successfully setup pod.' ) def lowerCAmelCase_( ) -> int: """simple docstring""" UpperCamelCase__ = tpu_command_parser() UpperCamelCase__ = parser.parse_args() tpu_command_launcher(SCREAMING_SNAKE_CASE )
20
0
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable A__ : Tuple= {'configuration_gpt_neox': ['GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXConfig']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : str= ['GPTNeoXTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Union[str, Any]= [ 'GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTNeoXForCausalLM', 'GPTNeoXForQuestionAnswering', 'GPTNeoXForSequenceClassification', 'GPTNeoXForTokenClassification', 'GPTNeoXLayer', 'GPTNeoXModel', 'GPTNeoXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys A__ : Any= _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
709
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : List[str]= logging.get_logger(__name__) class __lowerCamelCase ( _a ): a : Optional[int] ="""timm_backbone""" def __init__( self , snake_case_=None , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=None , **snake_case_ , ) -> Dict: super().__init__(**snake_case_ ) UpperCamelCase__ = backbone UpperCamelCase__ = num_channels UpperCamelCase__ = features_only UpperCamelCase__ = use_pretrained_backbone UpperCamelCase__ = True UpperCamelCase__ = out_indices if out_indices is not None else (-1,)
20
0
"""simple docstring""" def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError('iterations must be defined as integers' ) if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or not number >= 1: raise ValueError( 'starting number must be\n and integer and be more than 0' ) if not iterations >= 1: raise ValueError('Iterations must be done more than 0 times to play FizzBuzz' ) UpperCamelCase__ = '' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(SCREAMING_SNAKE_CASE ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
710
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType A__ : Any= logging.get_logger(__name__) A__ : str= { """microsoft/layoutlmv3-base""": """https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json""", } class __lowerCamelCase ( _a ): a : List[str] ="""layoutlmv3""" def __init__( self , snake_case_=5_0265 , snake_case_=768 , snake_case_=12 , snake_case_=12 , snake_case_=3072 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=2 , snake_case_=0.02 , snake_case_=1E-5 , snake_case_=1 , snake_case_=0 , snake_case_=2 , snake_case_=1024 , snake_case_=128 , snake_case_=128 , snake_case_=True , snake_case_=32 , snake_case_=128 , snake_case_=64 , snake_case_=256 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=224 , snake_case_=3 , snake_case_=16 , snake_case_=None , **snake_case_ , ) -> Union[str, Any]: super().__init__( vocab_size=snake_case_ , hidden_size=snake_case_ , num_hidden_layers=snake_case_ , num_attention_heads=snake_case_ , intermediate_size=snake_case_ , hidden_act=snake_case_ , hidden_dropout_prob=snake_case_ , attention_probs_dropout_prob=snake_case_ , max_position_embeddings=snake_case_ , type_vocab_size=snake_case_ , initializer_range=snake_case_ , layer_norm_eps=snake_case_ , pad_token_id=snake_case_ , bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ , ) UpperCamelCase__ = max_ad_position_embeddings UpperCamelCase__ = coordinate_size UpperCamelCase__ = shape_size UpperCamelCase__ = has_relative_attention_bias UpperCamelCase__ = rel_pos_bins UpperCamelCase__ = max_rel_pos UpperCamelCase__ = has_spatial_attention_bias UpperCamelCase__ = rel_ad_pos_bins UpperCamelCase__ = max_rel_ad_pos UpperCamelCase__ = text_embed UpperCamelCase__ = visual_embed UpperCamelCase__ = input_size UpperCamelCase__ = num_channels UpperCamelCase__ = patch_size UpperCamelCase__ = classifier_dropout class __lowerCamelCase ( _a ): a : Tuple =version.parse("""1.12""" ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) else: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels'}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: return 12 def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ = -1 , snake_case_ = -1 , snake_case_ = False , snake_case_ = None , snake_case_ = 3 , snake_case_ = 40 , snake_case_ = 40 , ) -> Mapping[str, Any]: setattr(processor.image_processor , 'apply_ocr' , snake_case_ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase__ = processor.tokenizer.num_special_tokens_to_add(snake_case_ ) UpperCamelCase__ = compute_effective_axis_dimension( snake_case_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case_ ) # Generate dummy inputs according to compute batch and sequence UpperCamelCase__ = [[' '.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes UpperCamelCase__ = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) UpperCamelCase__ = self._generate_dummy_images(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) UpperCamelCase__ = dict( processor( snake_case_ , text=snake_case_ , boxes=snake_case_ , return_tensors=snake_case_ , ) ) return inputs
20
0
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> list[int]: # This function is recursive """simple docstring""" UpperCamelCase__ = len(__snake_case ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else UpperCamelCase__ = array[0] UpperCamelCase__ = False UpperCamelCase__ = 1 UpperCamelCase__ = [] while not is_found and i < array_length: if array[i] < pivot: UpperCamelCase__ = True UpperCamelCase__ = [element for element in array[i:] if element >= array[i]] UpperCamelCase__ = longest_subsequence(__snake_case ) if len(__snake_case ) > len(__snake_case ): UpperCamelCase__ = temp_array else: i += 1 UpperCamelCase__ = [element for element in array[1:] if element >= pivot] UpperCamelCase__ = [pivot, *longest_subsequence(__snake_case )] if len(__snake_case ) > len(__snake_case ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
711
"""simple docstring""" from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class __lowerCamelCase : def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=2 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> Tuple: UpperCamelCase__ = parent UpperCamelCase__ = 13 UpperCamelCase__ = 7 UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = 99 UpperCamelCase__ = 384 UpperCamelCase__ = 2 UpperCamelCase__ = 4 UpperCamelCase__ = 37 UpperCamelCase__ = 'gelu' UpperCamelCase__ = 0.1 UpperCamelCase__ = 0.1 UpperCamelCase__ = 512 UpperCamelCase__ = 16 UpperCamelCase__ = 2 UpperCamelCase__ = 0.02 UpperCamelCase__ = 3 UpperCamelCase__ = 4 UpperCamelCase__ = 128 UpperCamelCase__ = 2 UpperCamelCase__ = 9 UpperCamelCase__ = 1 UpperCamelCase__ = None def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = ConvBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=snake_case_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertModel(config=snake_case_ ) UpperCamelCase__ = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} UpperCamelCase__ = [input_ids, input_mask] UpperCamelCase__ = model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: UpperCamelCase__ = TFConvBertForMaskedLM(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForSequenceClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Tuple: UpperCamelCase__ = self.num_choices UpperCamelCase__ = TFConvBertForMultipleChoice(config=snake_case_ ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase__ = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFConvBertForTokenClassification(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = TFConvBertForQuestionAnswering(config=snake_case_ ) UpperCamelCase__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class __lowerCamelCase ( _a , _a , unittest.TestCase ): a : Any =( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) a : str =( { """feature-extraction""": TFConvBertModel, """fill-mask""": TFConvBertForMaskedLM, """question-answering""": TFConvBertForQuestionAnswering, """text-classification""": TFConvBertForSequenceClassification, """token-classification""": TFConvBertForTokenClassification, """zero-shot""": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) a : Any =False a : Dict =False a : str =False def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = TFConvBertModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = True if hasattr(snake_case_ , 'use_cache' ): UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) for model_class in self.all_model_classes: UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ ) UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = len(model(snake_case_ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(snake_case_ , saved_model=snake_case_ ) UpperCamelCase__ = os.path.join(snake_case_ , 'saved_model' , '1' ) UpperCamelCase__ = tf.keras.models.load_model(snake_case_ ) UpperCamelCase__ = model(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = outputs['encoder_hidden_states'] UpperCamelCase__ = outputs['encoder_attentions'] else: UpperCamelCase__ = outputs['hidden_states'] UpperCamelCase__ = outputs['attentions'] self.assertEqual(len(snake_case_ ) , snake_case_ ) UpperCamelCase__ = getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(snake_case_ ) , snake_case_ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True UpperCamelCase__ = getattr(self.model_tester , 'decoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'encoder_seq_length' , self.model_tester.seq_length ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) UpperCamelCase__ = getattr(self.model_tester , 'key_length' , snake_case_ ) def check_decoder_attentions_output(snake_case_ ): UpperCamelCase__ = len(snake_case_ ) self.assertEqual(out_len % 2 , 0 ) UpperCamelCase__ = outputs.decoder_attentions self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(snake_case_ ): UpperCamelCase__ = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(snake_case_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: UpperCamelCase__ = True UpperCamelCase__ = False UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) UpperCamelCase__ = len(snake_case_ ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) if self.is_encoder_decoder: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_decoder_attentions_output(snake_case_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) # Check attention is always last and order is fine UpperCamelCase__ = True UpperCamelCase__ = True UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = model(self._prepare_for_class(snake_case_ , snake_case_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(snake_case_ ) ) self.assertEqual(model.config.output_hidden_states , snake_case_ ) check_encoder_attentions_output(snake_case_ ) @require_tf class __lowerCamelCase ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) UpperCamelCase__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase__ = model(snake_case_ )[0] UpperCamelCase__ = [1, 6, 768] self.assertEqual(output.shape , snake_case_ ) UpperCamelCase__ = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , snake_case_ , atol=1E-4 )
20
0
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef A__ : Union[str, Any]= ( """This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate """ """library. You can have a look at this example script for pointers: """ """https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py""" ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" warnings.warn(lowerCamelCase_ , lowerCamelCase_ ) requires_backends(lowerCamelCase_ , 'sklearn' ) return (preds == labels).mean() def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" warnings.warn(lowerCamelCase_ , lowerCamelCase_ ) requires_backends(lowerCamelCase_ , 'sklearn' ) UpperCamelCase__ = simple_accuracy(lowerCamelCase_ , lowerCamelCase_ ) UpperCamelCase__ = fa_score(y_true=lowerCamelCase_ , y_pred=lowerCamelCase_ ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" warnings.warn(lowerCamelCase_ , lowerCamelCase_ ) requires_backends(lowerCamelCase_ , 'sklearn' ) UpperCamelCase__ = pearsonr(lowerCamelCase_ , lowerCamelCase_ )[0] UpperCamelCase__ = spearmanr(lowerCamelCase_ , lowerCamelCase_ )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" warnings.warn(lowerCamelCase_ , lowerCamelCase_ ) requires_backends(lowerCamelCase_ , 'sklearn' ) assert len(lowerCamelCase_ ) == len(lowerCamelCase_ ), F'Predictions and labels have mismatched lengths {len(lowerCamelCase_ )} and {len(lowerCamelCase_ )}' if task_name == "cola": return {"mcc": matthews_corrcoef(lowerCamelCase_ , lowerCamelCase_ )} elif task_name == "sst-2": return {"acc": simple_accuracy(lowerCamelCase_ , lowerCamelCase_ )} elif task_name == "mrpc": return acc_and_fa(lowerCamelCase_ , lowerCamelCase_ ) elif task_name == "sts-b": return pearson_and_spearman(lowerCamelCase_ , lowerCamelCase_ ) elif task_name == "qqp": return acc_and_fa(lowerCamelCase_ , lowerCamelCase_ ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(lowerCamelCase_ , lowerCamelCase_ )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(lowerCamelCase_ , lowerCamelCase_ )} elif task_name == "qnli": return {"acc": simple_accuracy(lowerCamelCase_ , lowerCamelCase_ )} elif task_name == "rte": return {"acc": simple_accuracy(lowerCamelCase_ , lowerCamelCase_ )} elif task_name == "wnli": return {"acc": simple_accuracy(lowerCamelCase_ , lowerCamelCase_ )} elif task_name == "hans": return {"acc": simple_accuracy(lowerCamelCase_ , lowerCamelCase_ )} else: raise KeyError(lowerCamelCase_ ) def lowerCAmelCase_( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" warnings.warn(lowerCamelCase_ , lowerCamelCase_ ) requires_backends(lowerCamelCase_ , 'sklearn' ) if len(lowerCamelCase_ ) != len(lowerCamelCase_ ): raise ValueError(F'Predictions and labels have mismatched lengths {len(lowerCamelCase_ )} and {len(lowerCamelCase_ )}' ) if task_name == "xnli": return {"acc": simple_accuracy(lowerCamelCase_ , lowerCamelCase_ )} else: raise KeyError(lowerCamelCase_ )
712
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase_( SCREAMING_SNAKE_CASE = 1_00_00_00 , SCREAMING_SNAKE_CASE = 10 ) -> int: """simple docstring""" UpperCamelCase__ = defaultdict(SCREAMING_SNAKE_CASE ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: UpperCamelCase__ = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: UpperCamelCase__ = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(SCREAMING_SNAKE_CASE , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F"""{solution() = }""")
20
0
from __future__ import annotations import numpy as np def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" return np.maximum(0 , A__ ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
713
"""simple docstring""" import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __lowerCamelCase ( unittest.TestCase ): def __init__( self , snake_case_ , snake_case_=100 , snake_case_=13 , snake_case_=30 , snake_case_=2 , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=10 , snake_case_=0.02 , snake_case_=3 , ) -> Optional[int]: UpperCamelCase__ = parent UpperCamelCase__ = vocab_size UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = patch_size UpperCamelCase__ = num_channels UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCamelCase__ = (image_size // patch_size) ** 2 UpperCamelCase__ = num_patches + 1 def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=snake_case_ , initializer_range=self.initializer_range , ) return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = FlaxBeitModel(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = FlaxBeitForMaskedImageModeling(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = self.type_sequence_label_size UpperCamelCase__ = FlaxBeitForImageClassification(config=snake_case_ ) UpperCamelCase__ = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase__ = 1 UpperCamelCase__ = FlaxBeitForImageClassification(snake_case_ ) UpperCamelCase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase__ = model(snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class __lowerCamelCase ( _a , unittest.TestCase ): a : int =( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE__ ( self ) -> None: UpperCamelCase__ = FlaxBeitModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ['pixel_values'] self.assertListEqual(arg_names[:1] , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ ) UpperCamelCase__ = model_class(snake_case_ ) @jax.jit def model_jitted(snake_case_ , **snake_case_ ): return model(pixel_values=snake_case_ , **snake_case_ ) with self.subTest('JIT Enabled' ): UpperCamelCase__ = model_jitted(**snake_case_ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): UpperCamelCase__ = model_jitted(**snake_case_ ).to_tuple() self.assertEqual(len(snake_case_ ) , len(snake_case_ ) ) for jitted_output, output in zip(snake_case_ , snake_case_ ): self.assertEqual(jitted_output.shape , output.shape ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: for model_class_name in self.all_model_classes: UpperCamelCase__ = model_class_name.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase__ = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(snake_case_ ) def lowerCAmelCase_( ) -> Optional[int]: """simple docstring""" UpperCamelCase__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @require_flax class __lowerCamelCase ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = FlaxBeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ).pixel_values # prepare bool_masked_pos UpperCamelCase__ = np.ones((1, 196) , dtype=snake_case_ ) # forward pass UpperCamelCase__ = model(pixel_values=snake_case_ , bool_masked_pos=snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 196, 8192) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , snake_case_ , atol=1E-2 ) ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ) # forward pass UpperCamelCase__ = model(**snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 1000) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array([-1.2_385, -1.0_987, -1.0_108] ) self.assertTrue(np.allclose(logits[0, :3] , snake_case_ , atol=1E-4 ) ) UpperCamelCase__ = 281 self.assertEqual(logits.argmax(-1 ).item() , snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = FlaxBeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=snake_case_ , return_tensors='np' ) # forward pass UpperCamelCase__ = model(**snake_case_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = (1, 2_1841) self.assertEqual(logits.shape , snake_case_ ) UpperCamelCase__ = np.array([1.6_881, -0.2_787, 0.5_901] ) self.assertTrue(np.allclose(logits[0, :3] , snake_case_ , atol=1E-4 ) ) UpperCamelCase__ = 2396 self.assertEqual(logits.argmax(-1 ).item() , snake_case_ )
20
0
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __lowerCamelCase : def __init__( self , snake_case_ , snake_case_=13 , snake_case_=32 , snake_case_=3 , snake_case_=4 , snake_case_=[10, 20, 30, 40] , snake_case_=[2, 2, 3, 2] , snake_case_=True , snake_case_=True , snake_case_=37 , snake_case_="gelu" , snake_case_=10 , snake_case_=0.02 , snake_case_=["stage2", "stage3", "stage4"] , snake_case_=[2, 3, 4] , snake_case_=None , ) -> Optional[Any]: UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = num_channels UpperCamelCase__ = num_stages UpperCamelCase__ = hidden_sizes UpperCamelCase__ = depths UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = num_labels UpperCamelCase__ = initializer_range UpperCamelCase__ = out_features UpperCamelCase__ = out_indices UpperCamelCase__ = scope def SCREAMING_SNAKE_CASE__ ( self ) -> int: UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase__ = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self ) -> Any: return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=snake_case_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> str: UpperCamelCase__ = ConvNextVaModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: UpperCamelCase__ = ConvNextVaForImageClassification(snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ ) -> Union[str, Any]: UpperCamelCase__ = ConvNextVaBackbone(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None UpperCamelCase__ = None UpperCamelCase__ = ConvNextVaBackbone(config=snake_case_ ) model.to(snake_case_ ) model.eval() UpperCamelCase__ = model(snake_case_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: UpperCamelCase__ = self.prepare_config_and_inputs() UpperCamelCase__ = config_and_inputs UpperCamelCase__ = {"pixel_values": pixel_values} return config, inputs_dict def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.prepare_config_and_inputs() UpperCamelCase__ = config_and_inputs UpperCamelCase__ = {"pixel_values": pixel_values, "labels": labels} return config, inputs_dict @require_torch class __lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): a : Union[str, Any] =( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) a : Tuple =( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) a : List[str] =False a : Optional[Any] =False a : List[Any] =False a : str =False a : Optional[int] =False def SCREAMING_SNAKE_CASE__ ( self ) -> str: UpperCamelCase__ = ConvNextVaModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: return @unittest.skip(reason='ConvNextV2 does not use inputs_embeds' ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: pass @unittest.skip(reason='ConvNextV2 does not support input and output embeddings' ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: pass @unittest.skip(reason='ConvNextV2 does not use feedforward chunking' ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: pass def SCREAMING_SNAKE_CASE__ ( self ) -> int: if not self.model_tester.is_training: return for model_class in self.all_model_classes: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_with_labels() UpperCamelCase__ = True if model_class.__name__ in [ *get_values(snake_case_ ), *get_values(snake_case_ ), ]: continue UpperCamelCase__ = model_class(snake_case_ ) model.to(snake_case_ ) model.train() UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) UpperCamelCase__ = model(**snake_case_ ).loss loss.backward() def SCREAMING_SNAKE_CASE__ ( self ) -> int: if not self.model_tester.is_training: return for model_class in self.all_model_classes: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_with_labels() UpperCamelCase__ = False UpperCamelCase__ = True if ( model_class.__name__ in [*get_values(snake_case_ ), *get_values(snake_case_ )] or not model_class.supports_gradient_checkpointing ): continue UpperCamelCase__ = model_class(snake_case_ ) model.to(snake_case_ ) model.gradient_checkpointing_enable() model.train() UpperCamelCase__ = self._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) UpperCamelCase__ = model(**snake_case_ ).loss loss.backward() def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(snake_case_ ) UpperCamelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: def check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ ): UpperCamelCase__ = model_class(snake_case_ ) model.to(snake_case_ ) model.eval() with torch.no_grad(): UpperCamelCase__ = model(**self._prepare_for_class(snake_case_ , snake_case_ ) ) UpperCamelCase__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase__ = self.model_tester.num_stages self.assertEqual(len(snake_case_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = True check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase__ = True check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> int: for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = ConvNextVaModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) def lowerCAmelCase_( ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: UpperCamelCase__ = ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224' ).to(snake_case_ ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = preprocessor(images=snake_case_ , return_tensors='pt' ).to(snake_case_ ) # forward pass with torch.no_grad(): UpperCamelCase__ = model(**snake_case_ ) # verify the logits UpperCamelCase__ = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , snake_case_ ) UpperCamelCase__ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(snake_case_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case_ , atol=1E-4 ) )
714
"""simple docstring""" import sys from collections import defaultdict class __lowerCamelCase : def __init__( self ) -> Tuple: UpperCamelCase__ = [] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ ) -> List[str]: return self.node_position[vertex] def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Optional[int]: UpperCamelCase__ = pos def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: UpperCamelCase__ = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: UpperCamelCase__ = 2 * start + 1 else: UpperCamelCase__ = 2 * start + 2 if heap[smallest_child] < heap[start]: UpperCamelCase__ , UpperCamelCase__ = heap[smallest_child], positions[smallest_child] UpperCamelCase__ , UpperCamelCase__ = ( heap[start], positions[start], ) UpperCamelCase__ , UpperCamelCase__ = temp, tempa UpperCamelCase__ = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , snake_case_ ) self.top_to_bottom(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Any: UpperCamelCase__ = position[index] while index != 0: UpperCamelCase__ = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: UpperCamelCase__ = heap[parent] UpperCamelCase__ = position[parent] self.set_position(position[parent] , snake_case_ ) else: UpperCamelCase__ = val UpperCamelCase__ = temp self.set_position(snake_case_ , snake_case_ ) break UpperCamelCase__ = parent else: UpperCamelCase__ = val UpperCamelCase__ = temp self.set_position(snake_case_ , 0 ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> Any: UpperCamelCase__ = len(snake_case_ ) // 2 - 1 for i in range(snake_case_ , -1 , -1 ): self.top_to_bottom(snake_case_ , snake_case_ , len(snake_case_ ) , snake_case_ ) def SCREAMING_SNAKE_CASE__ ( self , snake_case_ , snake_case_ ) -> List[Any]: UpperCamelCase__ = positions[0] UpperCamelCase__ = sys.maxsize self.top_to_bottom(snake_case_ , 0 , len(snake_case_ ) , snake_case_ ) return temp def lowerCAmelCase_( SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" UpperCamelCase__ = Heap() UpperCamelCase__ = [0] * len(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = [-1] * len(SCREAMING_SNAKE_CASE ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph UpperCamelCase__ = [] # Heap of Distance of vertices from their neighboring vertex UpperCamelCase__ = [] for vertex in range(len(SCREAMING_SNAKE_CASE ) ): distance_tv.append(sys.maxsize ) positions.append(SCREAMING_SNAKE_CASE ) heap.node_position.append(SCREAMING_SNAKE_CASE ) UpperCamelCase__ = [] UpperCamelCase__ = 1 UpperCamelCase__ = sys.maxsize for neighbor, distance in adjacency_list[0]: UpperCamelCase__ = 0 UpperCamelCase__ = distance heap.heapify(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for _ in range(1 , len(SCREAMING_SNAKE_CASE ) ): UpperCamelCase__ = heap.delete_minimum(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) UpperCamelCase__ = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(SCREAMING_SNAKE_CASE )] ): UpperCamelCase__ = distance heap.bottom_to_top( SCREAMING_SNAKE_CASE , heap.get_position(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A__ : Dict= int(input("""Enter number of edges: """).strip()) A__ : Dict= defaultdict(list) for _ in range(edges_number): A__ : Dict= [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
20
0