code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { "kakaobrain/align-base": "https://huggingface.co/kakaobrain/align-base/resolve/main/config.json", } class SCREAMING_SNAKE_CASE ( a ): """simple docstring""" a_ : str ="align_text_model" def __init__( self : List[str] , _snake_case : str=3_0522 , _snake_case : List[Any]=768 , _snake_case : Tuple=12 , _snake_case : Dict=12 , _snake_case : str=3072 , _snake_case : Optional[Any]="gelu" , _snake_case : Optional[Any]=0.1 , _snake_case : str=0.1 , _snake_case : int=512 , _snake_case : List[str]=2 , _snake_case : List[Any]=0.02 , _snake_case : Dict=1E-12 , _snake_case : Any=0 , _snake_case : Any="absolute" , _snake_case : Dict=True , **_snake_case : Any , ) -> List[Any]: '''simple docstring''' super().__init__(**_snake_case ) a__ = vocab_size a__ = hidden_size a__ = num_hidden_layers a__ = num_attention_heads a__ = hidden_act a__ = intermediate_size a__ = hidden_dropout_prob a__ = attention_probs_dropout_prob a__ = max_position_embeddings a__ = type_vocab_size a__ = initializer_range a__ = layer_norm_eps a__ = position_embedding_type a__ = use_cache a__ = pad_token_id @classmethod def _lowerCAmelCase ( cls : Any , _snake_case : Union[str, os.PathLike] , **_snake_case : Union[str, Any] ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_snake_case ) a__ , a__ = cls.get_config_dict(_snake_case , **_snake_case ) # get the text config dict if we are loading from AlignConfig if config_dict.get('model_type' ) == "align": a__ = 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(_snake_case , **_snake_case ) class SCREAMING_SNAKE_CASE ( a ): """simple docstring""" a_ : Dict ="align_vision_model" def __init__( self : Tuple , _snake_case : int = 3 , _snake_case : int = 600 , _snake_case : float = 2.0 , _snake_case : float = 3.1 , _snake_case : int = 8 , _snake_case : List[int] = [3, 3, 5, 3, 5, 5, 3] , _snake_case : List[int] = [32, 16, 24, 40, 80, 112, 192] , _snake_case : List[int] = [16, 24, 40, 80, 112, 192, 320] , _snake_case : List[int] = [] , _snake_case : List[int] = [1, 2, 2, 2, 1, 2, 1] , _snake_case : List[int] = [1, 2, 2, 3, 3, 4, 1] , _snake_case : List[int] = [1, 6, 6, 6, 6, 6, 6] , _snake_case : float = 0.25 , _snake_case : str = "swish" , _snake_case : int = 2560 , _snake_case : str = "mean" , _snake_case : float = 0.02 , _snake_case : float = 0.001 , _snake_case : float = 0.99 , _snake_case : float = 0.2 , **_snake_case : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**_snake_case ) a__ = num_channels a__ = image_size a__ = width_coefficient a__ = depth_coefficient a__ = depth_divisor a__ = kernel_sizes a__ = in_channels a__ = out_channels a__ = depthwise_padding a__ = strides a__ = num_block_repeats a__ = expand_ratios a__ = squeeze_expansion_ratio a__ = hidden_act a__ = hidden_dim a__ = pooling_type a__ = initializer_range a__ = batch_norm_eps a__ = batch_norm_momentum a__ = drop_connect_rate a__ = sum(_snake_case ) * 4 @classmethod def _lowerCAmelCase ( cls : Tuple , _snake_case : Union[str, os.PathLike] , **_snake_case : Tuple ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_snake_case ) a__ , a__ = cls.get_config_dict(_snake_case , **_snake_case ) # get the vision config dict if we are loading from AlignConfig if config_dict.get('model_type' ) == "align": a__ = 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(_snake_case , **_snake_case ) class SCREAMING_SNAKE_CASE ( a ): """simple docstring""" a_ : Optional[Any] ="align" a_ : List[str] =True def __init__( self : Tuple , _snake_case : Optional[Any]=None , _snake_case : Union[str, Any]=None , _snake_case : Optional[Any]=640 , _snake_case : Any=1.0 , _snake_case : Optional[int]=0.02 , **_snake_case : List[Any] , ) -> int: '''simple docstring''' super().__init__(**_snake_case ) if text_config is None: a__ = {} logger.info('text_config is None. Initializing the AlignTextConfig with default values.' ) if vision_config is None: a__ = {} logger.info('vision_config is None. Initializing the AlignVisionConfig with default values.' ) a__ = AlignTextConfig(**_snake_case ) a__ = AlignVisionConfig(**_snake_case ) a__ = projection_dim a__ = temperature_init_value a__ = initializer_range @classmethod def _lowerCAmelCase ( cls : Optional[Any] , _snake_case : AlignTextConfig , _snake_case : AlignVisionConfig , **_snake_case : Optional[Any] ) -> Any: '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_snake_case ) def _lowerCAmelCase ( self : Dict ) -> Optional[Any]: '''simple docstring''' a__ = copy.deepcopy(self.__dict__ ) a__ = self.text_config.to_dict() a__ = self.vision_config.to_dict() a__ = self.__class__.model_type return output
232
"""simple docstring""" import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class SCREAMING_SNAKE_CASE ( a ): """simple docstring""" def __init__( self : List[str] , _snake_case : str = "▁" , _snake_case : bool = True , _snake_case : Union[str, AddedToken] = "<unk>" , _snake_case : Union[str, AddedToken] = "</s>" , _snake_case : Union[str, AddedToken] = "<pad>" , ) -> Optional[int]: '''simple docstring''' a__ = { 'pad': {'id': 0, 'token': pad_token}, 'eos': {'id': 1, 'token': eos_token}, 'unk': {'id': 2, 'token': unk_token}, } a__ = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): a__ = token_dict['token'] a__ = Tokenizer(Unigram() ) a__ = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(' {2,}' ) , ' ' ), normalizers.Lowercase(), ] ) a__ = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=_snake_case , add_prefix_space=_snake_case ), pre_tokenizers.Digits(individual_digits=_snake_case ), pre_tokenizers.Punctuation(), ] ) a__ = decoders.Metaspace(replacement=_snake_case , add_prefix_space=_snake_case ) a__ = TemplateProcessing( single=F'''$A {self.special_tokens["eos"]["token"]}''' , special_tokens=[(self.special_tokens['eos']['token'], self.special_tokens['eos']['id'])] , ) a__ = { 'model': 'SentencePieceUnigram', 'replacement': replacement, 'add_prefix_space': add_prefix_space, } super().__init__(_snake_case , _snake_case ) def _lowerCAmelCase ( self : Dict , _snake_case : Union[str, List[str]] , _snake_case : int = 8000 , _snake_case : bool = True , ) -> str: '''simple docstring''' a__ = trainers.UnigramTrainer( vocab_size=_snake_case , special_tokens=self.special_tokens_list , show_progress=_snake_case , ) if isinstance(_snake_case , _snake_case ): a__ = [files] self._tokenizer.train(_snake_case , trainer=_snake_case ) self.add_unk_id() def _lowerCAmelCase ( self : Union[str, Any] , _snake_case : Union[Iterator[str], Iterator[Iterator[str]]] , _snake_case : int = 8000 , _snake_case : bool = True , ) -> Optional[Any]: '''simple docstring''' a__ = trainers.UnigramTrainer( vocab_size=_snake_case , special_tokens=self.special_tokens_list , show_progress=_snake_case , ) self._tokenizer.train_from_iterator(_snake_case , trainer=_snake_case ) self.add_unk_id() def _lowerCAmelCase ( self : List[Any] ) -> int: '''simple docstring''' a__ = json.loads(self._tokenizer.to_str() ) a__ = self.special_tokens['unk']['id'] a__ = Tokenizer.from_str(json.dumps(_snake_case ) )
232
1
import numpy as np UpperCamelCase_ = [ ['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'k'], ['l', 'm', 'n', 'o', 'p'], ['q', 'r', 's', 't', 'u'], ['v', 'w', 'x', 'y', 'z'], ] class snake_case_ : '''simple docstring''' def __init__( self ) -> Union[str, Any]: UpperCAmelCase__ =np.array(UpperCamelCase__ ) def __UpperCAmelCase ( self, A_ ) -> int: UpperCAmelCase__ =np.where(letter == self.SQUARE ) UpperCAmelCase__ =np.concatenate([indexa + 1, indexa + 1] ) return indexes def __UpperCAmelCase ( self, A_, A_ ) -> str: UpperCAmelCase__ =self.SQUARE[indexa - 1, indexa - 1] return letter def __UpperCAmelCase ( self, A_ ) -> Dict: UpperCAmelCase__ =message.lower() UpperCAmelCase__ =message.replace(" ", "" ) UpperCAmelCase__ =message.replace("j", "i" ) UpperCAmelCase__ =np.empty((2, len(UpperCamelCase__ )) ) for letter_index in range(len(UpperCamelCase__ ) ): UpperCAmelCase__ =self.letter_to_numbers(message[letter_index] ) UpperCAmelCase__ =numbers[0] UpperCAmelCase__ =numbers[1] UpperCAmelCase__ =first_step.reshape(2 * len(UpperCamelCase__ ) ) UpperCAmelCase__ ='''''' for numbers_index in range(len(UpperCamelCase__ ) ): UpperCAmelCase__ =int(second_step[numbers_index * 2] ) UpperCAmelCase__ =int(second_step[(numbers_index * 2) + 1] ) UpperCAmelCase__ =self.numbers_to_letter(UpperCamelCase__, UpperCamelCase__ ) UpperCAmelCase__ =encoded_message + letter return encoded_message def __UpperCAmelCase ( self, A_ ) -> List[str]: UpperCAmelCase__ =message.lower() message.replace(" ", "" ) UpperCAmelCase__ =np.empty(2 * len(UpperCamelCase__ ) ) for letter_index in range(len(UpperCamelCase__ ) ): UpperCAmelCase__ =self.letter_to_numbers(message[letter_index] ) UpperCAmelCase__ =numbers[0] UpperCAmelCase__ =numbers[1] UpperCAmelCase__ =first_step.reshape((2, len(UpperCamelCase__ )) ) UpperCAmelCase__ ='''''' for numbers_index in range(len(UpperCamelCase__ ) ): UpperCAmelCase__ =int(second_step[0, numbers_index] ) UpperCAmelCase__ =int(second_step[1, numbers_index] ) UpperCAmelCase__ =self.numbers_to_letter(UpperCamelCase__, UpperCamelCase__ ) UpperCAmelCase__ =decoded_message + letter return decoded_message
711
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class snake_case_ ( TensorFormatter[Mapping, 'torch.Tensor', Mapping] ): '''simple docstring''' def __init__( self, A_=None, **A_ ) -> Tuple: super().__init__(features=A_ ) UpperCAmelCase__ =torch_tensor_kwargs import torch # noqa import torch at initialization def __UpperCAmelCase ( self, A_ ) -> Dict: import torch if isinstance(A_, A_ ) and column: if all( isinstance(A_, torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(A_ ) return column def __UpperCAmelCase ( self, A_ ) -> Dict: import torch if isinstance(A_, (str, bytes, type(A_ )) ): return value elif isinstance(A_, (np.character, np.ndarray) ) and np.issubdtype(value.dtype, np.character ): return value.tolist() UpperCAmelCase__ ={} if isinstance(A_, (np.number, np.ndarray) ) and np.issubdtype(value.dtype, np.integer ): UpperCAmelCase__ ={"dtype": torch.intaa} elif isinstance(A_, (np.number, np.ndarray) ) and np.issubdtype(value.dtype, np.floating ): UpperCAmelCase__ ={"dtype": torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(A_, PIL.Image.Image ): UpperCAmelCase__ =np.asarray(A_ ) return torch.tensor(A_, **{**default_dtype, **self.torch_tensor_kwargs} ) def __UpperCAmelCase ( self, A_ ) -> int: import torch # support for torch, tf, jax etc. if hasattr(A_, "__array__" ) and not isinstance(A_, torch.Tensor ): UpperCAmelCase__ =data_struct.__array__() # support for nested types like struct of list of struct if isinstance(A_, np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(A_ ) for substruct in data_struct] ) elif isinstance(A_, (list, tuple) ): return self._consolidate([self.recursive_tensorize(A_ ) for substruct in data_struct] ) return self._tensorize(A_ ) def __UpperCAmelCase ( self, A_ ) -> List[Any]: return map_nested(self._recursive_tensorize, A_, map_list=A_ ) def __UpperCAmelCase ( self, A_ ) -> Mapping: UpperCAmelCase__ =self.numpy_arrow_extractor().extract_row(A_ ) UpperCAmelCase__ =self.python_features_decoder.decode_row(A_ ) return self.recursive_tensorize(A_ ) def __UpperCAmelCase ( self, A_ ) -> "torch.Tensor": UpperCAmelCase__ =self.numpy_arrow_extractor().extract_column(A_ ) UpperCAmelCase__ =self.python_features_decoder.decode_column(A_, pa_table.column_names[0] ) UpperCAmelCase__ =self.recursive_tensorize(A_ ) UpperCAmelCase__ =self._consolidate(A_ ) return column def __UpperCAmelCase ( self, A_ ) -> Mapping: UpperCAmelCase__ =self.numpy_arrow_extractor().extract_batch(A_ ) UpperCAmelCase__ =self.python_features_decoder.decode_batch(A_ ) UpperCAmelCase__ =self.recursive_tensorize(A_ ) for column_name in batch: UpperCAmelCase__ =self._consolidate(batch[column_name] ) return batch
510
0
'''simple docstring''' import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig UpperCAmelCase_ = { 'facebook/maskformer-swin-base-ade': ( 'https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json' ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } UpperCAmelCase_ = logging.get_logger(__name__) class lowerCAmelCase_ ( lowerCamelCase_ ): '''simple docstring''' lowerCAmelCase_ : List[str] = """maskformer""" lowerCAmelCase_ : Tuple = {"""hidden_size""": """mask_feature_size"""} lowerCAmelCase_ : Union[str, Any] = ["""resnet""", """swin"""] lowerCAmelCase_ : Any = ["""detr"""] def __init__( self : Optional[int] , _UpperCAmelCase : int = 2_56 , _UpperCAmelCase : int = 2_56 , _UpperCAmelCase : float = 0.1 , _UpperCAmelCase : bool = False , _UpperCAmelCase : Optional[Dict] = None , _UpperCAmelCase : Optional[Dict] = None , _UpperCAmelCase : float = 0.02 , _UpperCAmelCase : float = 1.0 , _UpperCAmelCase : float = 1.0 , _UpperCAmelCase : float = 1.0 , _UpperCAmelCase : float = 20.0 , _UpperCAmelCase : Optional[bool] = None , **_UpperCAmelCase : Union[str, Any] , ): """simple docstring""" if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k UpperCAmelCase__ = SwinConfig( image_size=3_84 , in_channels=3 , patch_size=4 , embed_dim=1_28 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] , ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ): UpperCAmelCase__ = backbone_config.pop("""model_type""" ) UpperCAmelCase__ = CONFIG_MAPPING[backbone_model_type] UpperCAmelCase__ = config_class.from_dict(_UpperCAmelCase ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. ''' f'''Supported model types: {','.join(self.backbones_supported )}''' ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 UpperCAmelCase__ = DetrConfig() else: # verify that the decoder is supported UpperCAmelCase__ = ( decoder_config.pop("""model_type""" ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( f'''Transformer Decoder {decoder_type} not supported, please use one of''' f''' {','.join(self.decoders_supported )}''' ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ): UpperCAmelCase__ = CONFIG_MAPPING[decoder_type] UpperCAmelCase__ = config_class.from_dict(_UpperCAmelCase ) UpperCAmelCase__ = backbone_config UpperCAmelCase__ = decoder_config # main feature dimension for the model UpperCAmelCase__ = fpn_feature_size UpperCAmelCase__ = mask_feature_size # initializer UpperCAmelCase__ = init_std UpperCAmelCase__ = init_xavier_std # Hungarian matcher && loss UpperCAmelCase__ = cross_entropy_weight UpperCAmelCase__ = dice_weight UpperCAmelCase__ = mask_weight UpperCAmelCase__ = use_auxiliary_loss UpperCAmelCase__ = no_object_weight UpperCAmelCase__ = output_auxiliary_logits UpperCAmelCase__ = self.decoder_config.encoder_attention_heads UpperCAmelCase__ = self.decoder_config.num_hidden_layers super().__init__(**_UpperCAmelCase ) @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Tuple , _UpperCAmelCase : PretrainedConfig , _UpperCAmelCase : PretrainedConfig , **_UpperCAmelCase : List[str] ): """simple docstring""" return cls( backbone_config=_UpperCAmelCase , decoder_config=_UpperCAmelCase , **_UpperCAmelCase , ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" UpperCAmelCase__ = copy.deepcopy(self.__dict__ ) UpperCAmelCase__ = self.backbone_config.to_dict() UpperCAmelCase__ = self.decoder_config.to_dict() UpperCAmelCase__ = self.__class__.model_type return output
603
'''simple docstring''' import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( lowerCamelCase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ : List[Any] = PegasusTokenizer lowerCAmelCase_ : Optional[Any] = PegasusTokenizerFast lowerCAmelCase_ : Optional[int] = True lowerCAmelCase_ : List[str] = True def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase__ = PegasusTokenizer(_UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" return PegasusTokenizer.from_pretrained("""google/pegasus-large""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , **_UpperCAmelCase : Union[str, Any] ): """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : int , _UpperCAmelCase : List[str] ): """simple docstring""" return ("This is a test", "This is a test") def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = """</s>""" UpperCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase ) , _UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase ) , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" UpperCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<pad>""" ) self.assertEqual(vocab_keys[1] , """</s>""" ) self.assertEqual(vocab_keys[-1] , """v""" ) self.assertEqual(len(_UpperCAmelCase ) , 11_03 ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 11_03 ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" UpperCAmelCase__ = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase__ = self.tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase__ = ( """Let's see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important""" """ </s> <pad> <pad> <pad>""" ) UpperCAmelCase__ = rust_tokenizer([raw_input_str] , return_tensors=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase ).input_ids[0] UpperCAmelCase__ = py_tokenizer([raw_input_str] , return_tensors=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase ).input_ids[0] self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word UpperCAmelCase__ = """<mask_1> To ensure a <mask_2> flow of bank resolutions.""" UpperCAmelCase__ = [2, 4_13, 6_15, 1_14, 3, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] UpperCAmelCase__ = tokenizer([raw_input_str] , return_tensors=_UpperCAmelCase ).input_ids[0] self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_61_03 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_03 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_05 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 10_24 UpperCAmelCase__ = """To ensure a smooth flow of bank resolutions.""" UpperCAmelCase__ = [4_13, 6_15, 1_14, 22_91, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] UpperCAmelCase__ = tokenizer([raw_input_str] , return_tensors=_UpperCAmelCase ).input_ids[0] self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" UpperCAmelCase__ = ["""This is going to be way too long.""" * 1_50, """short example"""] UpperCAmelCase__ = ["""not super long but more than 5 tokens""", """tiny"""] UpperCAmelCase__ = self._large_tokenizer(_UpperCAmelCase , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , return_tensors="""pt""" ) UpperCAmelCase__ = self._large_tokenizer( text_target=_UpperCAmelCase , max_length=5 , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , return_tensors="""pt""" ) assert batch.input_ids.shape == (2, 10_24) assert batch.attention_mask.shape == (2, 10_24) assert targets["input_ids"].shape == (2, 5) assert len(_UpperCAmelCase ) == 2 # input_ids, attention_mask. @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = {"""input_ids""": [[3_89_79, 1_43, 1_84_85, 6_06, 1_30, 2_66_69, 8_76_86, 1_21, 5_41_89, 11_29, 1_11, 2_66_69, 8_76_86, 1_21, 91_14, 1_47_87, 1_21, 1_32_49, 1_58, 5_92, 9_56, 1_21, 1_46_21, 3_15_76, 1_43, 6_26_13, 1_08, 96_88, 9_30, 4_34_30, 1_15_62, 6_26_13, 3_04, 1_08, 1_14_43, 8_97, 1_08, 93_14, 1_74_15, 6_33_99, 1_08, 1_14_43, 76_14, 1_83_16, 1_18, 42_84, 71_48, 1_24_30, 1_43, 14_00, 2_57_03, 1_58, 1_11, 42_84, 71_48, 1_17_72, 1_43, 2_12_97, 10_64, 1_58, 1_22, 2_04, 35_06, 17_54, 11_33, 1_47_87, 15_81, 1_15, 3_32_24, 44_82, 1_11, 13_55, 1_10, 2_91_73, 3_17, 5_08_33, 1_08, 2_01_47, 9_46_65, 1_11, 7_71_98, 1_07, 1], [1_10, 6_26_13, 1_17, 6_38, 1_12, 11_33, 1_21, 2_00_98, 13_55, 7_90_50, 1_38_72, 1_35, 15_96, 5_35_41, 13_52, 1_41, 1_30_39, 55_42, 1_24, 3_02, 5_18, 1_11, 2_68, 29_56, 1_15, 1_49, 44_27, 1_07, 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], [1_39, 12_35, 27_99, 1_82_89, 1_77_80, 2_04, 1_09, 94_74, 12_96, 1_07, 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]], """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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=_UpperCAmelCase , model_name="""google/bigbird-pegasus-large-arxiv""" , revision="""ba85d0851d708441f91440d509690f1ab6353415""" , ) @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( lowerCamelCase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ : List[str] = PegasusTokenizer lowerCAmelCase_ : int = PegasusTokenizerFast lowerCAmelCase_ : List[Any] = True lowerCAmelCase_ : Union[str, Any] = True def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase__ = PegasusTokenizer(_UpperCAmelCase , offset=0 , mask_token_sent=_UpperCAmelCase , mask_token="""[MASK]""" ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" return PegasusTokenizer.from_pretrained("""google/bigbird-pegasus-large-arxiv""" ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , **_UpperCAmelCase : str ): """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **_UpperCAmelCase ) def SCREAMING_SNAKE_CASE__ ( self : Any , _UpperCAmelCase : Any ): """simple docstring""" return ("This is a test", "This is a test") def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase__ = self.tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase__ = ( """Let's see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>""" """ <pad> <pad> <pad>""" ) UpperCAmelCase__ = rust_tokenizer([raw_input_str] , return_tensors=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase ).input_ids[0] UpperCAmelCase__ = py_tokenizer([raw_input_str] , return_tensors=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase ).input_ids[0] self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase ) @require_torch def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" UpperCAmelCase__ = ["""This is going to be way too long.""" * 10_00, """short example"""] UpperCAmelCase__ = ["""not super long but more than 5 tokens""", """tiny"""] UpperCAmelCase__ = self._large_tokenizer(_UpperCAmelCase , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , return_tensors="""pt""" ) UpperCAmelCase__ = self._large_tokenizer( text_target=_UpperCAmelCase , max_length=5 , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , return_tensors="""pt""" ) assert batch.input_ids.shape == (2, 40_96) assert batch.attention_mask.shape == (2, 40_96) assert targets["input_ids"].shape == (2, 5) assert len(_UpperCAmelCase ) == 2 # input_ids, attention_mask. def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" UpperCAmelCase__ = ( """This is an example string that is used to test the original TF implementation against the HF""" """ implementation""" ) UpperCAmelCase__ = self._large_tokenizer(_UpperCAmelCase ).input_ids self.assertListEqual( _UpperCAmelCase , [1_82, 1_17, 1_42, 5_87, 42_11, 1_20, 1_17, 2_63, 1_12, 8_04, 1_09, 8_56, 2_50_16, 31_37, 4_64, 1_09, 2_69_55, 31_37, 1] , )
603
1
'''simple docstring''' from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. a_ : str = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. a_ : Tuple = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. a_ : Optional[int] = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def __snake_case ( UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] ): lowerCamelCase_ = len([g for position, g in enumerate(_lowercase ) if g == main_target[position]] ) return (item, float(_lowercase )) def __snake_case ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any ): lowerCamelCase_ = random.randint(0 , len(_lowercase ) - 1 ) lowerCamelCase_ = parent_a[:random_slice] + parent_a[random_slice:] lowerCamelCase_ = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def __snake_case ( UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] ): lowerCamelCase_ = list(_lowercase ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: lowerCamelCase_ = random.choice(_lowercase ) return "".join(_lowercase ) def __snake_case ( UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , ): lowerCamelCase_ = [] # Generate more children proportionally to the fitness score. lowerCamelCase_ = int(parent_a[1] * 100 ) + 1 lowerCamelCase_ = 10 if child_n >= 10 else child_n for _ in range(_lowercase ): lowerCamelCase_ = population_score[random.randint(0 , _lowercase )][0] lowerCamelCase_ = crossover(parent_a[0] , _lowercase ) # Append new string to the population list. pop.append(mutate(_lowercase , _lowercase ) ) pop.append(mutate(_lowercase , _lowercase ) ) return pop def __snake_case ( UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] = True ): # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: lowerCamelCase_ = F'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(_lowercase ) # Verify that the target contains no genes besides the ones inside genes variable. lowerCamelCase_ = sorted({c for c in target if c not in genes} ) if not_in_genes_list: lowerCamelCase_ = F'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(_lowercase ) # Generate random starting population. lowerCamelCase_ = [] for _ in range(_lowercase ): population.append("".join([random.choice(_lowercase ) for i in range(len(_lowercase ) )] ) ) # Just some logs to know what the algorithms is doing. lowerCamelCase_ = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(_lowercase ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. lowerCamelCase_ = [evaluate(_lowercase , _lowercase ) for item in population] # Check if there is a matching evolution. lowerCamelCase_ = sorted(_lowercase , key=lambda UpperCAmelCase_ : x[1] , reverse=_lowercase ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'''\nGeneration: {generation}''' F'''\nTotal Population:{total_population}''' F'''\nBest score: {population_score[0][1]}''' F'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. lowerCamelCase_ = population[: int(N_POPULATION / 3 )] population.clear() population.extend(_lowercase ) # Normalize population score to be between 0 and 1. lowerCamelCase_ = [ (item, score / len(_lowercase )) for item, score in population_score ] # This is selection for i in range(_lowercase ): population.extend(select(population_score[int(_lowercase )] , _lowercase , _lowercase ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(_lowercase ) > N_POPULATION: break if __name__ == "__main__": a_ : str = ( 'This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!' ) a_ : Optional[int] = list( """ ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm""" """nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\""" ) a_ : Optional[Any] = basic(target_str, genes_list) print( f'''\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}''' )
712
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class snake_case ( lowercase ): """simple docstring""" _lowerCamelCase = None _lowerCamelCase = None _lowerCamelCase = None _lowerCamelCase = None class snake_case ( lowercase ): """simple docstring""" def __init__( self , UpperCamelCase=1 , UpperCamelCase=0 , UpperCamelCase=2 , UpperCamelCase=512 , UpperCamelCase="cls" , UpperCamelCase=False , UpperCamelCase=True , **UpperCamelCase , ): """simple docstring""" super().__init__(pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , **UpperCamelCase ) lowerCamelCase_ = project_dim lowerCamelCase_ = pooler_fn lowerCamelCase_ = learn_encoder lowerCamelCase_ = use_attention_mask class snake_case ( lowercase ): """simple docstring""" _lowerCamelCase = [r"pooler", r"logit_scale"] _lowerCamelCase = [r"position_ids", r"predictions.decoder.bias"] _lowerCamelCase = "roberta" _lowerCamelCase = RobertaSeriesConfig def __init__( self , UpperCamelCase ): """simple docstring""" super().__init__(UpperCamelCase ) lowerCamelCase_ = XLMRobertaModel(UpperCamelCase ) lowerCamelCase_ = nn.Linear(config.hidden_size , config.project_dim ) lowerCamelCase_ = getattr(UpperCamelCase , "has_pre_transformation" , UpperCamelCase ) if self.has_pre_transformation: lowerCamelCase_ = nn.Linear(config.hidden_size , config.project_dim ) lowerCamelCase_ = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def snake_case ( self , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = None , ): """simple docstring""" lowerCamelCase_ = return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase_ = self.base_model( input_ids=UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , position_ids=UpperCamelCase , head_mask=UpperCamelCase , inputs_embeds=UpperCamelCase , encoder_hidden_states=UpperCamelCase , encoder_attention_mask=UpperCamelCase , output_attentions=UpperCamelCase , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=UpperCamelCase , ) if self.has_pre_transformation: lowerCamelCase_ = outputs["hidden_states"][-2] lowerCamelCase_ = self.pre_LN(UpperCamelCase ) lowerCamelCase_ = self.transformation_pre(UpperCamelCase ) return TransformationModelOutput( projection_state=UpperCamelCase , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: lowerCamelCase_ = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=UpperCamelCase , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
445
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase ( metaclass=_snake_case ): UpperCAmelCase = ["note_seq"] def __init__( self : List[str] , *__lowerCamelCase : int , **__lowerCamelCase : Optional[int] ): requires_backends(self , ['''note_seq'''] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls : Optional[Any] , *__lowerCamelCase : Dict , **__lowerCamelCase : Optional[Any] ): requires_backends(cls , ['''note_seq'''] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls : str , *__lowerCamelCase : Any , **__lowerCamelCase : Optional[Any] ): requires_backends(cls , ['''note_seq'''] )
467
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu __lowerCamelCase = False class UpperCAmelCase ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __SCREAMING_SNAKE_CASE ( self : str ): return 1_2 @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ): return 1_2 @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): return 3_2 @property def __SCREAMING_SNAKE_CASE ( self : List[str] ): torch.manual_seed(0 ) UpperCAmelCase__ :List[str] = VQModel( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=3 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def __SCREAMING_SNAKE_CASE ( self : int ): UpperCAmelCase__ :Tuple = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __SCREAMING_SNAKE_CASE ( self : Tuple ): torch.manual_seed(0 ) UpperCAmelCase__ :Optional[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(__lowerCamelCase ) @property def __SCREAMING_SNAKE_CASE ( self : List[str] ): torch.manual_seed(0 ) UpperCAmelCase__ :List[str] = 1_2 UpperCAmelCase__ :Optional[int] = 1_2 UpperCAmelCase__ :Optional[int] = { '''attention_bias''': True, '''cross_attention_dim''': 3_2, '''attention_head_dim''': height * width, '''num_attention_heads''': 1, '''num_vector_embeds''': self.num_embed, '''num_embeds_ada_norm''': self.num_embeds_ada_norm, '''norm_num_groups''': 3_2, '''sample_size''': width, '''activation_fn''': '''geglu-approximate''', } UpperCAmelCase__ :List[str] = TransformeraDModel(**__lowerCamelCase ) return model def __SCREAMING_SNAKE_CASE ( self : List[Any] ): UpperCAmelCase__ :Union[str, Any] = '''cpu''' UpperCAmelCase__ :Optional[Any] = self.dummy_vqvae UpperCAmelCase__ :Optional[int] = self.dummy_text_encoder UpperCAmelCase__ :Union[str, Any] = self.dummy_tokenizer UpperCAmelCase__ :List[Any] = self.dummy_transformer UpperCAmelCase__ :str = VQDiffusionScheduler(self.num_embed ) UpperCAmelCase__ :Optional[Any] = LearnedClassifierFreeSamplingEmbeddings(learnable=__lowerCamelCase ) UpperCAmelCase__ :Any = VQDiffusionPipeline( vqvae=__lowerCamelCase , text_encoder=__lowerCamelCase , tokenizer=__lowerCamelCase , transformer=__lowerCamelCase , scheduler=__lowerCamelCase , learned_classifier_free_sampling_embeddings=__lowerCamelCase , ) UpperCAmelCase__ :Any = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCAmelCase__ :str = '''teddy bear playing in the pool''' UpperCAmelCase__ :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCAmelCase__ :Any = pipe([prompt] , generator=__lowerCamelCase , num_inference_steps=2 , output_type='''np''' ) UpperCAmelCase__ :str = output.images UpperCAmelCase__ :List[Any] = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCAmelCase__ :Dict = pipe( [prompt] , generator=__lowerCamelCase , output_type='''np''' , return_dict=__lowerCamelCase , num_inference_steps=2 )[0] UpperCAmelCase__ :int = image[0, -3:, -3:, -1] UpperCAmelCase__ :List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 2_4, 2_4, 3) UpperCAmelCase__ :int = np.array([0.65_51, 0.61_68, 0.50_08, 0.56_76, 0.56_59, 0.42_95, 0.60_73, 0.55_99, 0.49_92] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __SCREAMING_SNAKE_CASE ( self : Tuple ): UpperCAmelCase__ :List[Any] = '''cpu''' UpperCAmelCase__ :int = self.dummy_vqvae UpperCAmelCase__ :List[str] = self.dummy_text_encoder UpperCAmelCase__ :Union[str, Any] = self.dummy_tokenizer UpperCAmelCase__ :Optional[Any] = self.dummy_transformer UpperCAmelCase__ :List[str] = VQDiffusionScheduler(self.num_embed ) UpperCAmelCase__ :List[str] = LearnedClassifierFreeSamplingEmbeddings( learnable=__lowerCamelCase , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) UpperCAmelCase__ :List[Any] = VQDiffusionPipeline( vqvae=__lowerCamelCase , text_encoder=__lowerCamelCase , tokenizer=__lowerCamelCase , transformer=__lowerCamelCase , scheduler=__lowerCamelCase , learned_classifier_free_sampling_embeddings=__lowerCamelCase , ) UpperCAmelCase__ :str = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) UpperCAmelCase__ :str = '''teddy bear playing in the pool''' UpperCAmelCase__ :str = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCAmelCase__ :Union[str, Any] = pipe([prompt] , generator=__lowerCamelCase , num_inference_steps=2 , output_type='''np''' ) UpperCAmelCase__ :Any = output.images UpperCAmelCase__ :Optional[int] = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCAmelCase__ :int = pipe( [prompt] , generator=__lowerCamelCase , output_type='''np''' , return_dict=__lowerCamelCase , num_inference_steps=2 )[0] UpperCAmelCase__ :List[Any] = image[0, -3:, -3:, -1] UpperCAmelCase__ :Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 2_4, 2_4, 3) UpperCAmelCase__ :Union[str, Any] = np.array([0.66_93, 0.60_75, 0.49_59, 0.57_01, 0.55_83, 0.43_33, 0.61_71, 0.56_84, 0.49_88] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class UpperCAmelCase ( 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 : Optional[int] ): UpperCAmelCase__ :Optional[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy''' ) UpperCAmelCase__ :Optional[Any] = VQDiffusionPipeline.from_pretrained('''microsoft/vq-diffusion-ithq''' ) UpperCAmelCase__ :List[str] = pipeline.to(__lowerCamelCase ) pipeline.set_progress_bar_config(disable=__lowerCamelCase ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though UpperCAmelCase__ :int = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) UpperCAmelCase__ :Union[str, Any] = pipeline( '''teddy bear playing in the pool''' , num_images_per_prompt=1 , generator=__lowerCamelCase , output_type='''np''' , ) UpperCAmelCase__ :List[str] = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) assert np.abs(expected_image - image ).max() < 2.0
467
1
import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __a ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): __lowercase : Tuple = VQModel __lowercase : Union[str, Any] = 'sample' @property def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=(32, 32) ) -> Optional[int]: '''simple docstring''' lowercase__: List[Any] = 4 lowercase__: int = 3 lowercase__: List[str] = floats_tensor((batch_size, num_channels) + sizes ).to(lowerCAmelCase__ ) return {"sample": image} @property def SCREAMING_SNAKE_CASE__ ( self ) -> Any: '''simple docstring''' return (3, 32, 32) @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: '''simple docstring''' return (3, 32, 32) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: '''simple docstring''' lowercase__: str = { 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 3, } lowercase__: Any = self.dummy_input return init_dict, inputs_dict def SCREAMING_SNAKE_CASE__ ( self ) -> Any: '''simple docstring''' pass def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: '''simple docstring''' pass def SCREAMING_SNAKE_CASE__ ( self ) -> str: '''simple docstring''' lowercase__ , lowercase__: Any = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) self.assertEqual(len(loading_info['missing_keys'] ) , 0 ) model.to(lowerCAmelCase__ ) lowercase__: Tuple = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: '''simple docstring''' lowercase__: List[Any] = VQModel.from_pretrained('fusing/vqgan-dummy' ) model.to(lowerCAmelCase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) lowercase__: str = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) lowercase__: Dict = image.to(lowerCAmelCase__ ) with torch.no_grad(): lowercase__: str = model(lowerCAmelCase__ ).sample lowercase__: Union[str, Any] = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off lowercase__: Dict = torch.tensor([-0.0_1_5_3, -0.4_0_4_4, -0.1_8_8_0, -0.5_1_6_1, -0.2_4_1_8, -0.4_0_7_2, -0.1_6_1_2, -0.0_6_3_3, -0.0_1_4_3] ) # fmt: on self.assertTrue(torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) )
702
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 __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { '''microsoft/beit-base-patch16-224-pt22k''': ( '''https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json''' ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __a ( __UpperCamelCase ): __lowercase : Optional[Any] = 'beit' def __init__( self , lowerCAmelCase__=8_192 , lowerCAmelCase__=768 , lowerCAmelCase__=12 , lowerCAmelCase__=12 , lowerCAmelCase__=3_072 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0_2 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=224 , lowerCAmelCase__=16 , lowerCAmelCase__=3 , lowerCAmelCase__=False , lowerCAmelCase__=False , lowerCAmelCase__=False , lowerCAmelCase__=False , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=True , lowerCAmelCase__=[3, 5, 7, 11] , lowerCAmelCase__=[1, 2, 3, 6] , lowerCAmelCase__=True , lowerCAmelCase__=0.4 , lowerCAmelCase__=256 , lowerCAmelCase__=1 , lowerCAmelCase__=False , lowerCAmelCase__=255 , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__(**lowerCAmelCase__ ) lowercase__: Optional[Any] = vocab_size lowercase__: Dict = hidden_size lowercase__: int = num_hidden_layers lowercase__: List[Any] = num_attention_heads lowercase__: List[str] = intermediate_size lowercase__: Any = hidden_act lowercase__: List[str] = hidden_dropout_prob lowercase__: Dict = attention_probs_dropout_prob lowercase__: Optional[Any] = initializer_range lowercase__: Tuple = layer_norm_eps lowercase__: Optional[Any] = image_size lowercase__: List[str] = patch_size lowercase__: List[str] = num_channels lowercase__: List[Any] = use_mask_token lowercase__: Tuple = use_absolute_position_embeddings lowercase__: Tuple = use_relative_position_bias lowercase__: int = use_shared_relative_position_bias lowercase__: Dict = layer_scale_init_value lowercase__: List[Any] = drop_path_rate lowercase__: Optional[int] = use_mean_pooling # decode head attributes (semantic segmentation) lowercase__: Optional[Any] = out_indices lowercase__: Tuple = pool_scales # auxiliary head attributes (semantic segmentation) lowercase__: Dict = use_auxiliary_head lowercase__: Union[str, Any] = auxiliary_loss_weight lowercase__: Tuple = auxiliary_channels lowercase__: Any = auxiliary_num_convs lowercase__: Optional[Any] = auxiliary_concat_input lowercase__: Optional[int] = semantic_loss_ignore_index class __a ( __UpperCamelCase ): __lowercase : Optional[int] = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> float: '''simple docstring''' return 1E-4
335
0
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
662
UpperCAmelCase_ = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", "\"": ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", "!": "-.-.--", " ": "/" } # Exclamation mark is not in ITU-R recommendation # fmt: on UpperCAmelCase_ = {value: key for key, value in MORSE_CODE_DICT.items()} def A__ ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def A__ ( SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" return "".join(REVERSE_DICT[char] for char in message.split() ) def A__ ( ) -> None: """simple docstring""" _UpperCAmelCase = '''Morse code here!''' print(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = encrypt(SCREAMING_SNAKE_CASE_ ) print(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = decrypt(SCREAMING_SNAKE_CASE_ ) print(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
32
0
from collections import Counter from timeit import timeit def _lowerCamelCase ( SCREAMING_SNAKE_CASE = "" , ): return sum(c % 2 for c in Counter(input_str.replace(''' ''' , '''''' ).lower() ).values() ) < 2 def _lowerCamelCase ( SCREAMING_SNAKE_CASE = "" ): if len(SCREAMING_SNAKE_CASE ) == 0: return True A_ = input_str.replace(''' ''' , '''''' ).lower() # character_freq_dict: Stores the frequency of every character in the input string A_ = {} for character in lower_case_input_str: A_ = character_freq_dict.get(SCREAMING_SNAKE_CASE , 0 ) + 1 A_ = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def _lowerCamelCase ( SCREAMING_SNAKE_CASE = "" ): print('''\nFor string = ''' , SCREAMING_SNAKE_CASE , ''':''' ) print( '''> can_string_be_rearranged_as_palindrome_counter()''' , '''\tans =''' , can_string_be_rearranged_as_palindrome_counter(SCREAMING_SNAKE_CASE ) , '''\ttime =''' , timeit( '''z.can_string_be_rearranged_as_palindrome_counter(z.check_str)''' , setup='''import __main__ as z''' , ) , '''seconds''' , ) print( '''> can_string_be_rearranged_as_palindrome()''' , '''\tans =''' , can_string_be_rearranged_as_palindrome(SCREAMING_SNAKE_CASE ) , '''\ttime =''' , timeit( '''z.can_string_be_rearranged_as_palindrome(z.check_str)''' , setup='''import __main__ as z''' , ) , '''seconds''' , ) if __name__ == "__main__": __lowercase = input( """Enter string to determine if it can be rearranged as a palindrome or not: """ ).strip() benchmark(check_str) __lowercase = can_string_be_rearranged_as_palindrome_counter(check_str) print(f'{check_str} can {"" if status else "not "}be rearranged as a palindrome')
720
def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' A_ = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' A_ = 0 while b > 0: if b & 1: A_ = ((res % c) + (a % c)) % c a += a b >>= 1 return res
563
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase_ : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Any = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys UpperCAmelCase_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
44
"""simple docstring""" _snake_case = 6_5521 def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : List[str] = 1 _a : Optional[int] = 0 for plain_chr in plain_text: _a : Dict = (a + ord(UpperCamelCase__ )) % MOD_ADLER _a : List[Any] = (b + a) % MOD_ADLER return (b << 1_6) | a
389
0
'''simple docstring''' import pytest import datasets # Import fixture modules as plugins lowerCAmelCase__ = ["tests.fixtures.files", "tests.fixtures.hub", "tests.fixtures.fsspec"] def SCREAMING_SNAKE_CASE( UpperCamelCase ,UpperCamelCase ) -> Union[str, Any]: # Mark tests as "unit" by default if not marked as "integration" (or already marked as "unit") for item in items: if any(marker in item.keywords for marker in ['integration', 'unit'] ): continue item.add_marker(pytest.mark.unit ) def SCREAMING_SNAKE_CASE( UpperCamelCase ) -> Union[str, Any]: config.addinivalue_line('markers' ,'torchaudio_latest: mark test to run with torchaudio>=0.12' ) @pytest.fixture(autouse=UpperCamelCase ) def SCREAMING_SNAKE_CASE( UpperCamelCase ,UpperCamelCase ) -> Dict: # test_hf_cache_home = tmp_path_factory.mktemp("cache") # TODO: why a cache dir per test function does not work? UpperCAmelCase_ : Any = tmp_path_factory.getbasetemp() / 'cache' UpperCAmelCase_ : Optional[Any] = test_hf_cache_home / 'datasets' UpperCAmelCase_ : Any = test_hf_cache_home / 'metrics' UpperCAmelCase_ : Optional[int] = test_hf_cache_home / 'modules' monkeypatch.setattr('datasets.config.HF_DATASETS_CACHE' ,str(UpperCamelCase ) ) monkeypatch.setattr('datasets.config.HF_METRICS_CACHE' ,str(UpperCamelCase ) ) monkeypatch.setattr('datasets.config.HF_MODULES_CACHE' ,str(UpperCamelCase ) ) UpperCAmelCase_ : Any = test_hf_datasets_cache / 'downloads' monkeypatch.setattr('datasets.config.DOWNLOADED_DATASETS_PATH' ,str(UpperCamelCase ) ) UpperCAmelCase_ : int = test_hf_datasets_cache / 'downloads' / 'extracted' monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' ,str(UpperCamelCase ) ) @pytest.fixture(autouse=UpperCamelCase ,scope='session' ) def SCREAMING_SNAKE_CASE( ) -> Optional[Any]: datasets.disable_progress_bar() @pytest.fixture(autouse=UpperCamelCase ) def SCREAMING_SNAKE_CASE( UpperCamelCase ) -> str: # don't take tests into account when counting downloads monkeypatch.setattr('datasets.config.HF_UPDATE_DOWNLOAD_COUNTS' ,UpperCamelCase ) @pytest.fixture def SCREAMING_SNAKE_CASE( UpperCamelCase ) -> int: # Required to suppress RemovedIn20Warning when feature(s) are not compatible with SQLAlchemy 2.0 # To be removed once SQLAlchemy 2.0 supported monkeypatch.setattr('sqlalchemy.util.deprecations.SILENCE_UBER_WARNING' ,UpperCamelCase )
471
'''simple docstring''' import numpy class lowercase : def __init__( self , _snake_case , _snake_case) -> None: UpperCAmelCase_ : Optional[Any] = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. UpperCAmelCase_ : Tuple = numpy.random.rand( self.input_array.shape[1] , 4) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. UpperCAmelCase_ : List[str] = numpy.random.rand( 4 , 3) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. UpperCAmelCase_ : Dict = numpy.random.rand(3 , 1) # Real output values provided. UpperCAmelCase_ : str = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. UpperCAmelCase_ : Union[str, Any] = numpy.zeros(output_array.shape) def _snake_case ( self) -> numpy.ndarray: UpperCAmelCase_ : Any = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights)) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. UpperCAmelCase_ : Tuple = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , )) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. UpperCAmelCase_ : int = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , )) return self.layer_between_second_hidden_layer_and_output def _snake_case ( self) -> None: UpperCAmelCase_ : Optional[int] = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , ) UpperCAmelCase_ : Any = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer) , ) UpperCAmelCase_ : Tuple = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def _snake_case ( self , _snake_case , _snake_case , _snake_case) -> None: for iteration in range(1 , iterations + 1): UpperCAmelCase_ : int = self.feedforward() self.back_propagation() if give_loss: UpperCAmelCase_ : List[Any] = numpy.mean(numpy.square(output - self.feedforward())) print(F"""Iteration {iteration} Loss: {loss}""") def _snake_case ( self , _snake_case) -> int: UpperCAmelCase_ : Optional[int] = input_arr UpperCAmelCase_ : Tuple = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights)) UpperCAmelCase_ : Optional[int] = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , )) UpperCAmelCase_ : int = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , )) return int(self.layer_between_second_hidden_layer_and_output > 0.6) def SCREAMING_SNAKE_CASE( UpperCamelCase ) -> numpy.ndarray: return 1 / (1 + numpy.exp(-value )) def SCREAMING_SNAKE_CASE( UpperCamelCase ) -> numpy.ndarray: return (value) * (1 - (value)) def SCREAMING_SNAKE_CASE( ) -> int: UpperCAmelCase_ : Optional[int] = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ) ,dtype=numpy.floataa ,) # True output values for the given input values. UpperCAmelCase_ : Dict = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) ,dtype=numpy.floataa ) # Calling neural network class. UpperCAmelCase_ : List[str] = TwoHiddenLayerNeuralNetwork( input_array=UpperCamelCase ,output_array=UpperCamelCase ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=UpperCamelCase ,iterations=1_0 ,give_loss=UpperCamelCase ) return neural_network.predict(numpy.array(([1, 1, 1]) ,dtype=numpy.floataa ) ) if __name__ == "__main__": example()
471
1
"""simple docstring""" class a : def __init__( self , _snake_case ): """simple docstring""" lowerCAmelCase = size lowerCAmelCase = [0] * size lowerCAmelCase = [0] * size @staticmethod def UpperCamelCase__ ( _snake_case ): """simple docstring""" return index | (index + 1) @staticmethod def UpperCamelCase__ ( _snake_case ): """simple docstring""" return (index & (index + 1)) - 1 def UpperCamelCase__ ( self , _snake_case , _snake_case ): """simple docstring""" lowerCAmelCase = value while index < self.size: lowerCAmelCase = self.get_prev(_snake_case ) + 1 if current_left_border == index: lowerCAmelCase = value else: lowerCAmelCase = max(_snake_case , _snake_case , _snake_case ) lowerCAmelCase = self.get_next(_snake_case ) def UpperCamelCase__ ( self , _snake_case , _snake_case ): """simple docstring""" right -= 1 # Because of right is exclusive lowerCAmelCase = 0 while left <= right: lowerCAmelCase = self.get_prev(_snake_case ) if left <= current_left: lowerCAmelCase = max(_snake_case , self.tree[right] ) lowerCAmelCase = current_left else: lowerCAmelCase = max(_snake_case , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
4
'''simple docstring''' import unittest from typing import Dict, List, Optional, Union import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BridgeTowerImageProcessor class lowercase_ ( unittest.TestCase ): """simple docstring""" def __init__( self : Tuple , __lowerCamelCase : Dict , __lowerCamelCase : bool = True , __lowerCamelCase : Dict[str, int] = None , __lowerCamelCase : int = 3_2 , __lowerCamelCase : bool = True , __lowerCamelCase : Union[int, float] = 1 / 2_5_5 , __lowerCamelCase : bool = True , __lowerCamelCase : bool = True , __lowerCamelCase : Optional[Union[float, List[float]]] = [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , __lowerCamelCase : Optional[Union[float, List[float]]] = [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , __lowerCamelCase : bool = True , __lowerCamelCase : str=7 , __lowerCamelCase : Union[str, Any]=3_0 , __lowerCamelCase : Tuple=4_0_0 , __lowerCamelCase : List[Any]=3 , ): """simple docstring""" _SCREAMING_SNAKE_CASE = parent _SCREAMING_SNAKE_CASE = do_resize _SCREAMING_SNAKE_CASE = size if size is not None else {"shortest_edge": 2_8_8} _SCREAMING_SNAKE_CASE = size_divisor _SCREAMING_SNAKE_CASE = do_rescale _SCREAMING_SNAKE_CASE = rescale_factor _SCREAMING_SNAKE_CASE = do_normalize _SCREAMING_SNAKE_CASE = do_center_crop _SCREAMING_SNAKE_CASE = image_mean _SCREAMING_SNAKE_CASE = image_std _SCREAMING_SNAKE_CASE = do_pad _SCREAMING_SNAKE_CASE = batch_size _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = min_resolution _SCREAMING_SNAKE_CASE = max_resolution def lowerCAmelCase_ ( self : Union[str, Any] ): """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def lowerCAmelCase_ ( self : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : int=False ): """simple docstring""" if not batched: _SCREAMING_SNAKE_CASE = self.size["shortest_edge"] _SCREAMING_SNAKE_CASE = image_inputs[0] if isinstance(__lowerCamelCase , Image.Image ): _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = image.size else: _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = image.shape[1], image.shape[2] _SCREAMING_SNAKE_CASE = size / min(__lowerCamelCase , __lowerCamelCase ) if h < w: _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = size, scale * w else: _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = scale * h, size _SCREAMING_SNAKE_CASE = int((1_3_3_3 / 8_0_0) * size ) if max(__lowerCamelCase , __lowerCamelCase ) > max_size: _SCREAMING_SNAKE_CASE = max_size / max(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = newh * scale _SCREAMING_SNAKE_CASE = neww * scale _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = int(newh + 0.5 ), int(neww + 0.5 ) _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: _SCREAMING_SNAKE_CASE = [] for image in image_inputs: _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _SCREAMING_SNAKE_CASE = max(__lowerCamelCase , key=lambda __lowerCamelCase : item[0] )[0] _SCREAMING_SNAKE_CASE = max(__lowerCamelCase , key=lambda __lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowercase_ ( A , unittest.TestCase ): """simple docstring""" lowerCamelCase_ = BridgeTowerImageProcessor if is_vision_available() else None def lowerCAmelCase_ ( self : Any ): """simple docstring""" _SCREAMING_SNAKE_CASE = BridgeTowerImageProcessingTester(self ) @property def lowerCAmelCase_ ( self : int ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase_ ( self : Optional[int] ): """simple docstring""" _SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(__lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(__lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(__lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(__lowerCamelCase , "size" ) ) self.assertTrue(hasattr(__lowerCamelCase , "size_divisor" ) ) def lowerCAmelCase_ ( self : Optional[Any] ): """simple docstring""" pass def lowerCAmelCase_ ( self : Optional[int] ): """simple docstring""" # Initialize image processor _SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _SCREAMING_SNAKE_CASE = image_processing(__lowerCamelCase , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCAmelCase_ ( self : str ): """simple docstring""" # Initialize image processor _SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase , numpify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , np.ndarray ) # Test not batched input _SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _SCREAMING_SNAKE_CASE = image_processing(__lowerCamelCase , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCAmelCase_ ( self : str ): """simple docstring""" # Initialize image processor _SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCamelCase , torchify=__lowerCamelCase ) for image in image_inputs: self.assertIsInstance(__lowerCamelCase , torch.Tensor ) # Test not batched input _SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(__lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _SCREAMING_SNAKE_CASE = image_processing(__lowerCamelCase , return_tensors="pt" ).pixel_values _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(__lowerCamelCase , batched=__lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
418
0
"""simple docstring""" A : Optional[Any] = [ 'VerificationMode', 'Version', 'disable_progress_bar', 'enable_progress_bar', 'is_progress_bar_enabled', 'experimental', ] from .info_utils import VerificationMode from .logging import disable_progress_bar, enable_progress_bar, is_progress_bar_enabled from .version import Version from .experimental import experimental
701
"""simple docstring""" def snake_case__ ( _snake_case : int , _snake_case : int , _snake_case : int ): """simple docstring""" if exponent == 1: return base if exponent % 2 == 0: UpperCamelCase__ = _modexpt(_snake_case , exponent // 2 , _snake_case ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(_snake_case , exponent - 1 , _snake_case )) % modulo_value def snake_case__ ( _snake_case : int = 17_77 , _snake_case : int = 18_55 , _snake_case : int = 8 ): """simple docstring""" UpperCamelCase__ = base for _ in range(1 , _snake_case ): UpperCamelCase__ = _modexpt(_snake_case , _snake_case , 10**digits ) return result if __name__ == "__main__": print(F"{solution() = }")
304
0
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __snake_case ( UpperCamelCase_ ): _a = ['''image_processor''', '''tokenizer'''] _a = '''ViltImageProcessor''' _a = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self : Optional[Any] , A_ : str=None , A_ : Any=None , **A_ : Dict): lowerCAmelCase_ : Optional[int] = 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_ , ) lowerCAmelCase_ : Optional[int] = kwargs.pop('''feature_extractor''') lowerCAmelCase_ : Optional[Any] = 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_) lowerCAmelCase_ : Any = self.image_processor def __call__( self : str , A_ : str , A_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , A_ : bool = True , A_ : Union[bool, str, PaddingStrategy] = False , A_ : Union[bool, str, TruncationStrategy] = None , A_ : Optional[int] = None , A_ : int = 0 , A_ : Optional[int] = None , A_ : Optional[bool] = None , A_ : Optional[bool] = None , A_ : bool = False , A_ : bool = False , A_ : bool = False , A_ : bool = False , A_ : bool = True , A_ : Optional[Union[str, TensorType]] = None , **A_ : Optional[Any] , ): lowerCAmelCase_ : List[str] = self.tokenizer( text=A_ , add_special_tokens=A_ , padding=A_ , truncation=A_ , max_length=A_ , stride=A_ , pad_to_multiple_of=A_ , return_token_type_ids=A_ , return_attention_mask=A_ , return_overflowing_tokens=A_ , return_special_tokens_mask=A_ , return_offsets_mapping=A_ , return_length=A_ , verbose=A_ , return_tensors=A_ , **A_ , ) # add pixel_values + pixel_mask lowerCAmelCase_ : List[Any] = self.image_processor(A_ , return_tensors=A_) encoding.update(A_) return encoding def UpperCAmelCase__ ( self : Tuple , *A_ : Union[str, Any] , **A_ : Any): return self.tokenizer.batch_decode(*A_ , **A_) def UpperCAmelCase__ ( self : Optional[Any] , *A_ : List[str] , **A_ : Union[str, Any]): return self.tokenizer.decode(*A_ , **A_) @property def UpperCAmelCase__ ( self : int): lowerCAmelCase_ : List[str] = self.tokenizer.model_input_names lowerCAmelCase_ : Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def UpperCAmelCase__ ( self : Union[str, Any]): 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 UpperCAmelCase__ ( self : Dict): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , A_ , ) return self.image_processor
171
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## A__ : List[str] = 16 A__ : Dict = 32 def UpperCamelCase( __UpperCamelCase : Accelerator ,__UpperCamelCase : int = 16 ): lowerCAmelCase_ : Union[str, Any] = AutoTokenizer.from_pretrained('''bert-base-cased''' ) lowerCAmelCase_ : int = load_dataset('''glue''' ,'''mrpc''' ) def tokenize_function(__UpperCamelCase : Optional[Any] ): # max_length=None => use the model max length (it's actually the default) lowerCAmelCase_ : Tuple = tokenizer(examples['''sentence1'''] ,examples['''sentence2'''] ,truncation=__UpperCamelCase ,max_length=__UpperCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): lowerCAmelCase_ : str = datasets.map( __UpperCamelCase ,batched=__UpperCamelCase ,remove_columns=['''idx''', '''sentence1''', '''sentence2'''] ,) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCAmelCase_ : Any = tokenized_datasets.rename_column('''label''' ,'''labels''' ) def collate_fn(__UpperCamelCase : Dict ): # On TPU it's best to pad everything to the same length or training will be very slow. lowerCAmelCase_ : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": lowerCAmelCase_ : Optional[int] = 16 elif accelerator.mixed_precision != "no": lowerCAmelCase_ : Optional[int] = 8 else: lowerCAmelCase_ : Optional[int] = None return tokenizer.pad( __UpperCamelCase ,padding='''longest''' ,max_length=__UpperCamelCase ,pad_to_multiple_of=__UpperCamelCase ,return_tensors='''pt''' ,) # Instantiate dataloaders. lowerCAmelCase_ : Tuple = DataLoader( tokenized_datasets['''train'''] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) lowerCAmelCase_ : List[Any] = DataLoader( tokenized_datasets['''validation'''] ,shuffle=__UpperCamelCase ,collate_fn=__UpperCamelCase ,batch_size=__UpperCamelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders A__ : Any = mocked_dataloaders # noqa: F811 def UpperCamelCase( __UpperCamelCase : Union[str, Any] ,__UpperCamelCase : str ): # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''' ,__UpperCamelCase ) == "1": lowerCAmelCase_ : Dict = 2 # New Code # lowerCAmelCase_ : List[str] = int(args.gradient_accumulation_steps ) lowerCAmelCase_ : Union[str, Any] = int(args.local_sgd_steps ) # Initialize accelerator lowerCAmelCase_ : Optional[Any] = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,gradient_accumulation_steps=__UpperCamelCase ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError('''LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)''' ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCAmelCase_ : List[Any] = config['''lr'''] lowerCAmelCase_ : List[Any] = int(config['''num_epochs'''] ) lowerCAmelCase_ : int = int(config['''seed'''] ) lowerCAmelCase_ : Optional[Any] = int(config['''batch_size'''] ) lowerCAmelCase_ : Optional[Any] = evaluate.load('''glue''' ,'''mrpc''' ) set_seed(__UpperCamelCase ) lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = get_dataloaders(__UpperCamelCase ,__UpperCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCAmelCase_ : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' ,return_dict=__UpperCamelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). lowerCAmelCase_ : Optional[int] = model.to(accelerator.device ) # Instantiate optimizer lowerCAmelCase_ : Tuple = AdamW(params=model.parameters() ,lr=__UpperCamelCase ) # Instantiate scheduler lowerCAmelCase_ : Any = get_linear_schedule_with_warmup( optimizer=__UpperCamelCase ,num_warmup_steps=100 ,num_training_steps=(len(__UpperCamelCase ) * num_epochs) ,) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : Union[str, Any] = accelerator.prepare( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # Now we train the model for epoch in range(__UpperCamelCase ): model.train() with LocalSGD( accelerator=__UpperCamelCase ,model=__UpperCamelCase ,local_sgd_steps=__UpperCamelCase ,enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(__UpperCamelCase ): lowerCAmelCase_ : str = model(**__UpperCamelCase ) lowerCAmelCase_ : Tuple = output.loss accelerator.backward(__UpperCamelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(__UpperCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCAmelCase_ : List[str] = model(**__UpperCamelCase ) lowerCAmelCase_ : int = outputs.logits.argmax(dim=-1 ) lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=__UpperCamelCase ,references=__UpperCamelCase ,) lowerCAmelCase_ : Optional[int] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" ,__UpperCamelCase ) def UpperCamelCase( ): lowerCAmelCase_ : Any = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' ,type=__UpperCamelCase ,default=__UpperCamelCase ,choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] ,help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' ,) # New Code # parser.add_argument( '''--gradient_accumulation_steps''' ,type=__UpperCamelCase ,default=1 ,help='''The number of minibatches to be ran before gradients are accumulated.''' ,) parser.add_argument( '''--local_sgd_steps''' ,type=__UpperCamelCase ,default=8 ,help='''Number of local SGD steps or None to disable local SGD''' ) parser.add_argument('''--cpu''' ,action='''store_true''' ,help='''If passed, will train on the CPU.''' ) lowerCAmelCase_ : List[Any] = parser.parse_args() lowerCAmelCase_ : List[Any] = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(__UpperCamelCase ,__UpperCamelCase ) if __name__ == "__main__": main()
171
1
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP 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 from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class UpperCAmelCase__ ( snake_case , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ : Any = KandinskyInpaintPipeline lowerCAmelCase__ : List[str] = ['prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image'] lowerCAmelCase__ : str = [ 'prompt', 'negative_prompt', 'image_embeds', 'negative_image_embeds', 'image', 'mask_image', ] lowerCAmelCase__ : List[Any] = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'negative_prompt', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] lowerCAmelCase__ : int = False @property def _UpperCAmelCase ( self: Union[str, Any] ) -> Any: '''simple docstring''' return 32 @property def _UpperCAmelCase ( self: int ) -> Any: '''simple docstring''' return 32 @property def _UpperCAmelCase ( self: Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim @property def _UpperCAmelCase ( self: Optional[int] ) -> Any: '''simple docstring''' return self.time_input_dim * 4 @property def _UpperCAmelCase ( self: List[str] ) -> Any: '''simple docstring''' return 100 @property def _UpperCAmelCase ( self: Optional[Any] ) -> Tuple: '''simple docstring''' __UpperCAmelCase = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def _UpperCAmelCase ( self: Optional[int] ) -> Tuple: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_005 , ) __UpperCAmelCase = MultilingualCLIP(__lowerCAmelCase ) __UpperCAmelCase = text_encoder.eval() return text_encoder @property def _UpperCAmelCase ( self: List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase = { "in_channels": 9, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "text_image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "text_image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } __UpperCAmelCase = UNetaDConditionModel(**__lowerCAmelCase ) return model @property def _UpperCAmelCase ( self: Union[str, Any] ) -> Optional[int]: '''simple docstring''' return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _UpperCAmelCase ( self: Optional[int] ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase = VQModel(**self.dummy_movq_kwargs ) return model def _UpperCAmelCase ( self: int ) -> Dict: '''simple docstring''' __UpperCAmelCase = self.dummy_text_encoder __UpperCAmelCase = self.dummy_tokenizer __UpperCAmelCase = self.dummy_unet __UpperCAmelCase = self.dummy_movq __UpperCAmelCase = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="linear" , beta_start=0.00085 , beta_end=0.012 , clip_sample=__lowerCAmelCase , set_alpha_to_one=__lowerCAmelCase , steps_offset=1 , prediction_type="epsilon" , thresholding=__lowerCAmelCase , ) __UpperCAmelCase = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def _UpperCAmelCase ( self: Optional[int] , __lowerCAmelCase: List[str] , __lowerCAmelCase: Optional[int]=0 ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(__lowerCAmelCase ) ).to(__lowerCAmelCase ) __UpperCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(__lowerCAmelCase ) # create init_image __UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCAmelCase ) ).to(__lowerCAmelCase ) __UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __UpperCAmelCase = Image.fromarray(np.uinta(__lowerCAmelCase ) ).convert("RGB" ).resize((256, 256) ) # create mask __UpperCAmelCase = np.ones((64, 64) , dtype=np.floataa ) __UpperCAmelCase = 0 if str(__lowerCAmelCase ).startswith("mps" ): __UpperCAmelCase = torch.manual_seed(__lowerCAmelCase ) else: __UpperCAmelCase = torch.Generator(device=__lowerCAmelCase ).manual_seed(__lowerCAmelCase ) __UpperCAmelCase = { "prompt": "horse", "image": init_image, "mask_image": mask, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 2, "guidance_scale": 4.0, "output_type": "np", } return inputs def _UpperCAmelCase ( self: Optional[int] ) -> Tuple: '''simple docstring''' __UpperCAmelCase = "cpu" __UpperCAmelCase = self.get_dummy_components() __UpperCAmelCase = self.pipeline_class(**__lowerCAmelCase ) __UpperCAmelCase = pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) __UpperCAmelCase = pipe(**self.get_dummy_inputs(__lowerCAmelCase ) ) __UpperCAmelCase = output.images __UpperCAmelCase = pipe( **self.get_dummy_inputs(__lowerCAmelCase ) , return_dict=__lowerCAmelCase , )[0] __UpperCAmelCase = image[0, -3:, -3:, -1] __UpperCAmelCase = image_from_tuple[0, -3:, -3:, -1] print(F'''image.shape {image.shape}''' ) assert image.shape == (1, 64, 64, 3) __UpperCAmelCase = np.array( [0.8326919, 0.73790467, 0.20918581, 0.9309612, 0.5511791, 0.43713328, 0.5513321, 0.49922934, 0.59497786] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' def _UpperCAmelCase ( self: List[str] ) -> Optional[int]: '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCAmelCase ( self: str ) -> Any: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCAmelCase ( self: Dict ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy" ) __UpperCAmelCase = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) __UpperCAmelCase = np.ones((768, 768) , dtype=np.floataa ) __UpperCAmelCase = 0 __UpperCAmelCase = "a hat" __UpperCAmelCase = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(__lowerCAmelCase ) __UpperCAmelCase = KandinskyInpaintPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-inpaint" , torch_dtype=torch.floataa ) __UpperCAmelCase = pipeline.to(__lowerCAmelCase ) pipeline.set_progress_bar_config(disable=__lowerCAmelCase ) __UpperCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __UpperCAmelCase , __UpperCAmelCase = pipe_prior( __lowerCAmelCase , generator=__lowerCAmelCase , num_inference_steps=5 , negative_prompt="" , ).to_tuple() __UpperCAmelCase = pipeline( __lowerCAmelCase , image=__lowerCAmelCase , mask_image=__lowerCAmelCase , image_embeds=__lowerCAmelCase , negative_image_embeds=__lowerCAmelCase , generator=__lowerCAmelCase , num_inference_steps=100 , height=768 , width=768 , output_type="np" , ) __UpperCAmelCase = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__lowerCAmelCase , __lowerCAmelCase )
286
import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class UpperCAmelCase__ ( snake_case , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ : int = DiTPipeline lowerCAmelCase__ : Any = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS lowerCAmelCase__ : Optional[Any] = PipelineTesterMixin.required_optional_params - { 'latents', 'num_images_per_prompt', 'callback', 'callback_steps', } lowerCAmelCase__ : List[Any] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS lowerCAmelCase__ : Optional[int] = False def _UpperCAmelCase ( self: str ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) __UpperCAmelCase = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=__lowerCAmelCase , activation_fn="gelu-approximate" , num_embeds_ada_norm=1_000 , norm_type="ada_norm_zero" , norm_elementwise_affine=__lowerCAmelCase , ) __UpperCAmelCase = AutoencoderKL() __UpperCAmelCase = DDIMScheduler() __UpperCAmelCase = {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler} return components def _UpperCAmelCase ( self: str , __lowerCAmelCase: str , __lowerCAmelCase: Optional[int]=0 ) -> int: '''simple docstring''' if str(__lowerCAmelCase ).startswith("mps" ): __UpperCAmelCase = torch.manual_seed(__lowerCAmelCase ) else: __UpperCAmelCase = torch.Generator(device=__lowerCAmelCase ).manual_seed(__lowerCAmelCase ) __UpperCAmelCase = { "class_labels": [1], "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def _UpperCAmelCase ( self: Tuple ) -> Dict: '''simple docstring''' __UpperCAmelCase = "cpu" __UpperCAmelCase = self.get_dummy_components() __UpperCAmelCase = self.pipeline_class(**__lowerCAmelCase ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) __UpperCAmelCase = self.get_dummy_inputs(__lowerCAmelCase ) __UpperCAmelCase = pipe(**__lowerCAmelCase ).images __UpperCAmelCase = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) __UpperCAmelCase = np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457] ) __UpperCAmelCase = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(__lowerCAmelCase , 1E-3 ) def _UpperCAmelCase ( self: int ) -> str: '''simple docstring''' self._test_inference_batch_single_identical(relax_max_difference=__lowerCAmelCase , expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _UpperCAmelCase ( self: Optional[int] ) -> str: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _UpperCAmelCase ( self: Any ) -> Optional[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCAmelCase ( self: Dict ) -> List[Any]: '''simple docstring''' __UpperCAmelCase = torch.manual_seed(0 ) __UpperCAmelCase = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256" ) pipe.to("cuda" ) __UpperCAmelCase = ["vase", "umbrella", "white shark", "white wolf"] __UpperCAmelCase = pipe.get_label_ids(__lowerCAmelCase ) __UpperCAmelCase = pipe(__lowerCAmelCase , generator=__lowerCAmelCase , num_inference_steps=40 , output_type="np" ).images for word, image in zip(__lowerCAmelCase , __lowerCAmelCase ): __UpperCAmelCase = load_numpy( F'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy''' ) assert np.abs((expected_image - image).max() ) < 1E-2 def _UpperCAmelCase ( self: Any ) -> List[str]: '''simple docstring''' __UpperCAmelCase = DiTPipeline.from_pretrained("facebook/DiT-XL-2-512" ) __UpperCAmelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("cuda" ) __UpperCAmelCase = ["vase", "umbrella"] __UpperCAmelCase = pipe.get_label_ids(__lowerCAmelCase ) __UpperCAmelCase = torch.manual_seed(0 ) __UpperCAmelCase = pipe(__lowerCAmelCase , generator=__lowerCAmelCase , num_inference_steps=25 , output_type="np" ).images for word, image in zip(__lowerCAmelCase , __lowerCAmelCase ): __UpperCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" F'''/dit/{word}_512.npy''' ) assert np.abs((expected_image - image).max() ) < 1E-1
286
1
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. __snake_case :Optional[Any] =abspath(join(dirname(__file__), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def lowerCamelCase_ ( lowerCAmelCase__ : Union[str, Any] ) -> Any: '''simple docstring''' config.addinivalue_line( 'markers' , 'is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested' ) config.addinivalue_line( 'markers' , 'is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested' ) config.addinivalue_line('markers' , 'is_pipeline_test: mark test to run only when pipelines are tested' ) config.addinivalue_line('markers' , 'is_staging_test: mark test to run only in the staging environment' ) config.addinivalue_line('markers' , 'accelerate_tests: mark test that require accelerate' ) config.addinivalue_line('markers' , 'tool_tests: mark the tool tests that are run on their specific schedule' ) def lowerCamelCase_ ( lowerCAmelCase__ : List[str] ) -> Any: '''simple docstring''' from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowerCAmelCase__ ) def lowerCamelCase_ ( lowerCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' from transformers.testing_utils import pytest_terminal_summary_main A = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(lowerCAmelCase__ , id=lowerCAmelCase__ ) def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Union[str, Any] ) -> List[Any]: '''simple docstring''' if exitstatus == 5: A = 0 # Doctest custom flag to ignore output. __snake_case :int =doctest.register_optionflag('IGNORE_RESULT') __snake_case :List[str] =doctest.OutputChecker class lowerCAmelCase__ ( _lowerCamelCase ): def __UpperCamelCase ( self : Tuple , __UpperCamelCase : List[str] , __UpperCamelCase : Optional[int] , __UpperCamelCase : str ) -> List[Any]: if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) __snake_case :str =CustomOutputChecker __snake_case :List[Any] =HfDoctestModule __snake_case :str =HfDocTestParser
106
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowercase ( lowercase__ ): lowercase = ['''image_processor''', '''tokenizer'''] lowercase = '''CLIPImageProcessor''' lowercase = ('''XLMRobertaTokenizer''', '''XLMRobertaTokenizerFast''') def __init__(self : Union[str, Any] ,SCREAMING_SNAKE_CASE_ : int=None ,SCREAMING_SNAKE_CASE_ : str=None ,**SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> int: """simple docstring""" lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' ,SCREAMING_SNAKE_CASE_ ,) lowerCAmelCase = kwargs.pop('''feature_extractor''' ) lowerCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) def __call__(self : Union[str, Any] ,SCREAMING_SNAKE_CASE_ : List[str]=None ,SCREAMING_SNAKE_CASE_ : Optional[int]=None ,SCREAMING_SNAKE_CASE_ : Union[str, Any]=None ,**SCREAMING_SNAKE_CASE_ : Any ) -> List[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: lowerCAmelCase = self.tokenizer(SCREAMING_SNAKE_CASE_ ,return_tensors=SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) if images is not None: lowerCAmelCase = self.image_processor(SCREAMING_SNAKE_CASE_ ,return_tensors=SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) if text is not None and images is not None: lowerCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**SCREAMING_SNAKE_CASE_ ) ,tensor_type=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : List[str] ,*SCREAMING_SNAKE_CASE_ : Union[str, Any] ,**SCREAMING_SNAKE_CASE_ : Tuple ) -> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : Union[str, Any] ,*SCREAMING_SNAKE_CASE_ : int ,**SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Any: """simple docstring""" return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) @property def UpperCAmelCase (self : List[Any] ) -> Dict: """simple docstring""" lowerCAmelCase = self.tokenizer.model_input_names lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
535
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class a ( __lowerCAmelCase ): """simple docstring""" lowerCamelCase :Union[str, Any] = '''gpt_neox''' def __init__( self , lowerCAmelCase_=5_04_32 , lowerCAmelCase_=61_44 , lowerCAmelCase_=44 , lowerCAmelCase_=64 , lowerCAmelCase_=2_45_76 , lowerCAmelCase_="gelu" , lowerCAmelCase_=0.25 , lowerCAmelCase_=1_00_00 , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.0 , lowerCAmelCase_=0.1 , lowerCAmelCase_=20_48 , lowerCAmelCase_=0.02 , lowerCAmelCase_=1E-5 , lowerCAmelCase_=True , lowerCAmelCase_=0 , lowerCAmelCase_=2 , lowerCAmelCase_=False , lowerCAmelCase_=True , lowerCAmelCase_=None , **lowerCAmelCase_ , ) -> Dict: super().__init__(bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , **lowerCAmelCase_ ) _A = vocab_size _A = max_position_embeddings _A = hidden_size _A = num_hidden_layers _A = num_attention_heads _A = intermediate_size _A = hidden_act _A = rotary_pct _A = rotary_emb_base _A = attention_dropout _A = hidden_dropout _A = classifier_dropout _A = initializer_range _A = layer_norm_eps _A = use_cache _A = tie_word_embeddings _A = use_parallel_residual _A = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( """The hidden size is not divisble by the number of attention heads! Make sure to update them!""" ) def UpperCAmelCase ( self ) -> Dict: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , lowerCAmelCase_ ) or len(self.rope_scaling ) != 2: raise ValueError( """`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, """ F'''got {self.rope_scaling}''' ) _A = self.rope_scaling.get("""type""" , lowerCAmelCase_ ) _A = self.rope_scaling.get("""factor""" , lowerCAmelCase_ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) or rope_scaling_factor <= 1.0: raise ValueError(F'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
83
from collections import defaultdict def snake_case ( snake_case__ :int) -> int: _A = 1 _A = True for v in tree[start]: if v not in visited: ret += dfs(snake_case__) if ret % 2 == 0: cuts.append(snake_case__) return ret def snake_case ( ) -> Any: dfs(1) if __name__ == "__main__": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 10, 9 _SCREAMING_SNAKE_CASE = defaultdict(list) _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
83
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] ): """simple docstring""" a_ : Optional[int] = (boundary[1] - boundary[0]) / steps a_ : Optional[Any] = boundary[0] a_ : Dict = boundary[1] a_ : Dict = make_points(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) a_ : Any = 0.0 y += (h / 2.0) * f(UpperCamelCase__ ) for i in x_i: # print(i) y += h * f(UpperCamelCase__ ) y += (h / 2.0) * f(UpperCamelCase__ ) return y def _SCREAMING_SNAKE_CASE ( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] ): """simple docstring""" a_ : str = a + h while x < (b - h): yield x a_ : Optional[Any] = x + h def _SCREAMING_SNAKE_CASE ( UpperCamelCase__ : str ): # enter your function here """simple docstring""" a_ : int = (x - 0) * (x - 0) return y def _SCREAMING_SNAKE_CASE ( ): """simple docstring""" a_ : Optional[int] = 0.0 # Lower bound of integration a_ : List[Any] = 1.0 # Upper bound of integration a_ : Union[str, Any] = 10.0 # define number of steps or resolution a_ : List[str] = [a, b] # define boundary of integration a_ : Optional[int] = method_a(UpperCamelCase__ , UpperCamelCase__ ) print(F"y = {y}" ) if __name__ == "__main__": main()
442
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer lowerCAmelCase_ : Optional[Any] = logging.get_logger(__name__) lowerCAmelCase_ : int = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} lowerCAmelCase_ : Union[str, Any] = { 'vocab_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/vocab.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/vocab.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/vocab.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json' ), }, 'merges_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/merges.txt', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/merges.txt', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/merges.txt', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt' ), }, 'tokenizer_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/tokenizer.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/tokenizer.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json', 'roberta-base-openai-detector': ( 'https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json' ), 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json' ), }, } lowerCAmelCase_ : Union[str, Any] = { 'roberta-base': 512, 'roberta-large': 512, 'roberta-large-mnli': 512, 'distilroberta-base': 512, 'roberta-base-openai-detector': 512, 'roberta-large-openai-detector': 512, } class SCREAMING_SNAKE_CASE ( snake_case_ ): __magic_name__ : int = VOCAB_FILES_NAMES __magic_name__ : List[str] = PRETRAINED_VOCAB_FILES_MAP __magic_name__ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ : List[str] = ['''input_ids''', '''attention_mask'''] __magic_name__ : Any = RobertaTokenizer def __init__( self : Any , lowercase__ : int=None , lowercase__ : Union[str, Any]=None , lowercase__ : List[Any]=None , lowercase__ : int="replace" , lowercase__ : Dict="<s>" , lowercase__ : int="</s>" , lowercase__ : Optional[Any]="</s>" , lowercase__ : List[Any]="<s>" , lowercase__ : Optional[int]="<unk>" , lowercase__ : Tuple="<pad>" , lowercase__ : Optional[Any]="<mask>" , lowercase__ : List[Any]=False , lowercase__ : Optional[Any]=True , **lowercase__ : List[str] , ): '''simple docstring''' super().__init__( lowercase__ , lowercase__ , tokenizer_file=lowercase__ , errors=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , sep_token=lowercase__ , cls_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , mask_token=lowercase__ , add_prefix_space=lowercase__ , trim_offsets=lowercase__ , **lowercase__ , ) a_ : Any = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , lowercase__ ) != add_prefix_space: a_ : List[Any] = getattr(lowercase__ , pre_tok_state.pop("""type""" ) ) a_ : Optional[Any] = add_prefix_space a_ : List[str] = pre_tok_class(**lowercase__ ) a_ : List[Any] = add_prefix_space a_ : Any = """post_processor""" a_ : Dict = getattr(self.backend_tokenizer , lowercase__ , lowercase__ ) if tokenizer_component_instance: a_ : Optional[Any] = 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: a_ : Dict = tuple(state["""sep"""] ) if "cls" in state: a_ : List[str] = tuple(state["""cls"""] ) a_ : str = False if state.get("""add_prefix_space""" , lowercase__ ) != add_prefix_space: a_ : Any = add_prefix_space a_ : List[str] = True if state.get("""trim_offsets""" , lowercase__ ) != trim_offsets: a_ : Optional[int] = trim_offsets a_ : Tuple = True if changes_to_apply: a_ : str = getattr(lowercase__ , state.pop("""type""" ) ) a_ : Union[str, Any] = component_class(**lowercase__ ) setattr(self.backend_tokenizer , lowercase__ , lowercase__ ) @property def lowercase_ ( self : List[str] ): '''simple docstring''' 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 lowercase_ ( self : Union[str, Any] , lowercase__ : Tuple ): '''simple docstring''' a_ : List[Any] = AddedToken(lowercase__ , lstrip=lowercase__ , rstrip=lowercase__ ) if isinstance(lowercase__ , lowercase__ ) else value a_ : Union[str, Any] = value def lowercase_ ( self : Union[str, Any] , *lowercase__ : Union[str, Any] , **lowercase__ : Union[str, Any] ): '''simple docstring''' a_ : Any = kwargs.get("""is_split_into_words""" , lowercase__ ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowercase__ , **lowercase__ ) def lowercase_ ( self : Dict , *lowercase__ : int , **lowercase__ : Dict ): '''simple docstring''' a_ : Any = kwargs.get("""is_split_into_words""" , lowercase__ ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*lowercase__ , **lowercase__ ) def lowercase_ ( self : Dict , lowercase__ : str , lowercase__ : Optional[str] = None ): '''simple docstring''' a_ : str = self._tokenizer.model.save(lowercase__ , name=lowercase__ ) return tuple(lowercase__ ) def lowercase_ ( self : Dict , lowercase__ : List[Any] , lowercase__ : int=None ): '''simple docstring''' a_ : int = [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 lowercase_ ( self : List[str] , lowercase__ : List[int] , lowercase__ : Optional[List[int]] = None ): '''simple docstring''' a_ : Optional[Any] = [self.sep_token_id] a_ : Optional[int] = [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]
442
1
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int _a = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class __A ( datasets.BuilderConfig ): '''simple docstring''' lowerCAmelCase_ = None def lowerCAmelCase__(__snake_case ,__snake_case ,) -> Any: '''simple docstring''' import pyspark def generate_fn(): lowerCamelCase__ = df.select('''*''' ,pyspark.sql.functions.spark_partition_id().alias('''part_id''' ) ) for partition_id in partition_order: lowerCamelCase__ = df_with_partition_id.select('''*''' ).where(F'part_id = {partition_id}' ).drop('''part_id''' ) lowerCamelCase__ = partition_df.collect() lowerCamelCase__ = 0 for row in rows: yield F'{partition_id}_{row_id}', row.asDict() row_id += 1 return generate_fn class __A ( _BaseExamplesIterable ): '''simple docstring''' def __init__( self , __lowerCAmelCase , __lowerCAmelCase=None , ): '''simple docstring''' lowerCamelCase__ = df lowerCamelCase__ = partition_order or range(self.df.rdd.getNumPartitions() ) lowerCamelCase__ = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ): '''simple docstring''' yield from self.generate_examples_fn() def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(__lowerCAmelCase ) return SparkExamplesIterable(self.df , partition_order=__lowerCAmelCase ) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = self.split_shard_indices_by_worker(__lowerCAmelCase , __lowerCAmelCase ) return SparkExamplesIterable(self.df , partition_order=__lowerCAmelCase ) @property def __lowerCamelCase ( self ): '''simple docstring''' return len(self.partition_order ) class __A ( datasets.DatasetBuilder ): '''simple docstring''' lowerCAmelCase_ = SparkConfig def __init__( self , __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = None , **__lowerCAmelCase , ): '''simple docstring''' import pyspark lowerCamelCase__ = pyspark.sql.SparkSession.builder.getOrCreate() lowerCamelCase__ = df lowerCamelCase__ = working_dir super().__init__( cache_dir=__lowerCAmelCase , config_name=str(self.df.semanticHash() ) , **__lowerCAmelCase , ) def __lowerCamelCase ( self ): '''simple docstring''' def create_cache_and_write_probe(__lowerCAmelCase ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=__lowerCAmelCase ) lowerCamelCase__ = os.path.join(self._cache_dir , '''fs_test''' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(__lowerCAmelCase , '''a''' ) return [probe_file] if self._spark.conf.get('''spark.master''' , '''''' ).startswith('''local''' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: lowerCamelCase__ = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(__lowerCAmelCase ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( '''When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir''' ) def __lowerCamelCase ( self ): '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' import pyspark def get_arrow_batch_size(__lowerCAmelCase ): for batch in it: yield pa.RecordBatch.from_pydict({'''batch_bytes''': [batch.nbytes]} ) lowerCamelCase__ = self.df.count() lowerCamelCase__ = df_num_rows if df_num_rows <= 1_0_0 else 1_0_0 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. lowerCamelCase__ = ( self.df.limit(__lowerCAmelCase ) .repartition(1 ) .mapInArrow(__lowerCAmelCase , '''batch_bytes: long''' ) .agg(pyspark.sql.functions.sum('''batch_bytes''' ).alias('''sample_bytes''' ) ) .collect()[0] .sample_bytes / sample_num_rows ) lowerCamelCase__ = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. lowerCamelCase__ = min(__lowerCAmelCase , int(approx_total_size / max_shard_size ) ) lowerCamelCase__ = self.df.repartition(__lowerCAmelCase ) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ): '''simple docstring''' import pyspark lowerCamelCase__ = ParquetWriter if file_format == '''parquet''' else ArrowWriter lowerCamelCase__ = os.path.join(self._working_dir , os.path.basename(__lowerCAmelCase ) ) if self._working_dir else fpath lowerCamelCase__ = file_format == '''parquet''' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. lowerCamelCase__ = self.config.features lowerCamelCase__ = self._writer_batch_size lowerCamelCase__ = self._fs.storage_options def write_arrow(__lowerCAmelCase ): # Within the same SparkContext, no two task attempts will share the same attempt ID. lowerCamelCase__ = pyspark.TaskContext().taskAttemptId() lowerCamelCase__ = next(__lowerCAmelCase , __lowerCAmelCase ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) lowerCamelCase__ = 0 lowerCamelCase__ = writer_class( features=__lowerCAmelCase , path=working_fpath.replace('''SSSSS''' , F'{shard_id:05d}' ).replace('''TTTTT''' , F'{task_id:05d}' ) , writer_batch_size=__lowerCAmelCase , storage_options=__lowerCAmelCase , embed_local_files=__lowerCAmelCase , ) lowerCamelCase__ = pa.Table.from_batches([first_batch] ) writer.write_table(__lowerCAmelCase ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: lowerCamelCase__ , lowerCamelCase__ = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) shard_id += 1 lowerCamelCase__ = writer_class( features=writer._features , path=working_fpath.replace('''SSSSS''' , F'{shard_id:05d}' ).replace('''TTTTT''' , F'{task_id:05d}' ) , writer_batch_size=__lowerCAmelCase , storage_options=__lowerCAmelCase , embed_local_files=__lowerCAmelCase , ) lowerCamelCase__ = pa.Table.from_batches([batch] ) writer.write_table(__lowerCAmelCase ) if writer._num_bytes > 0: lowerCamelCase__ , lowerCamelCase__ = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(__lowerCAmelCase ) ): lowerCamelCase__ = os.path.join(os.path.dirname(__lowerCAmelCase ) , os.path.basename(__lowerCAmelCase ) ) shutil.move(__lowerCAmelCase , __lowerCAmelCase ) lowerCamelCase__ = ( self.df.mapInArrow(__lowerCAmelCase , '''task_id: long, num_examples: long, num_bytes: long''' ) .groupBy('''task_id''' ) .agg( pyspark.sql.functions.sum('''num_examples''' ).alias('''total_num_examples''' ) , pyspark.sql.functions.sum('''num_bytes''' ).alias('''total_num_bytes''' ) , pyspark.sql.functions.count('''num_bytes''' ).alias('''num_shards''' ) , pyspark.sql.functions.collect_list('''num_examples''' ).alias('''shard_lengths''' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = "arrow" , __lowerCAmelCase = None , __lowerCAmelCase = None , **__lowerCAmelCase , ): '''simple docstring''' self._validate_cache_dir() lowerCamelCase__ = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(__lowerCAmelCase ) lowerCamelCase__ = not is_remote_filesystem(self._fs ) lowerCamelCase__ = os.path.join if is_local else posixpath.join lowerCamelCase__ = '''-TTTTT-SSSSS-of-NNNNN''' lowerCamelCase__ = F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}' lowerCamelCase__ = path_join(self._output_dir , __lowerCAmelCase ) lowerCamelCase__ = 0 lowerCamelCase__ = 0 lowerCamelCase__ = 0 lowerCamelCase__ = [] lowerCamelCase__ = [] for task_id, content in self._prepare_split_single(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(__lowerCAmelCase ) lowerCamelCase__ = total_num_examples lowerCamelCase__ = total_num_bytes # should rename everything at the end logger.debug(F'Renaming {total_shards} shards.' ) if total_shards > 1: lowerCamelCase__ = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. lowerCamelCase__ = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ): rename( __lowerCAmelCase , fpath.replace('''SSSSS''' , F'{shard_id:05d}' ).replace('''TTTTT''' , F'{task_id:05d}' ) , fpath.replace('''TTTTT-SSSSS''' , F'{global_shard_id:05d}' ).replace('''NNNNN''' , F'{total_shards:05d}' ) , ) lowerCamelCase__ = [] lowerCamelCase__ = 0 for i in range(len(__lowerCAmelCase ) ): lowerCamelCase__ , lowerCamelCase__ = task_id_and_num_shards[i] for shard_id in range(__lowerCAmelCase ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(__lowerCAmelCase , len(__lowerCAmelCase ) ).map(lambda __lowerCAmelCase : _rename_shard(*__lowerCAmelCase ) ).collect() else: # don't use any pattern lowerCamelCase__ = 0 lowerCamelCase__ = task_id_and_num_shards[0][0] self._rename( fpath.replace('''SSSSS''' , F'{shard_id:05d}' ).replace('''TTTTT''' , F'{task_id:05d}' ) , fpath.replace(__lowerCAmelCase , '''''' ) , ) def __lowerCamelCase ( self , __lowerCAmelCase , ): '''simple docstring''' return SparkExamplesIterable(self.df )
29
from __future__ import annotations def lowerCAmelCase__(__snake_case ,__snake_case = None ,__snake_case = None ) -> None: '''simple docstring''' if start is None: lowerCamelCase__ = 0 if end is None: lowerCamelCase__ = len(__snake_case ) - 1 if start >= end: return lowerCamelCase__ = (start + end) // 2 slowsort(__snake_case ,__snake_case ,__snake_case ) slowsort(__snake_case ,mid + 1 ,__snake_case ) if sequence[end] < sequence[mid]: lowerCamelCase__ , lowerCamelCase__ = sequence[mid], sequence[end] slowsort(__snake_case ,__snake_case ,end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
29
1
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def __UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None ) -> List[str]: """simple docstring""" if attention_mask is None: __snake_case = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class __magic_name__ : _SCREAMING_SNAKE_CASE : List[str] = OPTConfig _SCREAMING_SNAKE_CASE : Union[str, Any] = {} _SCREAMING_SNAKE_CASE : List[Any] = 'gelu' def __init__( self : List[Any] , snake_case_ : List[Any] , snake_case_ : Dict=13 , snake_case_ : Optional[Any]=7 , snake_case_ : str=True , snake_case_ : Any=False , snake_case_ : int=99 , snake_case_ : Optional[int]=16 , snake_case_ : int=2 , snake_case_ : Dict=4 , snake_case_ : List[Any]=4 , snake_case_ : Union[str, Any]="gelu" , snake_case_ : Any=0.1 , snake_case_ : int=0.1 , snake_case_ : Optional[int]=20 , snake_case_ : int=2 , snake_case_ : Tuple=1 , snake_case_ : str=0 , snake_case_ : Dict=16 , snake_case_ : List[str]=16 , ): __snake_case = parent __snake_case = batch_size __snake_case = seq_length __snake_case = is_training __snake_case = use_labels __snake_case = vocab_size __snake_case = hidden_size __snake_case = num_hidden_layers __snake_case = num_attention_heads __snake_case = intermediate_size __snake_case = hidden_act __snake_case = hidden_dropout_prob __snake_case = attention_probs_dropout_prob __snake_case = max_position_embeddings __snake_case = eos_token_id __snake_case = pad_token_id __snake_case = bos_token_id __snake_case = embed_dim __snake_case = word_embed_proj_dim __snake_case = False def lowerCAmelCase ( self : List[str] ): __snake_case = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __snake_case = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __snake_case = tf.concat([input_ids, eos_tensor] , axis=1 ) __snake_case = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=snake_case_ , **self.config_updates , ) __snake_case = prepare_opt_inputs_dict(snake_case_ , snake_case_ ) return config, inputs_dict def lowerCAmelCase ( self : Optional[int] , snake_case_ : Any , snake_case_ : Optional[int] ): __snake_case = TFOPTModel(config=snake_case_ ) __snake_case = inputs_dict["input_ids"] __snake_case = input_ids[:1, :] __snake_case = inputs_dict["attention_mask"][:1, :] __snake_case = 1 # first forward pass __snake_case = model(snake_case_ , attention_mask=snake_case_ , use_cache=snake_case_ ) __snake_case , __snake_case = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __snake_case = ids_tensor((self.batch_size, 3) , config.vocab_size ) __snake_case = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __snake_case = tf.concat([input_ids, next_tokens] , axis=-1 ) __snake_case = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __snake_case = model(snake_case_ , attention_mask=snake_case_ )[0] __snake_case = model(snake_case_ , attention_mask=snake_case_ , past_key_values=snake_case_ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __snake_case = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __snake_case = output_from_no_past[:, -3:, random_slice_idx] __snake_case = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(snake_case_ , snake_case_ , rtol=1e-3 ) @require_tf class __magic_name__ ( lowercase__ , lowercase__ , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Tuple = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () _SCREAMING_SNAKE_CASE : Tuple = (TFOPTForCausalLM,) if is_tf_available() else () _SCREAMING_SNAKE_CASE : List[str] = ( {'feature-extraction': TFOPTModel, 'text-generation': TFOPTForCausalLM} if is_tf_available() else {} ) _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : List[str] = False _SCREAMING_SNAKE_CASE : List[Any] = False _SCREAMING_SNAKE_CASE : Union[str, Any] = 10 def lowerCAmelCase ( self : Optional[int] ): __snake_case = TFOPTModelTester(self ) __snake_case = ConfigTester(self , config_class=snake_case_ ) def lowerCAmelCase ( self : Tuple ): self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[Any] ): __snake_case = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*snake_case_ ) def lowerCAmelCase ( self : Tuple ): __snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(snake_case_ : Optional[Any] , snake_case_ : Optional[int] ): if hasattr(snake_case_ , "weight" ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(snake_case_ , "weight" ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 10, config.vocab_size + 10]: # build the embeddings __snake_case = model_class(config=snake_case_ ) __snake_case = _get_word_embedding_weight(snake_case_ , model.get_input_embeddings() ) __snake_case = _get_word_embedding_weight(snake_case_ , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(snake_case_ ) __snake_case = _get_word_embedding_weight(snake_case_ , model.get_input_embeddings() ) __snake_case = _get_word_embedding_weight(snake_case_ , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. __snake_case = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , snake_case_ ) # check that weights remain the same after resizing __snake_case = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: __snake_case = False self.assertTrue(snake_case_ ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , snake_case_ ) __snake_case = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: __snake_case = False self.assertTrue(snake_case_ ) def __UpperCamelCase ( SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" return tf.constant(SCREAMING_SNAKE_CASE , dtype=tf.intaa ) @require_tf class __magic_name__ ( unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[Any] = 99 def lowerCAmelCase ( self : Union[str, Any] ): __snake_case = tf.ones((4, 1) , dtype=tf.intaa ) * 2 __snake_case = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) __snake_case = input_ids.shape[0] __snake_case = OPTConfig( vocab_size=self.vocab_size , hidden_size=24 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class __magic_name__ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : Dict ): __snake_case = TFOPTModel.from_pretrained("facebook/opt-350m" ) __snake_case = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) __snake_case = tf.not_equal(snake_case_ , model.config.pad_token_id ) with tf.GradientTape(): __snake_case = model(input_ids=snake_case_ , attention_mask=snake_case_ ).last_hidden_state __snake_case = (1, 11, 512) self.assertEqual(output.shape , snake_case_ ) __snake_case = tf.constant( [[-0.2873, -1.9218, -0.3033], [-1.2710, -0.1338, -0.1902], [0.4095, 0.1214, -1.3121]] ) self.assertTrue(np.allclose(output[:, :3, :3] , snake_case_ , atol=4e-3 ) ) __snake_case = tf.function(snake_case_ , jit_compile=snake_case_ ) __snake_case = xla_generate(snake_case_ , snake_case_ )[0] self.assertTrue(np.allclose(output[:, :3, :3] , snake_case_ , atol=4e-2 ) ) @require_tf @slow class __magic_name__ ( unittest.TestCase ): def lowerCAmelCase ( self : List[str] ): super().setUp() __snake_case = "facebook/opt-350m" def lowerCAmelCase ( self : Any ): __snake_case = TFOPTForCausalLM.from_pretrained(self.path_model ) __snake_case = GPTaTokenizer.from_pretrained(self.path_model ) __snake_case = [ "Today is a beautiful day and I want to", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False __snake_case = tokenizer(snake_case_ , return_tensors="tf" , padding=snake_case_ , add_special_tokens=snake_case_ ) __snake_case = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) __snake_case = tf.constant( [ [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670], [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822], [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703], [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477], ] ) self.assertTrue(np.allclose(snake_case_ , snake_case_ , atol=1e-4 ) ) __snake_case = tf.function(snake_case_ , jit_compile=snake_case_ ) __snake_case = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(snake_case_ , snake_case_ , atol=1e-4 ) ) @require_tf @slow class __magic_name__ ( unittest.TestCase ): @property def lowerCAmelCase ( self : Any ): return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def lowerCAmelCase ( self : List[str] ): __snake_case = "facebook/opt-125m" __snake_case = [ "Today is a beautiful day and I want to", "In the city of New York, the city", "Paris is the capital of France and the capital", "Computers and mobile phones have taken over the", ] __snake_case = [] __snake_case = GPTaTokenizer.from_pretrained(snake_case_ ) __snake_case = TFOPTForCausalLM.from_pretrained(snake_case_ ) for prompt in self.prompts: __snake_case = tokenizer(snake_case_ , return_tensors="tf" ).input_ids __snake_case = model.generate(snake_case_ , max_length=10 ) __snake_case = tokenizer.batch_decode(snake_case_ , skip_special_tokens=snake_case_ ) predicted_outputs += generated_string self.assertListEqual(snake_case_ , snake_case_ ) def lowerCAmelCase ( self : Dict ): __snake_case = "facebook/opt-350m" __snake_case = GPTaTokenizer.from_pretrained(snake_case_ ) __snake_case = TFOPTForCausalLM.from_pretrained(snake_case_ ) __snake_case = "left" # use different length sentences to test batching __snake_case = [ "Hello, my dog is a little", "Today, I", ] __snake_case = tokenizer(snake_case_ , return_tensors="tf" , padding=snake_case_ ) __snake_case = inputs["input_ids"] __snake_case = model.generate(input_ids=snake_case_ , attention_mask=inputs["attention_mask"] ) __snake_case = tokenizer(sentences[0] , return_tensors="tf" ).input_ids __snake_case = model.generate(input_ids=snake_case_ ) __snake_case = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs["attention_mask"][-1] , tf.intaa ) ) __snake_case = tokenizer(sentences[1] , return_tensors="tf" ).input_ids __snake_case = model.generate(input_ids=snake_case_ , max_length=model.config.max_length - num_paddings ) __snake_case = tokenizer.batch_decode(snake_case_ , skip_special_tokens=snake_case_ ) __snake_case = tokenizer.decode(output_non_padded[0] , skip_special_tokens=snake_case_ ) __snake_case = tokenizer.decode(output_padded[0] , skip_special_tokens=snake_case_ ) __snake_case = [ "Hello, my dog is a little bit of a dork.\nI'm a little bit", "Today, I was in the middle of a conversation with a friend about the", ] self.assertListEqual(snake_case_ , snake_case_ ) self.assertListEqual(snake_case_ , [non_padded_sentence, padded_sentence] ) def lowerCAmelCase ( self : int ): __snake_case = "facebook/opt-350m" __snake_case = [ "Today is a beautiful day and I want to", "In the city of San Francisco, the city", "Paris is the capital of France and the capital", "Computers and mobile phones have taken over the", ] __snake_case = [] __snake_case = GPTaTokenizer.from_pretrained(snake_case_ ) __snake_case = TFOPTForCausalLM.from_pretrained(snake_case_ ) for prompt in self.prompts: __snake_case = tokenizer(snake_case_ , return_tensors="tf" ).input_ids __snake_case = model.generate(snake_case_ , max_length=10 ) __snake_case = tokenizer.batch_decode(snake_case_ , skip_special_tokens=snake_case_ ) predicted_outputs += generated_string self.assertListEqual(snake_case_ , snake_case_ )
163
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) class __magic_name__ ( lowercase__ ): def __init__( self : str , *snake_case_ : Optional[Any] , **snake_case_ : int ): warnings.warn( "The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use SegformerImageProcessor instead." , snake_case_ , ) super().__init__(*snake_case_ , **snake_case_ )
163
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/config.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/config.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/config.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/config.json''', '''bert-base-multilingual-uncased''': '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json''', '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/config.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/config.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json''' ), '''bert-base-cased-finetuned-mrpc''': '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json''', '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json''', '''bert-base-german-dbmdz-uncased''': '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json''', '''cl-tohoku/bert-base-japanese''': '''https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json''', '''cl-tohoku/bert-base-japanese-whole-word-masking''': ( '''https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json''' ), '''cl-tohoku/bert-base-japanese-char''': ( '''https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json''' ), '''cl-tohoku/bert-base-japanese-char-whole-word-masking''': ( '''https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json''' ), '''wietsedv/bert-base-dutch-cased''': '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json''', # See all BERT models at https://huggingface.co/models?filter=bert } class __snake_case ( snake_case__ ): """simple docstring""" UpperCamelCase_ = 'bert' def __init__( self : List[str] ,lowerCAmelCase__ : List[Any]=3_05_22 ,lowerCAmelCase__ : List[str]=7_68 ,lowerCAmelCase__ : Optional[int]=12 ,lowerCAmelCase__ : List[Any]=12 ,lowerCAmelCase__ : int=30_72 ,lowerCAmelCase__ : List[Any]="gelu" ,lowerCAmelCase__ : Tuple=0.1 ,lowerCAmelCase__ : Tuple=0.1 ,lowerCAmelCase__ : List[str]=5_12 ,lowerCAmelCase__ : Optional[int]=2 ,lowerCAmelCase__ : Any=0.02 ,lowerCAmelCase__ : Union[str, Any]=1e-1_2 ,lowerCAmelCase__ : List[Any]=0 ,lowerCAmelCase__ : Any="absolute" ,lowerCAmelCase__ : Any=True ,lowerCAmelCase__ : Optional[int]=None ,**lowerCAmelCase__ : Optional[Any] ,) -> str: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ ,**lowerCAmelCase__ ) lowerCAmelCase_ : Any = vocab_size lowerCAmelCase_ : Optional[Any] = hidden_size lowerCAmelCase_ : Tuple = num_hidden_layers lowerCAmelCase_ : int = num_attention_heads lowerCAmelCase_ : str = hidden_act lowerCAmelCase_ : List[str] = intermediate_size lowerCAmelCase_ : Any = hidden_dropout_prob lowerCAmelCase_ : str = attention_probs_dropout_prob lowerCAmelCase_ : str = max_position_embeddings lowerCAmelCase_ : int = type_vocab_size lowerCAmelCase_ : str = initializer_range lowerCAmelCase_ : Optional[int] = layer_norm_eps lowerCAmelCase_ : Dict = position_embedding_type lowerCAmelCase_ : Optional[Any] = use_cache lowerCAmelCase_ : Tuple = classifier_dropout class __snake_case ( snake_case__ ): """simple docstring""" @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": lowerCAmelCase_ : Any = {0: "batch", 1: "choice", 2: "sequence"} else: lowerCAmelCase_ : Union[str, Any] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
683
from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time _lowercase = Lock() def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__): global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(snake_case__) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase_ : Optional[Any] = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase_ : Any = min(snake_case__ , snake_case__) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(snake_case__) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase_ : str = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase_ : Dict = max(snake_case__ , snake_case__) # after all swaps are performed, send the values back to main result_pipe[1].send(snake_case__) def UpperCamelCase ( snake_case__): lowerCAmelCase_ : Union[str, Any] = [] lowerCAmelCase_ : int = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe()) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase_ : Tuple = Pipe() lowerCAmelCase_ : Optional[int] = Pipe() process_array_.append( Process( target=snake_case__ , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , )) lowerCAmelCase_ : int = temp_rs lowerCAmelCase_ : List[Any] = temp_rr for i in range(1 , len(snake_case__) - 1): lowerCAmelCase_ : Dict = Pipe() lowerCAmelCase_ : List[str] = Pipe() process_array_.append( Process( target=snake_case__ , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , )) lowerCAmelCase_ : Dict = temp_rs lowerCAmelCase_ : Optional[Any] = temp_rr process_array_.append( Process( target=snake_case__ , args=( len(snake_case__) - 1, arr[len(snake_case__) - 1], temp_ls, None, temp_lr, None, result_pipe[len(snake_case__) - 1], ) , )) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(snake_case__)): lowerCAmelCase_ : Union[str, Any] = result_pipe[p][0].recv() process_array_[p].join() return arr def UpperCamelCase ( ): lowerCAmelCase_ : Optional[Any] = list(range(10 , 0 , -1)) print("Initial List") print(*snake_case__) lowerCAmelCase_ : Tuple = odd_even_transposition(snake_case__) print("Sorted List\n") print(*snake_case__) if __name__ == "__main__": main()
683
1
import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch __UpperCAmelCase = random.Random() def UpperCamelCase ( snake_case__ : List[str] , snake_case__ : Tuple=1.0 , snake_case__ : int=None , snake_case__ : Optional[Any]=None ) -> List[Any]: if rng is None: UpperCamelCase : Union[str, Any] = global_rng UpperCamelCase : Union[str, Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase_ ( unittest.TestCase ): def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=7, SCREAMING_SNAKE_CASE_=400, SCREAMING_SNAKE_CASE_=2000, SCREAMING_SNAKE_CASE_=10, SCREAMING_SNAKE_CASE_=160, SCREAMING_SNAKE_CASE_=8, SCREAMING_SNAKE_CASE_=0.0, SCREAMING_SNAKE_CASE_=4000, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=True, ) -> str: UpperCamelCase : Dict = parent UpperCamelCase : Optional[Any] = batch_size UpperCamelCase : Optional[int] = min_seq_length UpperCamelCase : Optional[Any] = max_seq_length UpperCamelCase : Union[str, Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCamelCase : Optional[int] = padding_value UpperCamelCase : Optional[Any] = sampling_rate UpperCamelCase : List[Any] = return_attention_mask UpperCamelCase : Union[str, Any] = do_normalize UpperCamelCase : Tuple = feature_size UpperCamelCase : Dict = chunk_length UpperCamelCase : Dict = hop_length def snake_case_ ( self ) -> List[Any]: return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def snake_case_ ( self, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=False ) -> Union[str, Any]: def _flatten(SCREAMING_SNAKE_CASE_ ): return list(itertools.chain(*SCREAMING_SNAKE_CASE_ ) ) if equal_length: UpperCamelCase : Optional[int] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size UpperCamelCase : Optional[Any] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: UpperCamelCase : Dict = [np.asarray(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase_ ( a__ , unittest.TestCase ): UpperCAmelCase__ : str = WhisperFeatureExtractor if is_speech_available() else None def snake_case_ ( self ) -> str: UpperCamelCase : int = WhisperFeatureExtractionTester(self ) def snake_case_ ( self ) -> Any: UpperCamelCase : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase : Union[str, Any] = feat_extract_first.save_pretrained(SCREAMING_SNAKE_CASE_ )[0] check_json_file_has_correct_format(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = self.feature_extraction_class.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = feat_extract_first.to_dict() UpperCamelCase : int = feat_extract_second.to_dict() UpperCamelCase : Union[str, Any] = feat_extract_first.mel_filters UpperCamelCase : Optional[Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Tuple: UpperCamelCase : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE_, 'feat_extract.json' ) feat_extract_first.to_json_file(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = self.feature_extraction_class.from_json_file(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = feat_extract_first.to_dict() UpperCamelCase : List[str] = feat_extract_second.to_dict() UpperCamelCase : int = feat_extract_first.mel_filters UpperCamelCase : Union[str, Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> List[str]: # Tests that all call wrap to encode_plus and batch_encode_plus UpperCamelCase : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCamelCase : Dict = [floats_list((1, x) )[0] for x in range(800, 1400, 200 )] UpperCamelCase : int = [np.asarray(SCREAMING_SNAKE_CASE_ ) for speech_input in speech_inputs] # Test feature size UpperCamelCase : List[Any] = feature_extractor(SCREAMING_SNAKE_CASE_, padding='max_length', return_tensors='np' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input UpperCamelCase : List[str] = feature_extractor(speech_inputs[0], return_tensors='np' ).input_features UpperCamelCase : Tuple = feature_extractor(np_speech_inputs[0], return_tensors='np' ).input_features self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, atol=1e-3 ) ) # Test batched UpperCamelCase : Optional[Any] = feature_extractor(SCREAMING_SNAKE_CASE_, return_tensors='np' ).input_features UpperCamelCase : List[str] = feature_extractor(SCREAMING_SNAKE_CASE_, return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCamelCase : Tuple = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCamelCase : Optional[Any] = np.asarray(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = feature_extractor(SCREAMING_SNAKE_CASE_, return_tensors='np' ).input_features UpperCamelCase : Optional[Any] = feature_extractor(SCREAMING_SNAKE_CASE_, return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, atol=1e-3 ) ) # Test truncation required UpperCamelCase : List[Any] = [floats_list((1, x) )[0] for x in range(200, (feature_extractor.n_samples + 500), 200 )] UpperCamelCase : List[str] = [np.asarray(SCREAMING_SNAKE_CASE_ ) for speech_input in speech_inputs] UpperCamelCase : List[str] = [x[: feature_extractor.n_samples] for x in speech_inputs] UpperCamelCase : Optional[int] = [np.asarray(SCREAMING_SNAKE_CASE_ ) for speech_input in speech_inputs_truncated] UpperCamelCase : List[str] = feature_extractor(SCREAMING_SNAKE_CASE_, return_tensors='np' ).input_features UpperCamelCase : Tuple = feature_extractor(SCREAMING_SNAKE_CASE_, return_tensors='np' ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, atol=1e-3 ) ) def snake_case_ ( self ) -> Dict: import torch UpperCamelCase : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : Optional[int] = np.random.rand(100, 32 ).astype(np.floataa ) UpperCamelCase : Optional[Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCamelCase : List[str] = feature_extractor.pad([{'input_features': inputs}], return_tensors='np' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) UpperCamelCase : List[Any] = feature_extractor.pad([{'input_features': inputs}], return_tensors='pt' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> List[Any]: UpperCamelCase : List[Any] = load_dataset('hf-internal-testing/librispeech_asr_dummy', 'clean', split='validation' ) # automatic decoding with librispeech UpperCamelCase : Dict = ds.sort('id' ).select(range(SCREAMING_SNAKE_CASE_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def snake_case_ ( self ) -> int: # fmt: off UpperCamelCase : Dict = torch.tensor( [ 0.11_93, -0.09_46, -0.10_98, -0.01_96, 0.02_25, -0.06_90, -0.17_36, 0.09_51, 0.09_71, -0.08_17, -0.07_02, 0.01_62, 0.02_60, 0.00_17, -0.01_92, -0.16_78, 0.07_09, -0.18_67, -0.06_55, -0.02_74, -0.02_34, -0.18_84, -0.05_16, -0.05_54, -0.02_74, -0.14_25, -0.14_23, 0.08_37, 0.03_77, -0.08_54 ] ) # fmt: on UpperCamelCase : List[Any] = self._load_datasamples(1 ) UpperCamelCase : Dict = WhisperFeatureExtractor() UpperCamelCase : Any = feature_extractor(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).input_features self.assertEqual(input_features.shape, (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30], SCREAMING_SNAKE_CASE_, atol=1e-4 ) ) def snake_case_ ( self ) -> Union[str, Any]: UpperCamelCase : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCamelCase : str = self._load_datasamples(1 )[0] UpperCamelCase : Optional[Any] = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue UpperCamelCase : Any = feat_extract.zero_mean_unit_var_norm([audio], attention_mask=SCREAMING_SNAKE_CASE_ )[0] self.assertTrue(np.all(np.mean(SCREAMING_SNAKE_CASE_ ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(SCREAMING_SNAKE_CASE_ ) - 1 ) < 1e-3 ) )
40
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class a__ : def __init__( self , A = None ) -> None: '''simple docstring''' if components is None: a = [] a = list(A ) def __len__( self ) -> int: '''simple docstring''' return len(self.__components ) def __str__( self ) -> str: '''simple docstring''' return "(" + ",".join(map(A , self.__components ) ) + ")" def __add__( self , A ) -> Vector: '''simple docstring''' a = len(self ) if size == len(A ): a = [self.__components[i] + other.component(A ) for i in range(A )] return Vector(A ) else: raise Exception("must have the same size" ) def __sub__( self , A ) -> Vector: '''simple docstring''' a = len(self ) if size == len(A ): a = [self.__components[i] - other.component(A ) for i in range(A )] return Vector(A ) else: # error case raise Exception("must have the same size" ) @overload def __mul__( self , A ) -> Vector: '''simple docstring''' ... @overload def __mul__( self , A ) -> float: '''simple docstring''' ... def __mul__( self , A ) -> float | Vector: '''simple docstring''' if isinstance(A , (float, int) ): a = [c * other for c in self.__components] return Vector(A ) elif isinstance(A , A ) and len(self ) == len(A ): a = len(self ) a = [self.__components[i] * other.component(A ) for i in range(A )] return sum(A ) else: # error case raise Exception("invalid operand!" ) def lowerCAmelCase_ ( self ) -> Vector: '''simple docstring''' return Vector(self.__components ) def lowerCAmelCase_ ( self , A ) -> float: '''simple docstring''' if isinstance(A , A ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception("index out of range" ) def lowerCAmelCase_ ( self , A , A ) -> None: '''simple docstring''' assert -len(self.__components ) <= pos < len(self.__components ) a = value def lowerCAmelCase_ ( self ) -> float: '''simple docstring''' if len(self.__components ) == 0: raise Exception("Vector is empty" ) a = [c**2 for c in self.__components] return math.sqrt(sum(A ) ) def lowerCAmelCase_ ( self , A , A = False ) -> float: '''simple docstring''' a = self * other a = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> Vector: assert isinstance(__UpperCamelCase , __UpperCamelCase) return Vector([0] * dimension) def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase) -> Vector: assert isinstance(__UpperCamelCase , __UpperCamelCase) and (isinstance(__UpperCamelCase , __UpperCamelCase)) a = [0] * dimension a = 1 return Vector(__UpperCamelCase) def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase) -> Vector: assert ( isinstance(__UpperCamelCase , __UpperCamelCase) and isinstance(__UpperCamelCase , __UpperCamelCase) and (isinstance(__UpperCamelCase , (int, float))) ) return x * scalar + y def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase) -> Vector: random.seed(__UpperCamelCase) a = [random.randint(__UpperCamelCase , __UpperCamelCase) for _ in range(__UpperCamelCase)] return Vector(__UpperCamelCase) class a__ : def __init__( self , A , A , A ) -> None: '''simple docstring''' a = matrix a = w a = h def __str__( self ) -> str: '''simple docstring''' a = "" for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , A ) -> Matrix: '''simple docstring''' if self.__width == other.width() and self.__height == other.height(): a = [] for i in range(self.__height ): a = [ self.__matrix[i][j] + other.component(A , A ) for j in range(self.__width ) ] matrix.append(A ) return Matrix(A , self.__width , self.__height ) else: raise Exception("matrix must have the same dimension!" ) def __sub__( self , A ) -> Matrix: '''simple docstring''' if self.__width == other.width() and self.__height == other.height(): a = [] for i in range(self.__height ): a = [ self.__matrix[i][j] - other.component(A , A ) for j in range(self.__width ) ] matrix.append(A ) return Matrix(A , self.__width , self.__height ) else: raise Exception("matrices must have the same dimension!" ) @overload def __mul__( self , A ) -> Matrix: '''simple docstring''' ... @overload def __mul__( self , A ) -> Vector: '''simple docstring''' ... def __mul__( self , A ) -> Vector | Matrix: '''simple docstring''' if isinstance(A , A ): # matrix-vector if len(A ) == self.__width: a = zero_vector(self.__height ) for i in range(self.__height ): a = [ self.__matrix[i][j] * other.component(A ) for j in range(self.__width ) ] ans.change_component(A , sum(A ) ) return ans else: raise Exception( "vector must have the same size as the " "number of columns of the matrix!" ) elif isinstance(A , (int, float) ): # matrix-scalar a = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(A , self.__width , self.__height ) return None def lowerCAmelCase_ ( self ) -> int: '''simple docstring''' return self.__height def lowerCAmelCase_ ( self ) -> int: '''simple docstring''' return self.__width def lowerCAmelCase_ ( self , A , A ) -> float: '''simple docstring''' if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("change_component: indices out of bounds" ) def lowerCAmelCase_ ( self , A , A , A ) -> None: '''simple docstring''' if 0 <= x < self.__height and 0 <= y < self.__width: a = value else: raise Exception("change_component: indices out of bounds" ) def lowerCAmelCase_ ( self , A , A ) -> float: '''simple docstring''' if self.__height != self.__width: raise Exception("Matrix is not square" ) a = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(A ) ): a = minor[i][:y] + minor[i][y + 1 :] return Matrix(A , self.__width - 1 , self.__height - 1 ).determinant() def lowerCAmelCase_ ( self , A , A ) -> float: '''simple docstring''' if self.__height != self.__width: raise Exception("Matrix is not square" ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(A , A ) else: raise Exception("Indices out of bounds" ) def lowerCAmelCase_ ( self ) -> float: '''simple docstring''' if self.__height != self.__width: raise Exception("Matrix is not square" ) if self.__height < 1: raise Exception("Matrix has no element" ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: a = [ self.__matrix[0][y] * self.cofactor(0 , A ) for y in range(self.__width ) ] return sum(A ) def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> Matrix: a = [[0] * n for _ in range(__UpperCamelCase)] return Matrix(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase) def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase) -> Matrix: random.seed(__UpperCamelCase) a = [ [random.randint(__UpperCamelCase , __UpperCamelCase) for _ in range(__UpperCamelCase)] for _ in range(__UpperCamelCase) ] return Matrix(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase)
515
0
import numpy as np def _A ( lowerCAmelCase_ : np.array ): """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
125
from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["input_features", "attention_mask"] def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Any=80 , SCREAMING_SNAKE_CASE__ : List[str]=16_000 , SCREAMING_SNAKE_CASE__ : Tuple=80 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : List[str]=True , **SCREAMING_SNAKE_CASE__ : int , ) -> List[str]: super().__init__(feature_size=SCREAMING_SNAKE_CASE__ , sampling_rate=SCREAMING_SNAKE_CASE__ , padding_value=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = num_mel_bins lowerCAmelCase__ = do_ceptral_normalize lowerCAmelCase__ = normalize_means lowerCAmelCase__ = normalize_vars lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , ) -> np.ndarray: lowerCAmelCase__ = waveform * (2**15) # Kaldi compliance: 16-bit signed integers lowerCAmelCase__ = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) lowerCAmelCase__ = ta_kaldi.fbank(SCREAMING_SNAKE_CASE__ , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def a ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[bool] = True , SCREAMING_SNAKE_CASE__ : Optional[bool] = True , SCREAMING_SNAKE_CASE__ : float = 0.0 , ) -> np.ndarray: # make sure we normalize float32 arrays if normalize_means: lowerCAmelCase__ = x[:input_length].mean(axis=0 ) lowerCAmelCase__ = np.subtract(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if normalize_vars: lowerCAmelCase__ = x[:input_length].std(axis=0 ) lowerCAmelCase__ = np.divide(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if input_length < x.shape[0]: lowerCAmelCase__ = padding_value # make sure array is in float32 lowerCAmelCase__ = x.astype(np.floataa ) return x def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[np.ndarray] , SCREAMING_SNAKE_CASE__ : Optional[np.ndarray] = None ) -> List[np.ndarray]: lowerCAmelCase__ = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ] def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> BatchFeature: if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( "It is strongly recommended to pass the `sampling_rate` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug." ) lowerCAmelCase__ = isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) lowerCAmelCase__ = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: lowerCAmelCase__ = [np.asarray(SCREAMING_SNAKE_CASE__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): lowerCAmelCase__ = np.asarray(SCREAMING_SNAKE_CASE__ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): lowerCAmelCase__ = raw_speech.astype(np.floataa ) # always return batch if not is_batched: lowerCAmelCase__ = [raw_speech] # extract fbank features lowerCAmelCase__ = [self._extract_fbank_features(SCREAMING_SNAKE_CASE__ ) for waveform in raw_speech] # convert into correct format for padding lowerCAmelCase__ = BatchFeature({"input_features": features} ) lowerCAmelCase__ = self.pad( SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) # make sure list is in array format lowerCAmelCase__ = padded_inputs.get("input_features" ) if isinstance(input_features[0] , SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = [np.asarray(SCREAMING_SNAKE_CASE__ , dtype=np.floataa ) for feature in input_features] lowerCAmelCase__ = padded_inputs.get("attention_mask" ) if attention_mask is not None: lowerCAmelCase__ = [np.asarray(SCREAMING_SNAKE_CASE__ , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: lowerCAmelCase__ = ( np.array(SCREAMING_SNAKE_CASE__ , dtype=np.intaa ) if self._get_padding_strategies(SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) is not PaddingStrategy.DO_NOT_PAD else None ) lowerCAmelCase__ = self.normalize( padded_inputs["input_features"] , attention_mask=SCREAMING_SNAKE_CASE__ ) if return_tensors is not None: lowerCAmelCase__ = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE__ ) return padded_inputs
125
1
'''simple docstring''' from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class UpperCAmelCase : def __init__( self , __A , ): __UpperCAmelCase = parent __UpperCAmelCase = 13 __UpperCAmelCase = 7 __UpperCAmelCase = 30 __UpperCAmelCase = self.seq_length + self.mem_len __UpperCAmelCase = 15 __UpperCAmelCase = True __UpperCAmelCase = True __UpperCAmelCase = 99 __UpperCAmelCase = [10, 50, 80] __UpperCAmelCase = 32 __UpperCAmelCase = 32 __UpperCAmelCase = 4 __UpperCAmelCase = 8 __UpperCAmelCase = 128 __UpperCAmelCase = 2 __UpperCAmelCase = 2 __UpperCAmelCase = None __UpperCAmelCase = 1 __UpperCAmelCase = 0 __UpperCAmelCase = 3 __UpperCAmelCase = self.vocab_size - 1 __UpperCAmelCase = 0.0_1 def __lowerCamelCase ( self ): __UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase = None if self.use_labels: __UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase = TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def __lowerCamelCase ( self ): random.seed(self.seed ) tf.random.set_seed(self.seed ) def __lowerCamelCase ( self , __A , __A , __A , __A ): __UpperCAmelCase = TFTransfoXLModel(__A ) __UpperCAmelCase , __UpperCAmelCase = model(__A ).to_tuple() __UpperCAmelCase = {'input_ids': input_ids_a, 'mems': mems_a} __UpperCAmelCase , __UpperCAmelCase = model(__A ).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def __lowerCamelCase ( self , __A , __A , __A , __A ): __UpperCAmelCase = TFTransfoXLLMHeadModel(__A ) __UpperCAmelCase , __UpperCAmelCase = model(__A ).to_tuple() __UpperCAmelCase = {'input_ids': input_ids_a, 'labels': lm_labels} __UpperCAmelCase , __UpperCAmelCase = model(__A ).to_tuple() __UpperCAmelCase , __UpperCAmelCase = model([input_ids_a, mems_a] ).to_tuple() __UpperCAmelCase = {'input_ids': input_ids_a, 'mems': mems_a, 'labels': lm_labels} __UpperCAmelCase , __UpperCAmelCase = model(__A ).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def __lowerCamelCase ( self , __A , __A , __A , __A ): __UpperCAmelCase = TFTransfoXLForSequenceClassification(__A ) __UpperCAmelCase = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self ): __UpperCAmelCase = self.prepare_config_and_inputs() ((__UpperCAmelCase) , (__UpperCAmelCase) , (__UpperCAmelCase) , (__UpperCAmelCase)) = config_and_inputs __UpperCAmelCase = {'input_ids': input_ids_a} return config, inputs_dict @require_tf class UpperCAmelCase ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): _A : Union[str, Any] = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) _A : Union[str, Any] = () if is_tf_available() else () _A : Union[str, Any] = ( { """feature-extraction""": TFTransfoXLModel, """text-classification""": TFTransfoXLForSequenceClassification, """text-generation""": TFTransfoXLLMHeadModel, """zero-shot""": TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented _A : str = False _A : Any = False _A : str = False _A : str = False def __lowerCamelCase ( self , __A , __A , __A , __A , __A ): if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def __lowerCamelCase ( self ): __UpperCAmelCase = TFTransfoXLModelTester(self ) __UpperCAmelCase = ConfigTester(self , config_class=__A , d_embed=37 ) def __lowerCamelCase ( self ): self.config_tester.run_common_tests() def __lowerCamelCase ( self ): self.model_tester.set_seed() __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*__A ) def __lowerCamelCase ( self ): self.model_tester.set_seed() __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*__A ) def __lowerCamelCase ( self ): __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*__A ) def __lowerCamelCase ( self ): __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: __UpperCAmelCase = model_class(__A ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: __UpperCAmelCase = model.get_output_embeddings() assert isinstance(__A , tf.keras.layers.Layer ) __UpperCAmelCase = model.get_bias() assert name is None else: __UpperCAmelCase = model.get_output_embeddings() assert x is None __UpperCAmelCase = model.get_bias() assert name is None def __lowerCamelCase ( self ): # TODO JP: Make TransfoXL XLA compliant pass @slow def __lowerCamelCase ( self ): for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase = TFTransfoXLModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @unittest.skip(reason='This model doesn\'t play well with fit() due to not returning a single loss.' ) def __lowerCamelCase ( self ): pass @require_tf class UpperCAmelCase ( unittest.TestCase ): @unittest.skip('Skip test until #12651 is resolved.' ) @slow def __lowerCamelCase ( self ): __UpperCAmelCase = TFTransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103' ) # fmt: off __UpperCAmelCase = tf.convert_to_tensor([[33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0]] , dtype=tf.intaa ) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off __UpperCAmelCase = [33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0,33,1,1_857,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,28,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> __UpperCAmelCase = model.generate(__A , max_length=200 , do_sample=__A ) self.assertListEqual(output_ids[0].numpy().tolist() , __A )
126
'''simple docstring''' import os from datetime import datetime as dt from github import Github _A: Any = [ """good first issue""", """feature request""", """wip""", ] def _lowerCAmelCase ( )-> Optional[int]: __UpperCAmelCase = Github(os.environ['GITHUB_TOKEN'] ) __UpperCAmelCase = g.get_repo('huggingface/accelerate' ) __UpperCAmelCase = repo.get_issues(state='open' ) for issue in open_issues: __UpperCAmelCase = sorted([comment for comment in issue.get_comments()] , key=lambda _lowerCAmelCase : i.created_at , reverse=_lowerCAmelCase ) __UpperCAmelCase = comments[0] if len(_lowerCAmelCase ) > 0 else None __UpperCAmelCase = dt.utcnow() __UpperCAmelCase = (current_time - issue.updated_at).days __UpperCAmelCase = (current_time - issue.created_at).days if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and days_since_updated > 7 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Close issue since it has been 7 days of inactivity since bot mention. issue.edit(state='closed' ) elif ( days_since_updated > 23 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Add stale comment issue.create_comment( 'This issue has been automatically marked as stale because it has not had ' 'recent activity. If you think this still needs to be addressed ' 'please comment on this thread.\n\nPlease note that issues that do not follow the ' '[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) ' 'are likely to be ignored.' ) if __name__ == "__main__": main()
126
1
from math import sqrt def __UpperCamelCase ( lowerCAmelCase__ : int ): __a : int = 0 for i in range(1 , int(sqrt(lowerCAmelCase__ ) + 1 ) ): if n % i == 0 and i != sqrt(lowerCAmelCase__ ): total += i + n // i elif i == sqrt(lowerCAmelCase__ ): total += i return total - n def __UpperCamelCase ( lowerCAmelCase__ : int = 1_0_0_0_0 ): __a : Union[str, Any] = sum( i for i in range(1 , lowerCAmelCase__ ) if sum_of_divisors(sum_of_divisors(lowerCAmelCase__ ) ) == i and sum_of_divisors(lowerCAmelCase__ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
326
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def __UpperCamelCase ( lowerCAmelCase__ : Any ): __a : Dict = filter(lambda lowerCAmelCase__ : p.requires_grad , model.parameters() ) __a : Tuple = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowercase__ =logging.getLogger(__name__) def __UpperCamelCase ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[Any] ): if metric == "rouge2": __a : List[Any] = '''{val_avg_rouge2:.4f}-{step_count}''' elif metric == "bleu": __a : List[str] = '''{val_avg_bleu:.4f}-{step_count}''' elif metric == "em": __a : Optional[Any] = '''{val_avg_em:.4f}-{step_count}''' else: raise NotImplementedError( f"seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this" ''' function.''' ) __a : List[Any] = ModelCheckpoint( dirpath=lowerCAmelCase__ , filename=lowerCAmelCase__ , monitor=f"val_{metric}" , mode='''max''' , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def __UpperCamelCase ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Union[str, Any] ): return EarlyStopping( monitor=f"val_{metric}" , mode='''min''' if '''loss''' in metric else '''max''' , patience=lowerCAmelCase__ , verbose=lowerCAmelCase__ , ) class UpperCamelCase__ ( pl.Callback ): def lowerCAmelCase (self : List[str] , snake_case_ : Any , snake_case_ : Any ): __a : Optional[int] = {f"lr_group_{i}": param['''lr'''] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(snake_case_ ) @rank_zero_only def lowerCAmelCase (self : str , snake_case_ : pl.Trainer , snake_case_ : pl.LightningModule , snake_case_ : str , snake_case_ : Dict=True ): logger.info(f"***** {type_path} results at step {trainer.global_step:05d} *****" ) __a : List[str] = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['''log''', '''progress_bar''', '''preds''']} ) # Log results __a : Union[str, Any] = Path(pl_module.hparams.output_dir ) if type_path == "test": __a : Union[str, Any] = od / '''test_results.txt''' __a : Optional[Any] = od / '''test_generations.txt''' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. __a : Optional[int] = od / f"{type_path}_results/{trainer.global_step:05d}.txt" __a : List[str] = od / f"{type_path}_generations/{trainer.global_step:05d}.txt" results_file.parent.mkdir(exist_ok=snake_case_ ) generations_file.parent.mkdir(exist_ok=snake_case_ ) with open(snake_case_ , '''a+''' ) as writer: for key in sorted(snake_case_ ): if key in ["log", "progress_bar", "preds"]: continue __a : Tuple = metrics[key] if isinstance(snake_case_ , torch.Tensor ): __a : Optional[int] = val.item() __a : List[str] = f"{key}: {val:.6f}\n" writer.write(snake_case_ ) if not save_generations: return if "preds" in metrics: __a : Optional[Any] = '''\n'''.join(metrics['''preds'''] ) generations_file.open('''w+''' ).write(snake_case_ ) @rank_zero_only def lowerCAmelCase (self : List[Any] , snake_case_ : Union[str, Any] , snake_case_ : Tuple ): try: __a : Union[str, Any] = pl_module.model.model.num_parameters() except AttributeError: __a : int = pl_module.model.num_parameters() __a : Any = count_trainable_parameters(snake_case_ ) # mp stands for million parameters trainer.logger.log_metrics({'''n_params''': npars, '''mp''': npars / 1E6, '''grad_mp''': n_trainable_pars / 1E6} ) @rank_zero_only def lowerCAmelCase (self : Optional[int] , snake_case_ : pl.Trainer , snake_case_ : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(snake_case_ , snake_case_ , '''test''' ) @rank_zero_only def lowerCAmelCase (self : Union[str, Any] , snake_case_ : pl.Trainer , snake_case_ : str ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
326
1
def UpperCamelCase_( _A :list )-> list: for i in range(len(_A ) - 1 , 0 , -1 ): UpperCamelCase__ = False for j in range(_A , 0 , -1 ): if unsorted[j] < unsorted[j - 1]: UpperCamelCase__, UpperCamelCase__ = unsorted[j - 1], unsorted[j] UpperCamelCase__ = True for j in range(_A ): if unsorted[j] > unsorted[j + 1]: UpperCamelCase__, UpperCamelCase__ = unsorted[j + 1], unsorted[j] UpperCamelCase__ = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() __UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() __UpperCamelCase = [int(item) for item in user_input.split(',')] print(f'''{cocktail_shaker_sort(unsorted) = }''')
551
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class lowerCamelCase__ ( UpperCAmelCase ): """simple docstring""" _UpperCamelCase : Tuple = CustomTokenizer pass
551
1
import math def __lowerCAmelCase ( _UpperCamelCase : int ) -> bool: '''simple docstring''' return math.sqrt(_UpperCamelCase ) * math.sqrt(_UpperCamelCase ) == num def __lowerCAmelCase ( _UpperCamelCase : int ) -> bool: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = n while left <= right: SCREAMING_SNAKE_CASE = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: SCREAMING_SNAKE_CASE = mid - 1 else: SCREAMING_SNAKE_CASE = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
714
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCamelCase ( SCREAMING_SNAKE_CASE ): __UpperCamelCase ="facebook/bart-large-mnli" __UpperCamelCase =( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) __UpperCamelCase ="text_classifier" __UpperCamelCase =AutoTokenizer __UpperCamelCase =AutoModelForSequenceClassification __UpperCamelCase =["text", ["text"]] __UpperCamelCase =["text"] def UpperCamelCase ( self : Optional[Any] ): """simple docstring""" super().setup() SCREAMING_SNAKE_CASE = self.model.config SCREAMING_SNAKE_CASE = -1 for idx, label in config.idalabel.items(): if label.lower().startswith('entail' ): SCREAMING_SNAKE_CASE = int(snake_case__ ) if self.entailment_id == -1: raise ValueError('Could not determine the entailment ID from the model config, please pass it at init.' ) def UpperCamelCase ( self : Optional[Any] , snake_case__ : List[str] , snake_case__ : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE = labels return self.pre_processor( [text] * len(snake_case__ ) , [F"""This example is {label}""" for label in labels] , return_tensors='pt' , padding='max_length' , ) def UpperCamelCase ( self : Dict , snake_case__ : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE = outputs.logits SCREAMING_SNAKE_CASE = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
673
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## UpperCamelCase__ =16 UpperCamelCase__ =32 def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase = 16 ): _SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained("bert-base-cased" ) _SCREAMING_SNAKE_CASE : str = load_dataset("glue", "mrpc" ) def tokenize_function(__lowerCamelCase ): # max_length=None => use the model max length (it's actually the default) _SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer(examples["sentence1"], examples["sentence2"], truncation=__lowerCamelCase, max_length=__lowerCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _SCREAMING_SNAKE_CASE : Tuple = datasets.map( __lowerCamelCase, batched=__lowerCamelCase, remove_columns=["idx", "sentence1", "sentence2"], ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _SCREAMING_SNAKE_CASE : List[str] = tokenized_datasets.rename_column("label", "labels" ) def collate_fn(__lowerCamelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. _SCREAMING_SNAKE_CASE : List[str] = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _SCREAMING_SNAKE_CASE : Dict = 16 elif accelerator.mixed_precision != "no": _SCREAMING_SNAKE_CASE : str = 8 else: _SCREAMING_SNAKE_CASE : Union[str, Any] = None return tokenizer.pad( __lowerCamelCase, padding="longest", max_length=__lowerCamelCase, pad_to_multiple_of=__lowerCamelCase, return_tensors="pt", ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE : Tuple = DataLoader( tokenized_datasets["train"], shuffle=__lowerCamelCase, collate_fn=__lowerCamelCase, batch_size=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[Any] = DataLoader( tokenized_datasets["validation"], shuffle=__lowerCamelCase, collate_fn=__lowerCamelCase, batch_size=__lowerCamelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders UpperCamelCase__ =mocked_dataloaders # noqa: F811 def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", __lowerCamelCase ) == "1": _SCREAMING_SNAKE_CASE : Optional[Any] = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: _SCREAMING_SNAKE_CASE : int = Accelerator( cpu=args.cpu, mixed_precision=args.mixed_precision, log_with="all", project_dir=args.project_dir ) else: _SCREAMING_SNAKE_CASE : Optional[Any] = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE : Optional[Any] = config["lr"] _SCREAMING_SNAKE_CASE : str = int(config["num_epochs"] ) _SCREAMING_SNAKE_CASE : int = int(config["seed"] ) _SCREAMING_SNAKE_CASE : Optional[Any] = int(config["batch_size"] ) set_seed(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = get_dataloaders(__lowerCamelCase, __lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = evaluate.load("glue", "mrpc" ) # If the batch size is too big we use gradient accumulation _SCREAMING_SNAKE_CASE : Optional[int] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _SCREAMING_SNAKE_CASE : Optional[int] = batch_size // MAX_GPU_BATCH_SIZE _SCREAMING_SNAKE_CASE : Dict = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=__lowerCamelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE : Tuple = model.to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE : List[str] = AdamW(params=model.parameters(), lr=__lowerCamelCase ) # Instantiate scheduler _SCREAMING_SNAKE_CASE : List[str] = get_linear_schedule_with_warmup( optimizer=__lowerCamelCase, num_warmup_steps=100, num_training_steps=(len(__lowerCamelCase ) * num_epochs) // gradient_accumulation_steps, ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = accelerator.prepare( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: _SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.split(__lowerCamelCase )[-1].split("." )[0] accelerator.init_trackers(__lowerCamelCase, __lowerCamelCase ) # Now we train the model for epoch in range(__lowerCamelCase ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: _SCREAMING_SNAKE_CASE : List[Any] = 0 for step, batch in enumerate(__lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _SCREAMING_SNAKE_CASE : Tuple = model(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() _SCREAMING_SNAKE_CASE : Any = loss / gradient_accumulation_steps accelerator.backward(__lowerCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE : Optional[Any] = model(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.logits.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=__lowerCamelCase, references=__lowerCamelCase, ) _SCREAMING_SNAKE_CASE : List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""", __lowerCamelCase ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { "accuracy": eval_metric["accuracy"], "f1": eval_metric["f1"], "train_loss": total_loss.item() / len(__lowerCamelCase ), "epoch": epoch, }, step=__lowerCamelCase, ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def lowerCamelCase__ (): _SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision", type=__lowerCamelCase, default=__lowerCamelCase, choices=["no", "fp16", "bf16", "fp8"], help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU.", ) parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU." ) parser.add_argument( "--with_tracking", action="store_true", help="Whether to load in all available experiment trackers from the environment and use them for logging.", ) parser.add_argument( "--project_dir", type=__lowerCamelCase, default="logs", help="Location on where to store experiment tracking logs` and relevent project information", ) _SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() _SCREAMING_SNAKE_CASE : List[str] = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(__lowerCamelCase, __lowerCamelCase ) if __name__ == "__main__": main()
249
"""simple docstring""" import sys __lowercase : Union[str, Any] = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def SCREAMING_SNAKE_CASE ( snake_case): __snake_case = 1 for digit in s: product *= int(snake_case) return product def SCREAMING_SNAKE_CASE ( snake_case = N): __snake_case = -sys.maxsize - 1 __snake_case = n[:13] __snake_case = 13 while cur_index < len(snake_case) - 13: if int(n[cur_index]) >= int(substr[0]): __snake_case = substr[1:] + n[cur_index] cur_index += 1 else: __snake_case = max(snake_case, str_eval(snake_case)) __snake_case = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(F"""{solution() = }""")
564
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Any = {'''vocab_file''': '''vocab.txt'''} _SCREAMING_SNAKE_CASE : Union[str, Any] = { '''vocab_file''': { '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt''', } } _SCREAMING_SNAKE_CASE : int = { '''YituTech/conv-bert-base''': 512, '''YituTech/conv-bert-medium-small''': 512, '''YituTech/conv-bert-small''': 512, } _SCREAMING_SNAKE_CASE : Dict = { '''YituTech/conv-bert-base''': {'''do_lower_case''': True}, '''YituTech/conv-bert-medium-small''': {'''do_lower_case''': True}, '''YituTech/conv-bert-small''': {'''do_lower_case''': True}, } class a ( __lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE : List[str] = ConvBertTokenizer def __init__( self : int , __SCREAMING_SNAKE_CASE : Union[str, Any]=None , __SCREAMING_SNAKE_CASE : int=None , __SCREAMING_SNAKE_CASE : List[Any]=True , __SCREAMING_SNAKE_CASE : int="[UNK]" , __SCREAMING_SNAKE_CASE : Optional[int]="[SEP]" , __SCREAMING_SNAKE_CASE : Tuple="[PAD]" , __SCREAMING_SNAKE_CASE : Optional[Any]="[CLS]" , __SCREAMING_SNAKE_CASE : Dict="[MASK]" , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : List[str]=None , **__SCREAMING_SNAKE_CASE : Tuple , ) -> Union[str, Any]: super().__init__( __A , tokenizer_file=__A , do_lower_case=__A , unk_token=__A , sep_token=__A , pad_token=__A , cls_token=__A , mask_token=__A , tokenize_chinese_chars=__A , strip_accents=__A , **__A , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __A ) != do_lower_case or normalizer_state.get('strip_accents' , __A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __A ) != tokenize_chinese_chars ): lowerCamelCase_ = getattr(__A , normalizer_state.pop('type' ) ) lowerCamelCase_ = do_lower_case lowerCamelCase_ = strip_accents lowerCamelCase_ = tokenize_chinese_chars lowerCamelCase_ = normalizer_class(**__A ) lowerCamelCase_ = do_lower_case def UpperCamelCase ( self : str , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict=None ) -> int: lowerCamelCase_ = [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 UpperCamelCase ( self : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict = None ) -> List[int]: lowerCamelCase_ = [self.sep_token_id] lowerCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase ( self : Any , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[int] = None ) -> Tuple[str]: lowerCamelCase_ = self._tokenizer.model.save(__A , name=__A ) return tuple(__A )
714
"""simple docstring""" from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class a ( __snake_case ): def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : Distribution , __SCREAMING_SNAKE_CASE : List[str]=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Tuple=0 ) -> Optional[Any]: lowerCamelCase_ = 1.0 if scale is None else scale lowerCamelCase_ = 0.0 if loc is None else loc super().__init__(__SCREAMING_SNAKE_CASE , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=__SCREAMING_SNAKE_CASE )] ) @property def UpperCamelCase ( self : Optional[Any] ) -> Tuple: return self.base_dist.mean * self.scale + self.loc @property def UpperCamelCase ( self : int ) -> Any: return self.base_dist.variance * self.scale**2 @property def UpperCamelCase ( self : List[Any] ) -> str: return self.variance.sqrt() class a ( nn.Module ): def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Dict[str, int] , __SCREAMING_SNAKE_CASE : Callable[..., Tuple[torch.Tensor]] , **__SCREAMING_SNAKE_CASE : str ) -> None: super().__init__(**__SCREAMING_SNAKE_CASE ) lowerCamelCase_ = args_dim lowerCamelCase_ = nn.ModuleList([nn.Linear(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for dim in args_dim.values()] ) lowerCamelCase_ = domain_map def UpperCamelCase ( self : Dict , __SCREAMING_SNAKE_CASE : torch.Tensor ) -> Tuple[torch.Tensor]: lowerCamelCase_ = [proj(__SCREAMING_SNAKE_CASE ) for proj in self.proj] return self.domain_map(*__SCREAMING_SNAKE_CASE ) class a ( nn.Module ): def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: super().__init__() lowerCamelCase_ = function def UpperCamelCase ( self : Optional[int] , __SCREAMING_SNAKE_CASE : int , *__SCREAMING_SNAKE_CASE : List[Any] ) -> List[Any]: return self.function(__SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ) class a : SCREAMING_SNAKE_CASE : type SCREAMING_SNAKE_CASE : int SCREAMING_SNAKE_CASE : Dict[str, int] def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : int = 1 ) -> None: lowerCamelCase_ = dim lowerCamelCase_ = {k: dim * self.args_dim[k] for k in self.args_dim} def UpperCamelCase ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] ) -> List[Any]: if self.dim == 1: return self.distribution_class(*__SCREAMING_SNAKE_CASE ) else: return Independent(self.distribution_class(*__SCREAMING_SNAKE_CASE ) , 1 ) def UpperCamelCase ( self : Tuple , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[torch.Tensor] = None , __SCREAMING_SNAKE_CASE : Optional[torch.Tensor] = None , ) -> Distribution: lowerCamelCase_ = self._base_distribution(__SCREAMING_SNAKE_CASE ) if loc is None and scale is None: return distr else: return AffineTransformed(__SCREAMING_SNAKE_CASE , loc=__SCREAMING_SNAKE_CASE , scale=__SCREAMING_SNAKE_CASE , event_dim=self.event_dim ) @property def UpperCamelCase ( self : int ) -> Tuple: return () if self.dim == 1 else (self.dim,) @property def UpperCamelCase ( self : Optional[Any] ) -> int: return len(self.event_shape ) @property def UpperCamelCase ( self : List[Any] ) -> float: return 0.0 def UpperCamelCase ( self : List[str] , __SCREAMING_SNAKE_CASE : int ) -> nn.Module: return ParameterProjection( in_features=__SCREAMING_SNAKE_CASE , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def UpperCamelCase ( self : List[str] , *__SCREAMING_SNAKE_CASE : torch.Tensor ) -> List[str]: raise NotImplementedError() @staticmethod def UpperCamelCase ( __SCREAMING_SNAKE_CASE : torch.Tensor ) -> torch.Tensor: return (x + torch.sqrt(torch.square(__SCREAMING_SNAKE_CASE ) + 4.0 )) / 2.0 class a ( __snake_case ): SCREAMING_SNAKE_CASE : Dict[str, int] = {"df": 1, "loc": 1, "scale": 1} SCREAMING_SNAKE_CASE : type = StudentT @classmethod def UpperCamelCase ( cls : str , __SCREAMING_SNAKE_CASE : torch.Tensor , __SCREAMING_SNAKE_CASE : torch.Tensor , __SCREAMING_SNAKE_CASE : torch.Tensor ) -> Optional[Any]: lowerCamelCase_ = cls.squareplus(__SCREAMING_SNAKE_CASE ).clamp_min(torch.finfo(scale.dtype ).eps ) lowerCamelCase_ = 2.0 + cls.squareplus(__SCREAMING_SNAKE_CASE ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class a ( __snake_case ): SCREAMING_SNAKE_CASE : Dict[str, int] = {"loc": 1, "scale": 1} SCREAMING_SNAKE_CASE : type = Normal @classmethod def UpperCamelCase ( cls : Dict , __SCREAMING_SNAKE_CASE : torch.Tensor , __SCREAMING_SNAKE_CASE : torch.Tensor ) -> Tuple: lowerCamelCase_ = cls.squareplus(__SCREAMING_SNAKE_CASE ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class a ( __snake_case ): SCREAMING_SNAKE_CASE : Dict[str, int] = {"total_count": 1, "logits": 1} SCREAMING_SNAKE_CASE : type = NegativeBinomial @classmethod def UpperCamelCase ( cls : Dict , __SCREAMING_SNAKE_CASE : torch.Tensor , __SCREAMING_SNAKE_CASE : torch.Tensor ) -> Optional[Any]: lowerCamelCase_ = cls.squareplus(__SCREAMING_SNAKE_CASE ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def UpperCamelCase ( self : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Distribution: lowerCamelCase_ , lowerCamelCase_ = distr_args if self.dim == 1: return self.distribution_class(total_count=__SCREAMING_SNAKE_CASE , logits=__SCREAMING_SNAKE_CASE ) else: return Independent(self.distribution_class(total_count=__SCREAMING_SNAKE_CASE , logits=__SCREAMING_SNAKE_CASE ) , 1 ) def UpperCamelCase ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[torch.Tensor] = None , __SCREAMING_SNAKE_CASE : Optional[torch.Tensor] = None ) -> Distribution: lowerCamelCase_ , lowerCamelCase_ = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
137
0
def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): A_ : Any = 0 for ch in input_str: A_ : Union[str, Any] = ord(lowerCamelCase_ ) A_ : Tuple = pow(2 , lowerCamelCase_ ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
590
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 UpperCamelCase__ : Optional[Any] = logging.get_logger(__name__) UpperCamelCase__ : int = TypeVar('''DatasetType''', Dataset, IterableDataset) def __UpperCAmelCase ( lowerCamelCase_ : List[DatasetType] , lowerCamelCase_ : Optional[List[float]] = None , lowerCamelCase_ : Optional[int] = None , lowerCamelCase_ : Optional[DatasetInfo] = None , lowerCamelCase_ : Optional[NamedSplit] = None , lowerCamelCase_ : Literal["first_exhausted", "all_exhausted"] = "first_exhausted" , ) -> DatasetType: """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(lowerCamelCase_ ): if not isinstance(lowerCamelCase_ , (Dataset, IterableDataset) ): if isinstance(lowerCamelCase_ , (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(lowerCamelCase_ )}\n' F'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(lowerCamelCase_ ) )}\']' ) raise ValueError( F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(lowerCamelCase_ ).__name__}.' ) if i == 0: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = ( (Dataset, IterableDataset) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else (IterableDataset, Dataset) ) elif not isinstance(lowerCamelCase_ , lowerCamelCase_ ): 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( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , info=lowerCamelCase_ , split=lowerCamelCase_ , stopping_strategy=lowerCamelCase_ ) else: return _interleave_iterable_datasets( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , info=lowerCamelCase_ , split=lowerCamelCase_ , stopping_strategy=lowerCamelCase_ ) def __UpperCAmelCase ( lowerCamelCase_ : List[DatasetType] , lowerCamelCase_ : Optional[DatasetInfo] = None , lowerCamelCase_ : Optional[NamedSplit] = None , lowerCamelCase_ : int = 0 , ) -> DatasetType: """simple docstring""" if not dsets: raise ValueError('Unable to concatenate an empty list of datasets.' ) for i, dataset in enumerate(lowerCamelCase_ ): if not isinstance(lowerCamelCase_ , (Dataset, IterableDataset) ): if isinstance(lowerCamelCase_ , (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(lowerCamelCase_ )}\n' F'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(lowerCamelCase_ ) )}\']' ) raise ValueError( F'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(lowerCamelCase_ ).__name__}.' ) if i == 0: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = ( (Dataset, IterableDataset) if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else (IterableDataset, Dataset) ) elif not isinstance(lowerCamelCase_ , lowerCamelCase_ ): 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(lowerCamelCase_ , info=lowerCamelCase_ , split=lowerCamelCase_ , axis=lowerCamelCase_ ) else: return _concatenate_iterable_datasets(lowerCamelCase_ , info=lowerCamelCase_ , split=lowerCamelCase_ , axis=lowerCamelCase_ )
105
0
"""simple docstring""" import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def lowercase__ ( lowercase_ ) -> List[str]: """simple docstring""" _UpperCamelCase : int = model.config _UpperCamelCase : Optional[int] = DonutSwinConfig( image_size=original_config.input_size ,patch_size=4 ,depths=original_config.encoder_layer ,num_heads=[4, 8, 16, 32] ,window_size=original_config.window_size ,embed_dim=128 ,) _UpperCamelCase : Any = MBartConfig( is_decoder=lowercase_ ,is_encoder_decoder=lowercase_ ,add_cross_attention=lowercase_ ,decoder_layers=original_config.decoder_layer ,max_position_embeddings=original_config.max_position_embeddings ,vocab_size=len( model.decoder.tokenizer ) ,scale_embedding=lowercase_ ,add_final_layer_norm=lowercase_ ,) return encoder_config, decoder_config def lowercase__ ( lowercase_ ) -> Optional[int]: """simple docstring""" if "encoder.model" in name: _UpperCamelCase : str = name.replace("encoder.model" ,"encoder" ) if "decoder.model" in name: _UpperCamelCase : Dict = name.replace("decoder.model" ,"decoder" ) if "patch_embed.proj" in name: _UpperCamelCase : List[Any] = name.replace("patch_embed.proj" ,"embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: _UpperCamelCase : str = name.replace("patch_embed.norm" ,"embeddings.norm" ) if name.startswith("encoder" ): if "layers" in name: _UpperCamelCase : Union[str, Any] = "encoder." + name if "attn.proj" in name: _UpperCamelCase : Any = name.replace("attn.proj" ,"attention.output.dense" ) if "attn" in name and "mask" not in name: _UpperCamelCase : int = name.replace("attn" ,"attention.self" ) if "norm1" in name: _UpperCamelCase : int = name.replace("norm1" ,"layernorm_before" ) if "norm2" in name: _UpperCamelCase : int = name.replace("norm2" ,"layernorm_after" ) if "mlp.fc1" in name: _UpperCamelCase : List[str] = name.replace("mlp.fc1" ,"intermediate.dense" ) if "mlp.fc2" in name: _UpperCamelCase : Optional[Any] = name.replace("mlp.fc2" ,"output.dense" ) if name == "encoder.norm.weight": _UpperCamelCase : Union[str, Any] = "encoder.layernorm.weight" if name == "encoder.norm.bias": _UpperCamelCase : Tuple = "encoder.layernorm.bias" return name def lowercase__ ( lowercase_ ,lowercase_ ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): _UpperCamelCase : Optional[Any] = orig_state_dict.pop(lowercase_ ) if "qkv" in key: _UpperCamelCase : Tuple = key.split("." ) _UpperCamelCase : Dict = int(key_split[3] ) _UpperCamelCase : Optional[Any] = int(key_split[5] ) _UpperCamelCase : int = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _UpperCamelCase : int = val[:dim, :] _UpperCamelCase : Tuple = val[dim : dim * 2, :] _UpperCamelCase : Optional[Any] = val[-dim:, :] else: _UpperCamelCase : Union[str, Any] = val[:dim] _UpperCamelCase : Tuple = val[dim : dim * 2] _UpperCamelCase : Any = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: _UpperCamelCase : Dict = val return orig_state_dict def lowercase__ ( lowercase_ ,lowercase_=None ,lowercase_=False ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : List[str] = DonutModel.from_pretrained(lowercase_ ).eval() # load HuggingFace model _UpperCamelCase, _UpperCamelCase : Dict = get_configs(lowercase_ ) _UpperCamelCase : Dict = DonutSwinModel(lowercase_ ) _UpperCamelCase : int = MBartForCausalLM(lowercase_ ) _UpperCamelCase : str = VisionEncoderDecoderModel(encoder=lowercase_ ,decoder=lowercase_ ) model.eval() _UpperCamelCase : str = original_model.state_dict() _UpperCamelCase : Union[str, Any] = convert_state_dict(lowercase_ ,lowercase_ ) model.load_state_dict(lowercase_ ) # verify results on scanned document _UpperCamelCase : Any = load_dataset("hf-internal-testing/example-documents" ) _UpperCamelCase : Any = dataset["test"][0]["image"].convert("RGB" ) _UpperCamelCase : Dict = XLMRobertaTokenizerFast.from_pretrained(lowercase_ ,from_slow=lowercase_ ) _UpperCamelCase : Any = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis ,size=original_model.config.input_size[::-1] ) _UpperCamelCase : int = DonutProcessor(lowercase_ ,lowercase_ ) _UpperCamelCase : List[str] = processor(lowercase_ ,return_tensors="pt" ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": _UpperCamelCase : Optional[Any] = "<s_docvqa><s_question>{user_input}</s_question><s_answer>" _UpperCamelCase : str = "When is the coffee break?" _UpperCamelCase : str = task_prompt.replace("{user_input}" ,lowercase_ ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": _UpperCamelCase : int = "<s_rvlcdip>" elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: _UpperCamelCase : Any = "<s_cord>" elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": _UpperCamelCase : Tuple = "s_cord-v2>" elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": _UpperCamelCase : Tuple = "<s_zhtrainticket>" elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt _UpperCamelCase : List[Any] = "hello world" else: raise ValueError("Model name not supported" ) _UpperCamelCase : str = original_model.decoder.tokenizer(lowercase_ ,add_special_tokens=lowercase_ ,return_tensors="pt" )[ "input_ids" ] _UpperCamelCase : List[Any] = original_model.encoder.model.patch_embed(lowercase_ ) _UpperCamelCase, _UpperCamelCase : List[Any] = model.encoder.embeddings(lowercase_ ) assert torch.allclose(lowercase_ ,lowercase_ ,atol=1e-3 ) # verify encoder hidden states _UpperCamelCase : Any = original_model.encoder(lowercase_ ) _UpperCamelCase : Any = model.encoder(lowercase_ ).last_hidden_state assert torch.allclose(lowercase_ ,lowercase_ ,atol=1e-2 ) # verify decoder hidden states _UpperCamelCase : Any = original_model(lowercase_ ,lowercase_ ,lowercase_ ).logits _UpperCamelCase : List[str] = model(lowercase_ ,decoder_input_ids=lowercase_ ).logits assert torch.allclose(lowercase_ ,lowercase_ ,atol=1e-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(F'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) if push_to_hub: model.push_to_hub("nielsr/" + model_name.split("/" )[-1] ,commit_message="Update model" ) processor.push_to_hub("nielsr/" + model_name.split("/" )[-1] ,commit_message="Update model" ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub.", ) lowerCamelCase__ = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
51
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar lowerCamelCase__ = TypeVar("KEY") lowerCamelCase__ = TypeVar("VAL") @dataclass(frozen=_UpperCamelCase , slots=_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( Generic[KEY, VAL] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :KEY SCREAMING_SNAKE_CASE__ :VAL class __SCREAMING_SNAKE_CASE ( _Item ): '''simple docstring''' def __init__( self : List[str] ) -> None: super().__init__(__a , __a ) def __bool__( self : Dict ) -> bool: return False lowerCamelCase__ = _DeletedItem() class __SCREAMING_SNAKE_CASE ( MutableMapping[KEY, VAL] ): '''simple docstring''' def __init__( self : int , __a : int = 8 , __a : float = 0.75 ) -> None: _UpperCamelCase : str = initial_block_size _UpperCamelCase : list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 _UpperCamelCase : List[str] = capacity_factor _UpperCamelCase : Dict = 0 def __SCREAMING_SNAKE_CASE ( self : int , __a : KEY ) -> int: return hash(__a ) % len(self._buckets ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : int ) -> int: return (ind + 1) % len(self._buckets ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : int , __a : KEY , __a : VAL ) -> bool: _UpperCamelCase : List[Any] = self._buckets[ind] if not stored: _UpperCamelCase : Tuple = _Item(__a , __a ) self._len += 1 return True elif stored.key == key: _UpperCamelCase : Union[str, Any] = _Item(__a , __a ) return True else: return False def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> bool: _UpperCamelCase : Any = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False _UpperCamelCase : List[str] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : int ) -> None: _UpperCamelCase : Any = self._buckets _UpperCamelCase : List[Any] = [None] * new_size _UpperCamelCase : List[str] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __SCREAMING_SNAKE_CASE ( self : int ) -> None: self._resize(len(self._buckets ) * 2 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: self._resize(len(self._buckets ) // 2 ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : KEY ) -> Iterator[int]: _UpperCamelCase : str = self._get_bucket_index(__a ) for _ in range(len(self._buckets ) ): yield ind _UpperCamelCase : Tuple = self._get_next_ind(__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : KEY , __a : VAL ) -> None: for ind in self._iterate_buckets(__a ): if self._try_set(__a , __a , __a ): break def __setitem__( self : int , __a : KEY , __a : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(__a , __a ) def __delitem__( self : str , __a : KEY ) -> None: for ind in self._iterate_buckets(__a ): _UpperCamelCase : Tuple = self._buckets[ind] if item is None: raise KeyError(__a ) if item is _deleted: continue if item.key == key: _UpperCamelCase : List[Any] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : str , __a : KEY ) -> VAL: for ind in self._iterate_buckets(__a ): _UpperCamelCase : Tuple = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__a ) def __len__( self : List[Any] ) -> int: return self._len def __iter__( self : List[str] ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : List[str] ) -> str: _UpperCamelCase : Optional[int] = " ,".join( F'''{item.key}: {item.val}''' for item in self._buckets if item ) return F'''HashMap({val_string})'''
51
1
import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin _SCREAMING_SNAKE_CASE = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.plbart.modeling_plbart import shift_tokens_right _SCREAMING_SNAKE_CASE = 50_003 _SCREAMING_SNAKE_CASE = 50_002 @require_sentencepiece @require_tokenizers class a ( UpperCAmelCase__ , unittest.TestCase ): """simple docstring""" lowerCamelCase :Tuple = PLBartTokenizer lowerCamelCase :str = None lowerCamelCase :Optional[Any] = False def UpperCAmelCase ( self ) -> List[Any]: super().setUp() # We have a SentencePiece fixture for testing _A = PLBartTokenizer(_a , language_codes="""base""" , keep_accents=_a ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase ( self ) -> Optional[int]: _A = PLBartTokenizer(_a , language_codes="""base""" , keep_accents=_a ) _A = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(_a , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) _A = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( _a , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _A = tokenizer.convert_tokens_to_ids(_a ) self.assertListEqual( _a , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) _A = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) _A = tokenizer.vocab_size _A = [tokenizer.convert_ids_to_tokens(_a ) for x in range(end - 4 , _a )] self.assertListEqual(_a , ["""__java__""", """__python__""", """__en_XX__""", """<mask>"""] ) _A = """java.lang.Exception, python.lang.Exception, javascript, php, ruby, go""" _A = tokenizer(_a ).input_ids self.assertEqual( tokenizer.decode(_a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a ) , _a , ) def UpperCAmelCase ( self ) -> Tuple: _A = PLBartTokenizer(_a , language_codes="""multi""" , keep_accents=_a ) _A = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(_a , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) _A = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( _a , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _A = tokenizer.convert_tokens_to_ids(_a ) self.assertListEqual( _a , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) _A = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) _A = tokenizer.vocab_size _A = [tokenizer.convert_ids_to_tokens(_a ) for x in range(end - 7 , _a )] self.assertListEqual( _a , ["""__java__""", """__python__""", """__en_XX__""", """__javascript__""", """__php__""", """__ruby__""", """__go__"""] ) _A = """java.lang.Exception, python.lang.Exception, javascript, php, ruby, go""" _A = tokenizer(_a ).input_ids self.assertEqual( tokenizer.decode(_a , skip_special_tokens=_a , clean_up_tokenization_spaces=_a ) , _a , ) @require_torch @require_sentencepiece @require_tokenizers class a ( unittest.TestCase ): """simple docstring""" lowerCamelCase :Tuple = '''uclanlp/plbart-python-en_XX''' lowerCamelCase :Optional[int] = [ '''def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])''', '''def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])''', ] lowerCamelCase :str = [ '''Returns the maximum value of a b c.''', '''Sums the values of a b c.''', ] lowerCamelCase :List[str] = [ 134, 5452, 33460, 33441, 33463, 33465, 33463, 33449, 988, 20, 33456, 19, 33456, 771, 39, 4258, 889, 3318, 33441, 33463, 33465, 33463, 33449, 2471, 2, PYTHON_CODE, ] @classmethod def UpperCAmelCase ( cls ) -> int: _A = PLBartTokenizer.from_pretrained( cls.checkpoint_name , language_codes="""base""" , src_lang="""python""" , tgt_lang="""en_XX""" ) _A = 1 return cls def UpperCAmelCase ( self ) -> Optional[int]: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""__java__"""] , 5_00_01 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""__python__"""] , 5_00_02 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""__en_XX__"""] , 5_00_03 ) def UpperCAmelCase ( self ) -> Optional[Any]: _A = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , _a ) def UpperCAmelCase ( self ) -> int: self.assertIn(_a , self.tokenizer.all_special_ids ) _A = [EN_CODE, 90_37, 3_34_42, 57, 7_52, 1_53, 14, 56, 18, 9, 2] _A = self.tokenizer.decode(_a , skip_special_tokens=_a ) _A = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_a ) self.assertEqual(_a , _a ) self.assertNotIn(self.tokenizer.eos_token , _a ) def UpperCAmelCase ( self ) -> List[str]: _A = ["""def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])""" * 20] self.assertIsInstance(src_text[0] , _a ) _A = 10 _A = self.tokenizer(_a , max_length=_a , truncation=_a ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , _a ) self.assertEqual(len(_a ) , _a ) def UpperCAmelCase ( self ) -> Any: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """__java__"""] ) , [5_00_04, 5_00_01] ) def UpperCAmelCase ( self ) -> Dict: _A = tempfile.mkdtemp() _A = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(_a ) _A = PLBartTokenizer.from_pretrained(_a ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , _a ) @require_torch def UpperCAmelCase ( self ) -> Optional[Any]: _A = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=_a , return_tensors="""pt""" ) _A = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 self.assertEqual(batch.input_ids[1][-2:].tolist() , [2, PYTHON_CODE] ) self.assertEqual(batch.decoder_input_ids[1][0] , _a ) self.assertEqual(batch.decoder_input_ids[1][-1] , 2 ) self.assertEqual(batch.labels[1][-2:].tolist() , [2, EN_CODE] ) @require_torch def UpperCAmelCase ( self ) -> Tuple: _A = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=_a , truncation=_a , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) _A = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) self.assertIsInstance(_a , _a ) self.assertEqual((2, 26) , batch.input_ids.shape ) self.assertEqual((2, 26) , batch.attention_mask.shape ) _A = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , _a ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, PYTHON_CODE] ) def UpperCAmelCase ( self ) -> Any: _A = self.tokenizer(self.src_text , padding=_a , truncation=_a , max_length=3 , return_tensors="""pt""" ) _A = self.tokenizer( text_target=self.tgt_text , padding=_a , truncation=_a , max_length=10 , return_tensors="""pt""" ) _A = targets["""input_ids"""] _A = shift_tokens_right(_a , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase ( self ) -> str: _A = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""java""" ) self.assertEqual( nested_simplify(_a ) , { # A, test, EOS, en_XX """input_ids""": [[1_50, 2_42, 2, 5_00_03]], """attention_mask""": [[1, 1, 1, 1]], # java """forced_bos_token_id""": 5_00_01, } , )
401
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels lowerCAmelCase : List[str] = object() # For specifying empty leaf dict `{}` lowerCAmelCase : Any = object() def a__ ( snake_case__ , snake_case__ ) -> List[Any]: lowerCamelCase = tuple((re.compile(x + """$""" ) for x in qs) ) for i in range(len(snake_case__ ) - len(snake_case__ ) + 1 ): lowerCamelCase = [x.match(snake_case__ ) for x, y in zip(snake_case__ , ks[i:] )] if matches and all(snake_case__ ): return True return False def a__ ( snake_case__ ) -> str: def replace(snake_case__ , snake_case__ ): for rule, replacement in rules: if _match(snake_case__ , snake_case__ ): return replacement return val return replace def a__ ( ) -> Union[str, Any]: return [ # embeddings (("transformer", "wpe", "embedding"), P("""mp""" , snake_case__ )), (("transformer", "wte", "embedding"), P("""mp""" , snake_case__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(snake_case__ , """mp""" )), (("attention", "out_proj", "kernel"), P("""mp""" , snake_case__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(snake_case__ , """mp""" )), (("mlp", "c_fc", "bias"), P("""mp""" )), (("mlp", "c_proj", "kernel"), P("""mp""" , snake_case__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def a__ ( snake_case__ ) -> Optional[Any]: lowerCamelCase = _get_partition_rules() lowerCamelCase = _replacement_rules(snake_case__ ) lowerCamelCase = {k: _unmatched for k in flatten_dict(snake_case__ )} lowerCamelCase = {k: replace(snake_case__ , snake_case__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(snake_case__ ) )
543
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class A ( unittest.TestCase ): def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=18 , SCREAMING_SNAKE_CASE=30 , SCREAMING_SNAKE_CASE=400 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=[0.48_145_466, 0.4_578_275, 0.40_821_073] , SCREAMING_SNAKE_CASE=[0.26_862_954, 0.26_130_258, 0.27_577_711] , SCREAMING_SNAKE_CASE=True , ) -> Optional[int]: """simple docstring""" A : Dict = size if size is not None else {'''height''': 224, '''width''': 224} A : int = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} A : Tuple = parent A : int = batch_size A : Optional[int] = num_channels A : str = image_size A : Optional[int] = min_resolution A : List[str] = max_resolution A : List[Any] = do_resize A : Optional[int] = size A : Optional[int] = do_center_crop A : Any = crop_size A : Any = do_normalize A : Optional[Any] = image_mean A : str = image_std A : Dict = do_convert_rgb def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False ) -> Any: """simple docstring""" assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: A : Dict = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 255 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: A : Union[str, Any] = [] for i in range(self.batch_size ): A : str = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(255 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension A : Optional[int] = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] if torchify: A : Dict = [torch.from_numpy(SCREAMING_SNAKE_CASE ) for x in image_inputs] return image_inputs @require_torch @require_vision class A ( __snake_case , unittest.TestCase ): __magic_name__ = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Union[str, Any] = ChineseCLIPImageProcessingTester(self , do_center_crop=SCREAMING_SNAKE_CASE ) @property def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''do_resize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''size''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''do_center_crop''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''center_crop''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''image_mean''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''image_std''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''do_convert_rgb''' ) ) def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 224, '''width''': 224} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) A : Dict = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" pass def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" A : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : List[str] = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input A : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched A : List[str] = image_processing(SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE , numpify=SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input A : Optional[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched A : Tuple = image_processing(SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Union[str, Any] = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE , torchify=SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input A : List[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched A : str = image_processing(SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) @require_torch @require_vision class A ( __snake_case , unittest.TestCase ): __magic_name__ = ChineseCLIPImageProcessor if is_vision_available() else None def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" A : Optional[int] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=SCREAMING_SNAKE_CASE ) A : Tuple = 3 @property def __lowerCAmelCase ( self ) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''do_resize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''size''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''do_center_crop''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''center_crop''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''image_mean''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''image_std''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , '''do_convert_rgb''' ) ) def __lowerCAmelCase ( self ) -> int: """simple docstring""" pass def __lowerCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" A : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : List[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input A : Any = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched A : Union[str, Any] = image_processing(SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
704
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging lowercase : str = logging.get_logger(__name__) # TODO: upload to AWS lowercase : Optional[Any] = { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json' ), } class A ( __snake_case ): __magic_name__ = '''retribert''' def __init__( self , SCREAMING_SNAKE_CASE=30522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=8 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-12 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=0 , **SCREAMING_SNAKE_CASE , ) -> Tuple: """simple docstring""" super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) A : List[Any] = vocab_size A : Dict = hidden_size A : Any = num_hidden_layers A : Any = num_attention_heads A : List[Any] = hidden_act A : Any = intermediate_size A : str = hidden_dropout_prob A : int = attention_probs_dropout_prob A : List[Any] = max_position_embeddings A : Tuple = type_vocab_size A : Optional[Any] = initializer_range A : Union[str, Any] = layer_norm_eps A : Dict = share_encoders A : Dict = projection_dim
343
0
"""simple docstring""" from __future__ import annotations import requests __lowerCamelCase = set( 'approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports'.split() ) def a ( __UpperCAmelCase : str , __UpperCAmelCase : int = 1 , __UpperCAmelCase : str = "new" , __UpperCAmelCase : list | None = None ) -> dict: __magic_name__: Optional[Any] = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(__UpperCAmelCase ) - valid_terms ) ): __magic_name__: Optional[int] = f'Invalid search term: {invalid_search_terms}' raise ValueError(__UpperCAmelCase ) __magic_name__: Optional[int] = requests.get( f'https://reddit.com/r/{subreddit}/{age}.json?limit={limit}' , headers={"""User-agent""": """A random string"""} , ) if response.status_code == 4_2_9: raise requests.HTTPError __magic_name__: Optional[int] = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(__UpperCAmelCase )} __magic_name__: str = {} for id_ in range(__UpperCAmelCase ): __magic_name__: str = { item: data["""data"""]["""children"""][id_]["""data"""][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data('learnpython', wanted_data=['title', 'url', 'selftext']))
96
'''simple docstring''' import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency _A: Optional[Any] = { """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } _A: List[Any] = """ETAOINSHRDLCUMWFGYPBVKJXQZ""" _A: str = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def _lowerCAmelCase ( _lowerCAmelCase )-> dict[str, int]: __UpperCAmelCase = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def _lowerCAmelCase ( _lowerCAmelCase )-> str: return x[0] def _lowerCAmelCase ( _lowerCAmelCase )-> str: __UpperCAmelCase = get_letter_count(_lowerCAmelCase ) __UpperCAmelCase = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(_lowerCAmelCase ) __UpperCAmelCase = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=_lowerCAmelCase ) __UpperCAmelCase = ''.join(freq_to_letter[freq] ) __UpperCAmelCase = list(freq_to_letter_str.items() ) freq_pairs.sort(key=_lowerCAmelCase , reverse=_lowerCAmelCase ) __UpperCAmelCase = [freq_pair[1] for freq_pair in freq_pairs] return "".join(_lowerCAmelCase ) def _lowerCAmelCase ( _lowerCAmelCase )-> int: __UpperCAmelCase = get_frequency_order(_lowerCAmelCase ) __UpperCAmelCase = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
126
0
"""simple docstring""" import collections import os import re from pathlib import Path A = 'src/transformers' # Matches is_xxx_available() A = re.compile(r'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} A = re.compile(r'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] A = re.compile(r'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available A = re.compile(r'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") A = re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] A = re.compile(r'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", A = re.compile(r'^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], A = re.compile(r'^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo A = re.compile(r'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: A = re.compile(r'^\s*try:') # Catches a line with else: A = re.compile(r'^\s*else:') def lowerCAmelCase__ ( lowerCamelCase__ ) -> Optional[int]: if _re_test_backend.search(_SCREAMING_SNAKE_CASE ) is None: return None A = [b[0] for b in _re_backend.findall(_SCREAMING_SNAKE_CASE )] backends.sort() return "_and_".join(_SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( lowerCamelCase__ ) -> Optional[int]: with open(_SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' , newline='\n' ) as f: A = f.readlines() A = 0 while line_index < len(_SCREAMING_SNAKE_CASE ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(_SCREAMING_SNAKE_CASE ): return None # First grab the objects without a specific backend in _import_structure A = [] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: A = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(_SCREAMING_SNAKE_CASE ): A = _re_one_line_import_struct.search(_SCREAMING_SNAKE_CASE ).groups()[0] A = re.findall(R'\[([^\]]+)\]' , _SCREAMING_SNAKE_CASE ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue A = _re_import_struct_key_value.search(_SCREAMING_SNAKE_CASE ) if single_line_import_search is not None: A = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(_SCREAMING_SNAKE_CASE ) > 0] objects.extend(_SCREAMING_SNAKE_CASE ) elif line.startswith(' ' * 8 + '\"' ): objects.append(line[9:-3] ) line_index += 1 A = {'none': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING' ): # If the line is an if not is_backend_available, we grab all objects associated. A = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): A = lines[line_index] if _re_import_struct_add_one.search(_SCREAMING_SNAKE_CASE ) is not None: objects.append(_re_import_struct_add_one.search(_SCREAMING_SNAKE_CASE ).groups()[0] ) elif _re_import_struct_add_many.search(_SCREAMING_SNAKE_CASE ) is not None: A = _re_import_struct_add_many.search(_SCREAMING_SNAKE_CASE ).groups()[0].split(', ' ) A = [obj[1:-1] for obj in imports if len(_SCREAMING_SNAKE_CASE ) > 0] objects.extend(_SCREAMING_SNAKE_CASE ) elif _re_between_brackets.search(_SCREAMING_SNAKE_CASE ) is not None: A = _re_between_brackets.search(_SCREAMING_SNAKE_CASE ).groups()[0].split(', ' ) A = [obj[1:-1] for obj in imports if len(_SCREAMING_SNAKE_CASE ) > 0] objects.extend(_SCREAMING_SNAKE_CASE ) elif _re_quote_object.search(_SCREAMING_SNAKE_CASE ) is not None: objects.append(_re_quote_object.search(_SCREAMING_SNAKE_CASE ).groups()[0] ) elif line.startswith(' ' * 8 + '\"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '\"' ): objects.append(line[13:-3] ) line_index += 1 A = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A = [] while ( line_index < len(_SCREAMING_SNAKE_CASE ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): A = lines[line_index] A = _re_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 A = {'none': objects} # Let's continue with backend-specific objects while line_index < len(_SCREAMING_SNAKE_CASE ): # If the line is an if is_backend_available, we grab all objects associated. A = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): A = lines[line_index] A = _re_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(' ' * 12 ): objects.append(line[12:-2] ) line_index += 1 A = objects else: line_index += 1 return import_dict_objects, type_hint_objects def lowerCAmelCase__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Tuple: def find_duplicates(lowerCamelCase__ ): return [k for k, v in collections.Counter(_SCREAMING_SNAKE_CASE ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] A = [] for key in import_dict_objects.keys(): A = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f"""Duplicate _import_structure definitions for: {duplicate_imports}""" ) A = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f"""Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}""" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): A = 'base imports' if key == 'none' else f"""{key} backend""" errors.append(f"""Differences for {name}:""" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f""" {a} in TYPE_HINT but not in _import_structure.""" ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f""" {a} in _import_structure but not in TYPE_HINT.""" ) return errors def lowerCAmelCase__ ( ) -> str: A = [] for root, _, files in os.walk(_SCREAMING_SNAKE_CASE ): if "__init__.py" in files: A = os.path.join(_SCREAMING_SNAKE_CASE , '__init__.py' ) A = parse_init(_SCREAMING_SNAKE_CASE ) if objects is not None: A = analyze_results(*_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: A = f"""Problem in {fname}, both halves do not define the same objects.\n{errors[0]}""" failures.append('\n'.join(_SCREAMING_SNAKE_CASE ) ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError('\n\n'.join(_SCREAMING_SNAKE_CASE ) ) def lowerCAmelCase__ ( ) -> int: A = [] for path, directories, files in os.walk(_SCREAMING_SNAKE_CASE ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(_SCREAMING_SNAKE_CASE ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(_SCREAMING_SNAKE_CASE ) / folder).glob('*.py' ) ) ) == 0: continue A = str((Path(_SCREAMING_SNAKE_CASE ) / folder).relative_to(_SCREAMING_SNAKE_CASE ) ) A = short_path.replace(os.path.sep , '.' ) submodules.append(_SCREAMING_SNAKE_CASE ) for fname in files: if fname == "__init__.py": continue A = str((Path(_SCREAMING_SNAKE_CASE ) / fname).relative_to(_SCREAMING_SNAKE_CASE ) ) A = short_path.replace('.py' , '' ).replace(os.path.sep , '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(_SCREAMING_SNAKE_CASE ) return submodules A = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', 'models.esm.openfold_utils', ] def lowerCAmelCase__ ( ) -> Tuple: # This is to make sure the transformers module imported is the one in the repo. from transformers.utils import direct_transformers_import A = direct_transformers_import(_SCREAMING_SNAKE_CASE ) A = set(transformers._import_structure.keys() ) # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and # (potentiall re-) add them. with open(os.path.join(_SCREAMING_SNAKE_CASE , '__init__.py' ) , 'r' ) as f: A = f.read() import_structure_keys.update(set(re.findall(R'import_structure\[\"([^\"]*)\"\]' , _SCREAMING_SNAKE_CASE ) ) ) A = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in import_structure_keys ] if len(_SCREAMING_SNAKE_CASE ) > 0: A = '\n'.join(f"""- {module}""" for module in module_not_registered ) raise ValueError( 'The following submodules are not properly registed in the main init of Transformers:\n' f"""{list_of_modules}\n""" 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.' ) if __name__ == "__main__": check_all_inits() check_submodules()
702
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class UpperCAmelCase__ ( unittest.TestCase ): def A_ ( self : Dict ) -> Dict: '''simple docstring''' A = tempfile.mkdtemp() A = BlipImageProcessor() A = GPTaTokenizer.from_pretrained('hf-internal-testing/tiny-random-GPT2Model' ) A = BertTokenizerFast.from_pretrained('hf-internal-testing/tiny-random-bert' ) A = InstructBlipProcessor(snake_case , snake_case , snake_case ) processor.save_pretrained(self.tmpdirname ) def A_ ( self : List[str] , **snake_case : str ) -> Dict: '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **snake_case ).tokenizer def A_ ( self : int , **snake_case : Optional[Any] ) -> Any: '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **snake_case ).image_processor def A_ ( self : Any , **snake_case : Union[str, Any] ) -> Any: '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **snake_case ).qformer_tokenizer def A_ ( self : int ) -> Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : List[Any] ) -> Tuple: '''simple docstring''' A = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] A = [Image.fromarray(np.moveaxis(snake_case , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' A = InstructBlipProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() , qformer_tokenizer=self.get_qformer_tokenizer() , ) processor.save_pretrained(self.tmpdirname ) A = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) A = self.get_image_processor(do_normalize=snake_case , padding_value=1.0 ) A = InstructBlipProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=snake_case , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , snake_case ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , snake_case ) self.assertIsInstance(processor.qformer_tokenizer , snake_case ) def A_ ( self : Optional[Any] ) -> Dict: '''simple docstring''' A = self.get_image_processor() A = self.get_tokenizer() A = self.get_qformer_tokenizer() A = InstructBlipProcessor( tokenizer=snake_case , image_processor=snake_case , qformer_tokenizer=snake_case ) A = self.prepare_image_inputs() A = image_processor(snake_case , return_tensors='np' ) A = processor(images=snake_case , 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 A_ ( self : Tuple ) -> List[str]: '''simple docstring''' A = self.get_image_processor() A = self.get_tokenizer() A = self.get_qformer_tokenizer() A = InstructBlipProcessor( tokenizer=snake_case , image_processor=snake_case , qformer_tokenizer=snake_case ) A = 'lower newer' A = processor(text=snake_case ) A = tokenizer(snake_case , return_token_type_ids=snake_case ) A = qformer_tokenizer(snake_case , return_token_type_ids=snake_case ) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key] , encoded_processor[key] ) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key] , encoded_processor['qformer_' + key] ) def A_ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' A = self.get_image_processor() A = self.get_tokenizer() A = self.get_qformer_tokenizer() A = InstructBlipProcessor( tokenizer=snake_case , image_processor=snake_case , qformer_tokenizer=snake_case ) A = 'lower newer' A = self.prepare_image_inputs() A = processor(text=snake_case , images=snake_case ) self.assertListEqual( list(inputs.keys() ) , ['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values'] , ) # test if it raises when no input is passed with pytest.raises(snake_case ): processor() def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' A = self.get_image_processor() A = self.get_tokenizer() A = self.get_qformer_tokenizer() A = InstructBlipProcessor( tokenizer=snake_case , image_processor=snake_case , qformer_tokenizer=snake_case ) A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] A = processor.batch_decode(snake_case ) A = tokenizer.batch_decode(snake_case ) self.assertListEqual(snake_case , snake_case ) def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' A = self.get_image_processor() A = self.get_tokenizer() A = self.get_qformer_tokenizer() A = InstructBlipProcessor( tokenizer=snake_case , image_processor=snake_case , qformer_tokenizer=snake_case ) A = 'lower newer' A = self.prepare_image_inputs() A = processor(text=snake_case , images=snake_case ) self.assertListEqual( list(inputs.keys() ) , ['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values'] , )
109
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) __A : Optional[int] = {'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = ['BeitFeatureExtractor'] __A : int = ['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Tuple = [ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys __A : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
334
'''simple docstring''' def UpperCAmelCase ( lowerCamelCase_ :int ): '''simple docstring''' if isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(lowerCamelCase_ , lowerCamelCase_ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" snake_case_ : str = False if num < 0: snake_case_ : Optional[int] = True snake_case_ : List[str] = -num snake_case_ : list[int] = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCamelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCamelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
334
1
'''simple docstring''' from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Union[str, Any] =logging.get_logger(__name__) A__ : Dict ={ 'microsoft/xprophetnet-large-wiki100-cased': ( 'https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json' ), } class __A ( _SCREAMING_SNAKE_CASE ): lowerCamelCase ='''xlm-prophetnet''' lowerCamelCase =['''past_key_values'''] lowerCamelCase ={ '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self : List[Any] , lowerCamelCase : Optional[float] = 0.1 , lowerCamelCase : Optional[Union[str, Callable]] = "gelu" , lowerCamelCase : Optional[int] = 3_05_22 , lowerCamelCase : Optional[int] = 10_24 , lowerCamelCase : Optional[int] = 40_96 , lowerCamelCase : Optional[int] = 12 , lowerCamelCase : Optional[int] = 16 , lowerCamelCase : Optional[int] = 40_96 , lowerCamelCase : Optional[int] = 12 , lowerCamelCase : Optional[int] = 16 , lowerCamelCase : Optional[float] = 0.1 , lowerCamelCase : Optional[float] = 0.1 , lowerCamelCase : Optional[int] = 5_12 , lowerCamelCase : Optional[float] = 0.02 , lowerCamelCase : Optional[bool] = True , lowerCamelCase : Optional[bool] = True , lowerCamelCase : Optional[int] = 0 , lowerCamelCase : Optional[int] = 2 , lowerCamelCase : Optional[int] = 32 , lowerCamelCase : Optional[int] = 1_28 , lowerCamelCase : Optional[bool] = False , lowerCamelCase : Optional[float] = 0.0 , lowerCamelCase : Optional[bool] = True , lowerCamelCase : Optional[int] = 0 , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : Optional[int] = 2 , **lowerCamelCase : List[Any] , ): """simple docstring""" __A : List[Any] = vocab_size __A : Union[str, Any] = hidden_size __A : int = encoder_ffn_dim __A : Optional[int] = num_encoder_layers __A : Any = num_encoder_attention_heads __A : Optional[int] = decoder_ffn_dim __A : Optional[Any] = num_decoder_layers __A : Any = num_decoder_attention_heads __A : List[str] = max_position_embeddings __A : Tuple = init_std # Normal(0, this parameter) __A : str = activation_function # parameters for xlmprophetnet __A : Tuple = ngram __A : Dict = num_buckets __A : Optional[Any] = relative_max_distance __A : str = disable_ngram_loss __A : List[str] = eps # 3 Types of Dropout __A : int = attention_dropout __A : Union[str, Any] = activation_dropout __A : List[str] = dropout __A : List[str] = use_cache super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , is_encoder_decoder=lowerCamelCase , add_cross_attention=lowerCamelCase , decoder_start_token_id=lowerCamelCase , **lowerCamelCase , ) @property def lowercase_( self : Union[str, Any] ): """simple docstring""" return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def lowercase_( self : Any , lowerCamelCase : List[str] ): """simple docstring""" raise NotImplementedError( """This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and""" """ `num_decoder_layers`.""" )
716
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : int =logging.get_logger(__name__) A__ : Union[str, Any] ={ 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json' ), } class __A ( _SCREAMING_SNAKE_CASE ): lowerCamelCase ='''dpr''' def __init__( self : Optional[int] , lowerCamelCase : Tuple=3_05_22 , lowerCamelCase : List[str]=7_68 , lowerCamelCase : Union[str, Any]=12 , lowerCamelCase : Tuple=12 , lowerCamelCase : Dict=30_72 , lowerCamelCase : List[Any]="gelu" , lowerCamelCase : List[Any]=0.1 , lowerCamelCase : Union[str, Any]=0.1 , lowerCamelCase : Optional[Any]=5_12 , lowerCamelCase : List[Any]=2 , lowerCamelCase : int=0.02 , lowerCamelCase : Union[str, Any]=1e-1_2 , lowerCamelCase : int=0 , lowerCamelCase : List[str]="absolute" , lowerCamelCase : int = 0 , **lowerCamelCase : List[Any] , ): """simple docstring""" super().__init__(pad_token_id=lowerCamelCase , **lowerCamelCase ) __A : Dict = vocab_size __A : int = hidden_size __A : str = num_hidden_layers __A : Union[str, Any] = num_attention_heads __A : Union[str, Any] = hidden_act __A : Optional[Any] = intermediate_size __A : str = hidden_dropout_prob __A : int = attention_probs_dropout_prob __A : int = max_position_embeddings __A : Dict = type_vocab_size __A : Dict = initializer_range __A : Union[str, Any] = layer_norm_eps __A : int = projection_dim __A : List[Any] = position_embedding_type
499
0
"""simple docstring""" def __A ( a_ :List[Any]) -> Optional[int]: __a , __a : int = [], [] while len(a_) > 1: __a , __a : Any = min(a_), max(a_) start.append(a_) end.append(a_) collection.remove(a_) collection.remove(a_) end.reverse() return start + collection + end if __name__ == "__main__": A = input('''Enter numbers separated by a comma:\n''').strip() A = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
52
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class __A ( unittest.TestCase ): '''simple docstring''' def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = '''hf-internal-testing/tiny-random-t5''' lowerCamelCase__ = AutoTokenizer.from_pretrained(__lowerCAmelCase ) lowerCamelCase__ = AutoModelForSeqaSeqLM.from_pretrained(__lowerCAmelCase ) lowerCamelCase__ = tokenizer('''This is me''' , return_tensors='''pt''' ) lowerCamelCase__ = model.to_bettertransformer() self.assertTrue(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) lowerCamelCase__ = model.generate(**__lowerCAmelCase ) lowerCamelCase__ = model.reverse_bettertransformer() self.assertFalse(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowerCAmelCase ) lowerCamelCase__ = AutoModelForSeqaSeqLM.from_pretrained(__lowerCAmelCase ) self.assertFalse( any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) lowerCamelCase__ = model_reloaded.generate(**__lowerCAmelCase ) self.assertTrue(torch.allclose(__lowerCAmelCase , __lowerCAmelCase ) ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = '''hf-internal-testing/tiny-random-t5''' lowerCamelCase__ = AutoModelForSeqaSeqLM.from_pretrained(__lowerCAmelCase ) lowerCamelCase__ = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__lowerCAmelCase ): model.save_pretrained(__lowerCAmelCase ) lowerCamelCase__ = model.reverse_bettertransformer() model.save_pretrained(__lowerCAmelCase )
481
0
from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=1e-12 ): '''simple docstring''' UpperCAmelCase = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(lowerCAmelCase , axis=1 ) , a_min=lowerCAmelCase ) ).T UpperCAmelCase = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(lowerCAmelCase , axis=1 ) , a_min=lowerCAmelCase ) ).T return jnp.matmul(lowerCAmelCase , norm_emb_a.T ) class UpperCamelCase_ ( nn.Module ): _A : CLIPConfig _A : jnp.dtype = jnp.floataa def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" UpperCAmelCase = FlaxCLIPVisionModule(self.config.vision_config ) UpperCAmelCase = nn.Dense(self.config.projection_dim , use_bias=snake_case__ , dtype=self.dtype ) UpperCAmelCase = self.param("""concept_embeds""" , jax.nn.initializers.ones , (17, self.config.projection_dim) ) UpperCAmelCase = self.param( """special_care_embeds""" , jax.nn.initializers.ones , (3, self.config.projection_dim) ) UpperCAmelCase = self.param("""concept_embeds_weights""" , jax.nn.initializers.ones , (17,) ) UpperCAmelCase = self.param("""special_care_embeds_weights""" , jax.nn.initializers.ones , (3,) ) def __call__( self , snake_case__ ) -> Any: """simple docstring""" UpperCAmelCase = self.vision_model(snake_case__ )[1] UpperCAmelCase = self.visual_projection(snake_case__ ) UpperCAmelCase = jax_cosine_distance(snake_case__ , self.special_care_embeds ) UpperCAmelCase = jax_cosine_distance(snake_case__ , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs UpperCAmelCase = 0.0 UpperCAmelCase = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment UpperCAmelCase = jnp.round(snake_case__ , 3 ) UpperCAmelCase = jnp.any(special_scores > 0 , axis=1 , keepdims=snake_case__ ) # Use a lower threshold if an image has any special care concept UpperCAmelCase = is_special_care * 0.01 UpperCAmelCase = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment UpperCAmelCase = jnp.round(snake_case__ , 3 ) UpperCAmelCase = jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class UpperCamelCase_ ( a_ ): _A : str = CLIPConfig _A : List[Any] = 'clip_input' _A : Dict = FlaxStableDiffusionSafetyCheckerModule def __init__( self , snake_case__ , snake_case__ = None , snake_case__ = 0 , snake_case__ = jnp.floataa , snake_case__ = True , **snake_case__ , ) -> Optional[int]: """simple docstring""" if input_shape is None: UpperCAmelCase = (1, 2_24, 2_24, 3) UpperCAmelCase = self.module_class(config=snake_case__ , dtype=snake_case__ , **snake_case__ ) super().__init__(snake_case__ , snake_case__ , input_shape=snake_case__ , seed=snake_case__ , dtype=snake_case__ , _do_init=_do_init ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ = None ) -> FrozenDict: """simple docstring""" UpperCAmelCase = jax.random.normal(snake_case__ , snake_case__ ) UpperCAmelCase , UpperCAmelCase = jax.random.split(snake_case__ ) UpperCAmelCase = {"""params""": params_rng, """dropout""": dropout_rng} UpperCAmelCase = self.module.init(snake_case__ , snake_case__ )["""params"""] return random_params def __call__( self , snake_case__ , snake_case__ = None , ) -> Optional[int]: """simple docstring""" UpperCAmelCase = jnp.transpose(snake_case__ , (0, 2, 3, 1) ) return self.module.apply( {"""params""": params or self.params} , jnp.array(snake_case__ , dtype=jnp.floataa ) , rngs={} , )
715
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase_ : Optional[int] = { '''configuration_graphormer''': ['''GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GraphormerConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ : str = [ '''GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GraphormerForGraphClassification''', '''GraphormerModel''', '''GraphormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys lowerCAmelCase_ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
378
0
import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> List[Any]: _lowercase : Optional[int] = WavaVecaForSequenceClassification.from_pretrained(__lowerCAmelCase , config=__lowerCAmelCase ) _lowercase : str = downstream_dict['projector.weight'] _lowercase : Dict = downstream_dict['projector.bias'] _lowercase : Optional[Any] = downstream_dict['model.post_net.linear.weight'] _lowercase : Union[str, Any] = downstream_dict['model.post_net.linear.bias'] return model def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Optional[int]: _lowercase : Dict = WavaVecaForAudioFrameClassification.from_pretrained(__lowerCAmelCase , config=__lowerCAmelCase ) _lowercase : Tuple = downstream_dict['model.linear.weight'] _lowercase : int = downstream_dict['model.linear.bias'] return model def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> str: _lowercase : List[Any] = WavaVecaForXVector.from_pretrained(__lowerCAmelCase , config=__lowerCAmelCase ) _lowercase : Optional[int] = downstream_dict['connector.weight'] _lowercase : Union[str, Any] = downstream_dict['connector.bias'] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): _lowercase : Optional[Any] = downstream_dict[ F'''model.framelevel_feature_extractor.module.{i}.kernel.weight''' ] _lowercase : Tuple = downstream_dict[F'''model.framelevel_feature_extractor.module.{i}.kernel.bias'''] _lowercase : Optional[int] = downstream_dict['model.utterancelevel_feature_extractor.linear1.weight'] _lowercase : Optional[int] = downstream_dict['model.utterancelevel_feature_extractor.linear1.bias'] _lowercase : Union[str, Any] = downstream_dict['model.utterancelevel_feature_extractor.linear2.weight'] _lowercase : Tuple = downstream_dict['model.utterancelevel_feature_extractor.linear2.bias'] _lowercase : List[str] = downstream_dict['objective.W'] return model @torch.no_grad() def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Union[str, Any]: _lowercase : Dict = torch.load(__lowerCAmelCase , map_location='cpu' ) _lowercase : Optional[Any] = checkpoint['Downstream'] _lowercase : Any = WavaVecaConfig.from_pretrained(__lowerCAmelCase ) _lowercase : List[Any] = WavaVecaFeatureExtractor.from_pretrained( __lowerCAmelCase , return_attention_mask=__lowerCAmelCase , do_normalize=__lowerCAmelCase ) _lowercase : Tuple = hf_config.architectures[0] if arch.endswith('ForSequenceClassification' ): _lowercase : int = convert_classification(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) elif arch.endswith('ForAudioFrameClassification' ): _lowercase : Tuple = convert_diarization(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) elif arch.endswith('ForXVector' ): _lowercase : str = convert_xvector(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) else: raise NotImplementedError(F'''S3PRL weights conversion is not supported for {arch}''' ) if hf_config.use_weighted_layer_sum: _lowercase : List[str] = checkpoint['Featurizer']['weights'] hf_feature_extractor.save_pretrained(__lowerCAmelCase ) hf_model.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument( "--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model." ) parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.") parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.") SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
89
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : List[str] = { "facebook/timesformer": "https://huggingface.co/facebook/timesformer/resolve/main/config.json", } class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ): lowercase__ = "timesformer" def __init__( self : int , lowerCAmelCase_ : Dict=2_2_4 , lowerCAmelCase_ : Any=1_6 , lowerCAmelCase_ : Union[str, Any]=3 , lowerCAmelCase_ : Union[str, Any]=8 , lowerCAmelCase_ : Dict=7_6_8 , lowerCAmelCase_ : Dict=1_2 , lowerCAmelCase_ : Optional[int]=1_2 , lowerCAmelCase_ : str=3_0_7_2 , lowerCAmelCase_ : Dict="gelu" , lowerCAmelCase_ : Dict=0.0 , lowerCAmelCase_ : int=0.0 , lowerCAmelCase_ : Any=0.02 , lowerCAmelCase_ : List[str]=1E-6 , lowerCAmelCase_ : Union[str, Any]=True , lowerCAmelCase_ : Optional[int]="divided_space_time" , lowerCAmelCase_ : Optional[Any]=0 , **lowerCAmelCase_ : Dict , ): """simple docstring""" super().__init__(**lowerCAmelCase_) lowercase_ = image_size lowercase_ = patch_size lowercase_ = num_channels lowercase_ = num_frames lowercase_ = hidden_size lowercase_ = num_hidden_layers lowercase_ = num_attention_heads lowercase_ = intermediate_size lowercase_ = hidden_act lowercase_ = hidden_dropout_prob lowercase_ = attention_probs_dropout_prob lowercase_ = initializer_range lowercase_ = layer_norm_eps lowercase_ = qkv_bias lowercase_ = attention_type lowercase_ = drop_path_rate
567
0
import requests __lowerCAmelCase : Dict = "YOUR API KEY" def lowerCAmelCase ( UpperCamelCase__ : str , UpperCamelCase__ : str = giphy_api_key ): """simple docstring""" __UpperCAmelCase = '''+'''.join(query.split() ) __UpperCAmelCase = f"""https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}""" __UpperCAmelCase = requests.get(UpperCamelCase__ ).json()['''data'''] return [gif["url"] for gif in gifs] if __name__ == "__main__": print("\n".join(get_gifs("space ship")))
701
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva __lowerCAmelCase : Any = "" __lowerCAmelCase : int = "" __lowerCAmelCase : Union[str, Any] = "" __lowerCAmelCase : Any = 1 # (0 is vertical, 1 is horizontal) def lowerCAmelCase ( ): """simple docstring""" __UpperCAmelCase , __UpperCAmelCase = get_dataset(UpperCamelCase__ , UpperCamelCase__ ) print('''Processing...''' ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = update_image_and_anno(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for index, image in enumerate(UpperCamelCase__ ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __UpperCAmelCase = random_chars(3_2 ) __UpperCAmelCase = paths[index].split(os.sep )[-1].rsplit('''.''' , 1 )[0] __UpperCAmelCase = f"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(f"""/{file_root}.jpg""" , UpperCamelCase__ , [cva.IMWRITE_JPEG_QUALITY, 8_5] ) print(f"""Success {index+1}/{len(UpperCamelCase__ )} with {file_name}""" ) __UpperCAmelCase = [] for anno in new_annos[index]: __UpperCAmelCase = f"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(UpperCamelCase__ ) with open(f"""/{file_root}.txt""" , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def lowerCAmelCase ( UpperCamelCase__ : str , UpperCamelCase__ : str ): """simple docstring""" __UpperCAmelCase = [] __UpperCAmelCase = [] for label_file in glob.glob(os.path.join(UpperCamelCase__ , '''*.txt''' ) ): __UpperCAmelCase = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(UpperCamelCase__ ) as in_file: __UpperCAmelCase = in_file.readlines() __UpperCAmelCase = os.path.join(UpperCamelCase__ , f"""{label_name}.jpg""" ) __UpperCAmelCase = [] for obj_list in obj_lists: __UpperCAmelCase = obj_list.rstrip('''\n''' ).split(''' ''' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(UpperCamelCase__ ) labels.append(UpperCamelCase__ ) return img_paths, labels def lowerCAmelCase ( UpperCamelCase__ : list , UpperCamelCase__ : list , UpperCamelCase__ : int = 1 ): """simple docstring""" __UpperCAmelCase = [] __UpperCAmelCase = [] __UpperCAmelCase = [] for idx in range(len(UpperCamelCase__ ) ): __UpperCAmelCase = [] __UpperCAmelCase = img_list[idx] path_list.append(UpperCamelCase__ ) __UpperCAmelCase = anno_list[idx] __UpperCAmelCase = cva.imread(UpperCamelCase__ ) if flip_type == 1: __UpperCAmelCase = cva.flip(UpperCamelCase__ , UpperCamelCase__ ) for bbox in img_annos: __UpperCAmelCase = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __UpperCAmelCase = cva.flip(UpperCamelCase__ , UpperCamelCase__ ) for bbox in img_annos: __UpperCAmelCase = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(UpperCamelCase__ ) new_imgs_list.append(UpperCamelCase__ ) return new_imgs_list, new_annos_lists, path_list def lowerCAmelCase ( UpperCamelCase__ : int = 3_2 ): """simple docstring""" assert number_char > 1, "The number of character should greater than 1" __UpperCAmelCase = ascii_lowercase + digits return "".join(random.choice(UpperCamelCase__ ) for _ in range(UpperCamelCase__ ) ) if __name__ == "__main__": main() print("DONE ✅")
654
0
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class a ( UpperCAmelCase__ ): """simple docstring""" def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> str: super().__init__() self.register_modules(vqvae=_a , unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , lowerCAmelCase_ = 1 , lowerCAmelCase_ = None , lowerCAmelCase_ = 0.0 , lowerCAmelCase_ = 50 , lowerCAmelCase_ = "pil" , lowerCAmelCase_ = True , **lowerCAmelCase_ , ) -> Optional[Any]: _A = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=_a , ) _A = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler _A = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_a ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature _A = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) _A = {} if accepts_eta: _A = eta for t in self.progress_bar(self.scheduler.timesteps ): _A = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual _A = self.unet(_a , _a ).sample # compute the previous noisy sample x_t -> x_t-1 _A = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # decode the image latents with the VAE _A = self.vqvae.decode(_a ).sample _A = (image / 2 + 0.5).clamp(0 , 1 ) _A = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _A = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
401
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels lowerCAmelCase : List[str] = object() # For specifying empty leaf dict `{}` lowerCAmelCase : Any = object() def a__ ( snake_case__ , snake_case__ ) -> List[Any]: lowerCamelCase = tuple((re.compile(x + """$""" ) for x in qs) ) for i in range(len(snake_case__ ) - len(snake_case__ ) + 1 ): lowerCamelCase = [x.match(snake_case__ ) for x, y in zip(snake_case__ , ks[i:] )] if matches and all(snake_case__ ): return True return False def a__ ( snake_case__ ) -> str: def replace(snake_case__ , snake_case__ ): for rule, replacement in rules: if _match(snake_case__ , snake_case__ ): return replacement return val return replace def a__ ( ) -> Union[str, Any]: return [ # embeddings (("transformer", "wpe", "embedding"), P("""mp""" , snake_case__ )), (("transformer", "wte", "embedding"), P("""mp""" , snake_case__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(snake_case__ , """mp""" )), (("attention", "out_proj", "kernel"), P("""mp""" , snake_case__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(snake_case__ , """mp""" )), (("mlp", "c_fc", "bias"), P("""mp""" )), (("mlp", "c_proj", "kernel"), P("""mp""" , snake_case__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def a__ ( snake_case__ ) -> Optional[Any]: lowerCamelCase = _get_partition_rules() lowerCamelCase = _replacement_rules(snake_case__ ) lowerCamelCase = {k: _unmatched for k in flatten_dict(snake_case__ )} lowerCamelCase = {k: replace(snake_case__ , snake_case__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(snake_case__ ) )
543
0
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def UpperCamelCase_ ( a_ ) ->Union[str, Any]: if not is_accelerate_available(): return method A =version.parse(accelerate.__version__ ).base_version if version.parse(a_ ) < version.parse("0.17.0" ): return method def wrapper(self , *a_ , **a_ ): if hasattr(self , "_hf_hook" ) and hasattr(self._hf_hook , "pre_forward" ): self._hf_hook.pre_forward(self ) return method(self , *a_ , **a_ ) return wrapper
689
def UpperCamelCase_ ( a_ = 6008_5147_5143 ) ->int: try: A =int(a_ ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) A =2 A =0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 A =i while n % i == 0: A =n // i i += 1 return int(a_ ) if __name__ == "__main__": print(F'''{solution() = }''')
689
1
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_pegasus import PegasusTokenizer else: lowercase__ = None lowercase__ = logging.get_logger(__name__) lowercase__ = """▁""" lowercase__ = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} lowercase__ = { """vocab_file""": {"""google/pegasus-xsum""": """https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"""}, """tokenizer_file""": { """google/pegasus-xsum""": """https://huggingface.co/google/pegasus-xsum/resolve/main/tokenizer.json""" }, } lowercase__ = { """google/pegasus-xsum""": 512, } class lowerCAmelCase__ ( lowercase ): '''simple docstring''' lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = PegasusTokenizer lowerCamelCase__ = ["""input_ids""", """attention_mask"""] def __init__( self , lowercase=None , lowercase=None , lowercase="<pad>" , lowercase="</s>" , lowercase="<unk>" , lowercase="<mask_2>" , lowercase="<mask_1>" , lowercase=None , lowercase=103 , **lowercase , ): _lowerCamelCase : List[Any] = offset if additional_special_tokens is not None: if not isinstance(lowercase , lowercase ): raise TypeError( F'''additional_special_tokens should be of type {type(lowercase )}, but is''' F''' {type(lowercase )}''' ) _lowerCamelCase : Tuple = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ F'''<unk_{i}>''' for i in range(len(lowercase ) , self.offset - 1 ) ] if len(set(lowercase ) ) != len(lowercase ): raise ValueError( 'Please make sure that the provided additional_special_tokens do not contain an incorrectly' F''' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.''' ) _lowerCamelCase : List[Any] = additional_special_tokens_extended else: _lowerCamelCase : Dict = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F'''<unk_{i}>''' for i in range(2 , self.offset )] super().__init__( lowercase , tokenizer_file=lowercase , pad_token=lowercase , eos_token=lowercase , unk_token=lowercase , mask_token=lowercase , mask_token_sent=lowercase , offset=lowercase , additional_special_tokens=lowercase , **lowercase , ) _lowerCamelCase : str = vocab_file _lowerCamelCase : Optional[Any] = False if not self.vocab_file else True def A_ ( self , lowercase ): _lowerCamelCase : Dict = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special if all_special_ids != set(range(len(self.additional_special_tokens ) + 3 ) ): raise ValueError( 'There should be 3 special tokens: mask_token, pad_token, and eos_token +' F''' {len(self.additional_special_tokens )} additional_special_tokens, but got {all_special_ids}''' ) return [1 if x in all_special_ids else 0 for x in seq] def A_ ( self , lowercase , lowercase = None , lowercase = False ): if already_has_special_tokens: return self._special_token_mask(lowercase ) elif token_ids_a is None: return self._special_token_mask(lowercase ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def A_ ( self , lowercase , lowercase=None ): if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def A_ ( self , lowercase , lowercase = None ): if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(lowercase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return _lowerCamelCase : Optional[int] = os.path.join( lowercase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase ): copyfile(self.vocab_file , lowercase ) return (out_vocab_file,)
630
"""simple docstring""" import operator as op def _snake_case ( lowercase__ ): _lowerCamelCase : Dict = [] _lowerCamelCase : List[str] = lambda lowercase__ , lowercase__ : int(x / y ) # noqa: E731 integer division operation _lowerCamelCase : Optional[int] = { '^': op.pow, '*': op.mul, '/': div, '+': op.add, '-': op.sub, } # operators & their respective operation # print table header print('Symbol'.center(8 ) , 'Action'.center(12 ) , 'Stack' , sep=' | ' ) print('-' * (30 + len(lowercase__ )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(lowercase__ ) # append x to stack # output in tabular format print(x.rjust(8 ) , ('push(' + x + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' ) else: _lowerCamelCase : int = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + b + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' ) _lowerCamelCase : Tuple = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + a + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' ) stack.append( str(opr[x](int(lowercase__ ) , int(lowercase__ ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ('push(' + a + x + b + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' , ) return int(stack[0] ) if __name__ == "__main__": lowercase__ = input("""\n\nEnter a Postfix Equation (space separated) = """).split(""" """) print("""\n\tResult = """, solve(Postfix))
630
1
'''simple docstring''' import cmath import math def lowerCAmelCase ( UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple ): """simple docstring""" __UpperCAmelCase = math.radians(SCREAMING_SNAKE_CASE_ ) __UpperCAmelCase = math.radians(SCREAMING_SNAKE_CASE_ ) # Convert voltage and current to rectangular form __UpperCAmelCase = cmath.rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __UpperCAmelCase = cmath.rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
703
'''simple docstring''' def lowerCAmelCase ( UpperCamelCase__ : int ): """simple docstring""" if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): __UpperCAmelCase = f"""Input value of [number={number}] must be an integer""" raise TypeError(UpperCamelCase__ ) if number < 1: __UpperCAmelCase = f"""Input value of [number={number}] must be > 0""" raise ValueError(UpperCamelCase__ ) __UpperCAmelCase = 1 for i in range(1 , UpperCamelCase__ ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
654
0
def UpperCAmelCase__ ( __magic_name__ : Dict , __magic_name__ : Tuple ): '''simple docstring''' lowerCAmelCase : Optional[Any] = 0 lowerCAmelCase : Any = len(__magic_name__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None lowerCAmelCase : Union[str, Any] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(__magic_name__ ): return None lowerCAmelCase : Union[str, Any] = sorted_collection[point] if current_item == item: return point else: if point < left: lowerCAmelCase : int = left lowerCAmelCase : Any = point elif point > right: lowerCAmelCase : Optional[int] = right lowerCAmelCase : List[Any] = point else: if item < current_item: lowerCAmelCase : List[Any] = point - 1 else: lowerCAmelCase : int = point + 1 return None def UpperCAmelCase__ ( __magic_name__ : Dict , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : Optional[int] ): '''simple docstring''' if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None lowerCAmelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(__magic_name__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) elif point > right: return interpolation_search_by_recursion(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( __magic_name__ , __magic_name__ , __magic_name__ , point - 1 ) else: return interpolation_search_by_recursion( __magic_name__ , __magic_name__ , point + 1 , __magic_name__ ) def UpperCAmelCase__ ( __magic_name__ : Dict ): '''simple docstring''' if collection != sorted(__magic_name__ ): raise ValueError('''Collection must be ascending sorted''' ) return True if __name__ == "__main__": import sys __SCREAMING_SNAKE_CASE : Optional[int] = 0 if debug == 1: __SCREAMING_SNAKE_CASE : Union[str, Any] = [10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') __SCREAMING_SNAKE_CASE : Any = 67 __SCREAMING_SNAKE_CASE : List[Any] = interpolation_search(collection, target) if result is not None: print(f"""{target} found at positions: {result}""") else: print('Not found')
348
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __SCREAMING_SNAKE_CASE : str = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : List[Any] = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Any = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : int = [ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
348
1
"""simple docstring""" import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets __snake_case = '''\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } ''' __snake_case = '''\ This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset. It first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy. ''' __snake_case = r''' Calculates accuracy after canonicalizing inputs. Args: predictions: list of predictions to score. Each prediction is a string that contains natural language and LaTex. references: list of reference for each prediction. Each reference is a string that contains natural language and LaTex. Returns: accuracy: accuracy after canonicalizing inputs (e.g., converting "1/2" to "\\frac{1}{2}") Examples: >>> metric = datasets.load_metric("competition_math") >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"]) >>> print(results) {\'accuracy\': 1.0} ''' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCamelCase ( datasets.Metric ): def _UpperCAmelCase ( self ) -> int: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' ), '''references''': datasets.Value('''string''' ), } ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase ) -> int: _a = 0.0 for i, j in zip(__UpperCAmelCase , __UpperCAmelCase ): n_correct += 1.0 if math_equivalence.is_equiv(__UpperCAmelCase , __UpperCAmelCase ) else 0.0 _a = n_correct / len(__UpperCAmelCase ) return { "accuracy": accuracy, }
710
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __snake_case = logging.get_logger(__name__) class __lowerCamelCase ( a__ ): '''simple docstring''' A_ : Any = ['pixel_values'] def __init__( self , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = PILImageResampling.BILINEAR , __UpperCAmelCase = True , __UpperCAmelCase = 1 / 255 , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> None: super().__init__(**__UpperCAmelCase ) _a = size if size is not None else {'''shortest_edge''': 384} _a = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) _a = do_resize _a = size # Default value set here for backwards compatibility where the value in config is None _a = crop_pct if crop_pct is not None else 224 / 256 _a = resample _a = do_rescale _a = rescale_factor _a = do_normalize _a = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _a = image_std if image_std is not None else IMAGENET_STANDARD_STD def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = PILImageResampling.BICUBIC , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: _a = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) if "shortest_edge" not in size: raise ValueError(F'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) _a = size['''shortest_edge'''] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct _a = int(shortest_edge / crop_pct ) _a = get_resize_output_image_size(__UpperCAmelCase , size=__UpperCAmelCase , default_to_square=__UpperCAmelCase ) _a = resize(image=__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=__UpperCAmelCase , size=(shortest_edge, shortest_edge) , data_format=__UpperCAmelCase , **__UpperCAmelCase ) else: # warping (no cropping) when evaluated at 384 or larger return resize( __UpperCAmelCase , size=(shortest_edge, shortest_edge) , resample=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> Optional[int]: return rescale(__UpperCAmelCase , scale=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: return normalize(__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , **__UpperCAmelCase , ) -> PIL.Image.Image: _a = do_resize if do_resize is not None else self.do_resize _a = crop_pct if crop_pct is not None else self.crop_pct _a = resample if resample is not None else self.resample _a = do_rescale if do_rescale is not None else self.do_rescale _a = rescale_factor if rescale_factor is not None else self.rescale_factor _a = do_normalize if do_normalize is not None else self.do_normalize _a = image_mean if image_mean is not None else self.image_mean _a = image_std if image_std is not None else self.image_std _a = size if size is not None else self.size _a = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) _a = make_list_of_images(__UpperCAmelCase ) if not valid_images(__UpperCAmelCase ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError('''crop_pct must be specified if size < 384.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. _a = [to_numpy_array(__UpperCAmelCase ) for image in images] if do_resize: _a = [self.resize(image=__UpperCAmelCase , size=__UpperCAmelCase , crop_pct=__UpperCAmelCase , resample=__UpperCAmelCase ) for image in images] if do_rescale: _a = [self.rescale(image=__UpperCAmelCase , scale=__UpperCAmelCase ) for image in images] if do_normalize: _a = [self.normalize(image=__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase ) for image in images] _a = [to_channel_dimension_format(__UpperCAmelCase , __UpperCAmelCase ) for image in images] _a = {'''pixel_values''': images} return BatchFeature(data=__UpperCAmelCase , tensor_type=__UpperCAmelCase )
285
0
import math import os import sys def UpperCamelCase ( __magic_name__ : str ) -> str: """simple docstring""" lowercase__ = """""" try: with open(__magic_name__ , """rb""" ) as binary_file: lowercase__ = binary_file.read() for dat in data: lowercase__ = f'''{dat:08b}''' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def UpperCamelCase ( __magic_name__ : dict[str, str] , __magic_name__ : str , __magic_name__ : int , __magic_name__ : str ) -> None: """simple docstring""" lexicon.pop(__magic_name__ ) lowercase__ = last_match_id if math.loga(__magic_name__ ).is_integer(): for curr_key in lexicon: lowercase__ = """0""" + lexicon[curr_key] lowercase__ = bin(__magic_name__ )[2:] def UpperCamelCase ( __magic_name__ : str ) -> str: """simple docstring""" lowercase__ = {"""0""": """0""", """1""": """1"""} lowercase__ , lowercase__ = """""", """""" lowercase__ = len(__magic_name__ ) for i in range(len(__magic_name__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue lowercase__ = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) index += 1 lowercase__ = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": lowercase__ = lexicon[curr_string] result += last_match_id return result def UpperCamelCase ( __magic_name__ : str , __magic_name__ : str ) -> str: """simple docstring""" lowercase__ = os.path.getsize(__magic_name__ ) lowercase__ = bin(__magic_name__ )[2:] lowercase__ = len(__magic_name__ ) return "0" * (length_length - 1) + file_length_binary + compressed def UpperCamelCase ( __magic_name__ : str , __magic_name__ : str ) -> None: """simple docstring""" lowercase__ = 8 try: with open(__magic_name__ , """wb""" ) as opened_file: lowercase__ = [ to_write[i : i + byte_length] for i in range(0 , len(__magic_name__ ) , __magic_name__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__magic_name__ , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def UpperCamelCase ( __magic_name__ : str , __magic_name__ : str ) -> None: """simple docstring""" lowercase__ = read_file_binary(__magic_name__ ) lowercase__ = compress_data(__magic_name__ ) lowercase__ = add_file_length(__magic_name__ , __magic_name__ ) write_file_binary(__magic_name__ , __magic_name__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
15
def SCREAMING_SNAKE_CASE ( snake_case , snake_case = False ) -> str: if not isinstance(snake_case , snake_case ): __lowercase = F"Expected string as input, found {type(snake_case )}" raise ValueError(snake_case ) if not isinstance(snake_case , snake_case ): __lowercase = F"Expected boolean as use_pascal parameter, found {type(snake_case )}" raise ValueError(snake_case ) __lowercase = input_str.split('_' ) __lowercase = 0 if use_pascal else 1 __lowercase = words[start_index:] __lowercase = [word[0].upper() + word[1:] for word in words_to_capitalize] __lowercase = '' if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
375
0
"""simple docstring""" from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record lowercase__ : Tuple = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' lowercase__ : Optional[Any] = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' lowercase__ : str = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def __lowercase ( _a , _a ): return float((preds == labels).mean() ) def __lowercase ( _a , _a , _a="binary" ): snake_case_ : List[Any] = simple_accuracy(_a , _a ) snake_case_ : List[str] = float(fa_score(y_true=_a , y_pred=_a , average=_a ) ) return { "accuracy": acc, "f1": fa, } def __lowercase ( _a , _a ): snake_case_ : Any = {} for id_pred, label in zip(_a , _a ): snake_case_ : Union[str, Any] = f"{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}" snake_case_ : int = id_pred['''prediction'''] if question_id in question_map: question_map[question_id].append((pred, label) ) else: snake_case_ : List[str] = [(pred, label)] snake_case_, snake_case_ : str = [], [] for question, preds_labels in question_map.items(): snake_case_, snake_case_ : List[Any] = zip(*_a ) snake_case_ : List[Any] = fa_score(y_true=_a , y_pred=_a , average='''macro''' ) fas.append(_a ) snake_case_ : int = int(sum(pred == label for pred, label in preds_labels ) == len(_a ) ) ems.append(_a ) snake_case_ : Union[str, Any] = float(sum(_a ) / len(_a ) ) snake_case_ : str = sum(_a ) / len(_a ) snake_case_ : Union[str, Any] = float(fa_score(y_true=_a , y_pred=[id_pred['''prediction'''] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _UpperCAmelCase ( datasets.Metric): def _snake_case ( self : List[Any] ): if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' if not self.config_name == '''record''' and not self.config_name == '''multirc''' else None , ) def _snake_case ( self : Optional[Any] ): if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "prediction_text": datasets.Value('''string''' ), }, "references": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "answers": datasets.Sequence(datasets.Value('''string''' ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value('''int64''' ), "paragraph": datasets.Value('''int64''' ), "question": datasets.Value('''int64''' ), }, "prediction": datasets.Value('''int64''' ), }, "references": datasets.Value('''int64''' ), } else: return { "predictions": datasets.Value('''int64''' ), "references": datasets.Value('''int64''' ), } def _snake_case ( self : Optional[int] , lowercase_ : Dict , lowercase_ : Any ): if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(lowercase_ , lowercase_ )} elif self.config_name == "cb": return acc_and_fa(lowercase_ , lowercase_ , fa_avg='''macro''' ) elif self.config_name == "record": snake_case_ : Tuple = [ { '''qas''': [ {'''id''': ref['''idx''']['''query'''], '''answers''': [{'''text''': ans} for ans in ref['''answers''']]} for ref in references ] } ] snake_case_ : Union[str, Any] = {pred['''idx''']['''query''']: pred['''prediction_text'''] for pred in predictions} return evaluate_record(lowercase_ , lowercase_ )[0] elif self.config_name == "multirc": return evaluate_multirc(lowercase_ , lowercase_ ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(lowercase_ , lowercase_ )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' )
485
"""simple docstring""" from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _UpperCAmelCase ( lowerCAmelCase__): def _snake_case ( self : int ): snake_case_ : Any = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowercase_ , '''embed_dim''' ) ) self.parent.assertTrue(hasattr(lowercase_ , '''num_heads''' ) ) class _UpperCAmelCase : def __init__( self : List[str] , lowercase_ : Optional[Any] , lowercase_ : int=13 , lowercase_ : Optional[int]=64 , lowercase_ : Any=3 , lowercase_ : Any=[16, 48, 96] , lowercase_ : List[Any]=[1, 3, 6] , lowercase_ : Union[str, Any]=[1, 2, 10] , lowercase_ : Optional[Any]=[7, 3, 3] , lowercase_ : Union[str, Any]=[4, 2, 2] , lowercase_ : Tuple=[2, 1, 1] , lowercase_ : List[str]=[2, 2, 2] , lowercase_ : Union[str, Any]=[False, False, True] , lowercase_ : Optional[int]=[0.0, 0.0, 0.0] , lowercase_ : str=0.02 , lowercase_ : Optional[Any]=1E-12 , lowercase_ : Optional[int]=True , lowercase_ : Optional[int]=True , lowercase_ : Optional[Any]=2 , ): snake_case_ : List[Any] = parent snake_case_ : int = batch_size snake_case_ : Union[str, Any] = image_size snake_case_ : Tuple = patch_sizes snake_case_ : List[Any] = patch_stride snake_case_ : Dict = patch_padding snake_case_ : Any = is_training snake_case_ : Any = use_labels snake_case_ : str = num_labels snake_case_ : Optional[Any] = num_channels snake_case_ : Optional[Any] = embed_dim snake_case_ : int = num_heads snake_case_ : List[str] = stride_kv snake_case_ : Any = depth snake_case_ : Dict = cls_token snake_case_ : Dict = attention_drop_rate snake_case_ : int = initializer_range snake_case_ : Tuple = layer_norm_eps def _snake_case ( self : Dict ): snake_case_ : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ : str = None if self.use_labels: # create a random int32 tensor of given shape snake_case_ : Union[str, Any] = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ : Dict = self.get_config() return config, pixel_values, labels def _snake_case ( self : int ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def _snake_case ( self : int , lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] ): snake_case_ : Tuple = TFCvtModel(config=lowercase_ ) snake_case_ : Tuple = model(lowercase_ , training=lowercase_ ) snake_case_ : int = (self.image_size, self.image_size) snake_case_, snake_case_ : List[str] = image_size[0], image_size[1] for i in range(len(self.depth ) ): snake_case_ : str = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) snake_case_ : str = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def _snake_case ( self : Dict , lowercase_ : Tuple , lowercase_ : Union[str, Any] , lowercase_ : List[str] ): snake_case_ : int = self.num_labels snake_case_ : Any = TFCvtForImageClassification(lowercase_ ) snake_case_ : List[Any] = model(lowercase_ , labels=lowercase_ , training=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self : Any ): snake_case_ : Tuple = self.prepare_config_and_inputs() snake_case_, snake_case_, snake_case_ : List[str] = config_and_inputs snake_case_ : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class _UpperCAmelCase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase): _lowerCAmelCase : Optional[int] = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () _lowerCAmelCase : str = ( {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification} if is_tf_available() else {} ) _lowerCAmelCase : str = False _lowerCAmelCase : int = False _lowerCAmelCase : Tuple = False _lowerCAmelCase : int = False _lowerCAmelCase : int = False def _snake_case ( self : int ): snake_case_ : Optional[int] = TFCvtModelTester(self ) snake_case_ : str = TFCvtConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37 ) def _snake_case ( self : int ): self.config_tester.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() @unittest.skip(reason='''Cvt does not output attentions''' ) def _snake_case ( self : Any ): pass @unittest.skip(reason='''Cvt does not use inputs_embeds''' ) def _snake_case ( self : str ): pass @unittest.skip(reason='''Cvt does not support input and output embeddings''' ) def _snake_case ( self : Union[str, Any] ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , ) def _snake_case ( self : Tuple ): super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , ) @slow def _snake_case ( self : Tuple ): super().test_keras_fit() @unittest.skip(reason='''Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8''' ) def _snake_case ( self : List[str] ): snake_case_ : Optional[Any] = tf.keras.mixed_precision.Policy('''mixed_float16''' ) tf.keras.mixed_precision.set_global_policy(lowercase_ ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy('''float32''' ) def _snake_case ( self : int ): snake_case_, snake_case_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Dict = model_class(lowercase_ ) snake_case_ : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ : List[str] = [*signature.parameters.keys()] snake_case_ : int = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_ ) def _snake_case ( self : List[str] ): def check_hidden_states_output(lowercase_ : Optional[int] , lowercase_ : Union[str, Any] , lowercase_ : str ): snake_case_ : Any = model_class(lowercase_ ) snake_case_ : Optional[Any] = model(**self._prepare_for_class(lowercase_ , lowercase_ ) ) snake_case_ : Tuple = outputs.hidden_states snake_case_ : str = len(self.model_tester.depth ) self.assertEqual(len(lowercase_ ) , lowercase_ ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) snake_case_, snake_case_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Dict = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_ ) def _snake_case ( self : str ): snake_case_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) def _snake_case ( self : List[Any] ): snake_case_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_ ) @slow def _snake_case ( self : Optional[Any] ): for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : int = TFCvtModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) def __lowercase ( ): snake_case_ : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class _UpperCAmelCase ( unittest.TestCase): @cached_property def _snake_case ( self : List[Any] ): return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _snake_case ( self : Tuple ): snake_case_ : int = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) snake_case_ : Any = self.default_image_processor snake_case_ : Union[str, Any] = prepare_img() snake_case_ : int = image_processor(images=lowercase_ , return_tensors='''tf''' ) # forward pass snake_case_ : Tuple = model(**lowercase_ ) # verify the logits snake_case_ : Optional[Any] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , lowercase_ ) snake_case_ : Tuple = tf.constant([0.92_85, 0.90_15, -0.31_50] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , lowercase_ , atol=1E-4 ) )
485
1
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. a_ = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def __UpperCAmelCase ( __UpperCamelCase ): from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(__UpperCamelCase ) def __UpperCAmelCase ( __UpperCamelCase ): from diffusers.utils.testing_utils import pytest_terminal_summary_main __lowercase : str = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(__UpperCamelCase , id=__UpperCamelCase )
76
"""simple docstring""" from collections import deque class _a : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): lowerCamelCase__ = process_name # process name lowerCamelCase__ = arrival_time # arrival time of the process # completion time of finished process or last interrupted time lowerCamelCase__ = arrival_time lowerCamelCase__ = burst_time # remaining burst time lowerCamelCase__ = 0 # total time of the process wait in ready queue lowerCamelCase__ = 0 # time from arrival time to completion time class _a : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : deque[Process] , SCREAMING_SNAKE_CASE__ : int , ): # total number of mlfq's queues lowerCamelCase__ = number_of_queues # time slice of queues that round robin algorithm applied lowerCamelCase__ = time_slices # unfinished process is in this ready_queue lowerCamelCase__ = queue # current time lowerCamelCase__ = current_time # finished process is in this sequence queue lowerCamelCase__ = deque() def _UpperCamelCase ( self : List[str] ): lowerCamelCase__ = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def _UpperCamelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : list[Process] ): lowerCamelCase__ = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def _UpperCamelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : list[Process] ): lowerCamelCase__ = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def _UpperCamelCase ( self : Any , SCREAMING_SNAKE_CASE__ : list[Process] ): lowerCamelCase__ = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): completion_times.append(queue[i].stop_time ) return completion_times def _UpperCamelCase ( self : Any , SCREAMING_SNAKE_CASE__ : deque[Process] ): return [q.burst_time for q in queue] def _UpperCamelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Process ): process.waiting_time += self.current_time - process.stop_time return process.waiting_time def _UpperCamelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : deque[Process] ): lowerCamelCase__ = deque() # sequence deque of finished process while len(SCREAMING_SNAKE_CASE__ ) != 0: lowerCamelCase__ = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(SCREAMING_SNAKE_CASE__ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 lowerCamelCase__ = 0 # set the process's turnaround time because it is finished lowerCamelCase__ = self.current_time - cp.arrival_time # set the completion time lowerCamelCase__ = self.current_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE__ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE__ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def _UpperCamelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : deque[Process] , SCREAMING_SNAKE_CASE__ : int ): lowerCamelCase__ = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(SCREAMING_SNAKE_CASE__ ) ): lowerCamelCase__ = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(SCREAMING_SNAKE_CASE__ ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time lowerCamelCase__ = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(SCREAMING_SNAKE_CASE__ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished lowerCamelCase__ = 0 # set the finish time lowerCamelCase__ = self.current_time # update the process' turnaround time because it is finished lowerCamelCase__ = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE__ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE__ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def _UpperCamelCase ( self : Dict ): # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1 ): lowerCamelCase__ , lowerCamelCase__ = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest _snake_case = Process("P1", 0, 53) _snake_case = Process("P2", 0, 17) _snake_case = Process("P3", 0, 68) _snake_case = Process("P4", 0, 24) _snake_case = 3 _snake_case = [17, 25] _snake_case = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={"queue": deque([Pa, Pa, Pa, Pa])}) _snake_case = Process("P1", 0, 53) _snake_case = Process("P2", 0, 17) _snake_case = Process("P3", 0, 68) _snake_case = Process("P4", 0, 24) _snake_case = 3 _snake_case = [17, 25] _snake_case = deque([Pa, Pa, Pa, Pa]) _snake_case = MLFQ(number_of_queues, time_slices, queue, 0) _snake_case = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f"""waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print completion times of processes(P1, P2, P3, P4) print( f"""completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print total turnaround times of processes(P1, P2, P3, P4) print( f"""turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print sequence of finished processes print( f"""sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}""" )
510
0
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig lowercase_ = { '''susnato/ernie-m-base_pytorch''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json''', '''susnato/ernie-m-large_pytorch''': '''https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json''', } class SCREAMING_SNAKE_CASE ( __lowercase): """simple docstring""" lowercase : Optional[int] = 'ernie_m' lowercase : Dict[str, str] = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self , __A = 25_0002 , __A = 768 , __A = 12 , __A = 12 , __A = 3072 , __A = "gelu" , __A = 0.1 , __A = 0.1 , __A = 514 , __A = 0.02 , __A = 1 , __A = 1E-05 , __A=None , __A=False , __A=0.0 , **__A , ) -> Optional[Any]: super().__init__(pad_token_id=__A , **__A ) _lowerCAmelCase =vocab_size _lowerCAmelCase =hidden_size _lowerCAmelCase =num_hidden_layers _lowerCAmelCase =num_attention_heads _lowerCAmelCase =intermediate_size _lowerCAmelCase =hidden_act _lowerCAmelCase =hidden_dropout_prob _lowerCAmelCase =attention_probs_dropout_prob _lowerCAmelCase =max_position_embeddings _lowerCAmelCase =initializer_range _lowerCAmelCase =layer_norm_eps _lowerCAmelCase =classifier_dropout _lowerCAmelCase =is_decoder _lowerCAmelCase =act_dropout
708
'''simple docstring''' import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters lowercase_ = False lowercase_ = False def UpperCamelCase__ ( a__ ): '''simple docstring''' return TrainCommand(a__ ) class SCREAMING_SNAKE_CASE ( __lowercase): """simple docstring""" @staticmethod def UpperCamelCase__ ( __A ) -> Tuple: _lowerCAmelCase =parser.add_parser('train' , help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' , type=__A , required=__A , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , ) train_parser.add_argument( '--column_label' , type=__A , default=0 , help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' , type=__A , default=1 , help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' , type=__A , default=2 , help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' , type=__A , default='' , help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' , type=__A , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , ) train_parser.add_argument('--output' , type=__A , default='./' , help='path to saved the trained model.' ) train_parser.add_argument( '--task' , type=__A , default='text_classification' , help='Task to train the model on.' ) train_parser.add_argument( '--model' , type=__A , default='bert-base-uncased' , help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' , type=__A , default=32 , help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' , type=__A , default=64 , help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' , type=__A , default=3E-5 , help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' , type=__A , default=1E-08 , help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=__A ) def __init__( self , __A ) -> List[str]: _lowerCAmelCase =logging.get_logger('transformers-cli/training' ) _lowerCAmelCase ='tf' if is_tf_available() else 'torch' os.makedirs(args.output , exist_ok=__A ) _lowerCAmelCase =args.output _lowerCAmelCase =args.column_label _lowerCAmelCase =args.column_text _lowerCAmelCase =args.column_id self.logger.info(F'''Loading {args.task} pipeline for {args.model}''' ) if args.task == "text_classification": _lowerCAmelCase =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(F'''Loading dataset from {args.train_data}''' ) _lowerCAmelCase =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) _lowerCAmelCase =None if args.validation_data: self.logger.info(F'''Loading validation dataset from {args.validation_data}''' ) _lowerCAmelCase =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) _lowerCAmelCase =args.validation_split _lowerCAmelCase =args.train_batch_size _lowerCAmelCase =args.valid_batch_size _lowerCAmelCase =args.learning_rate _lowerCAmelCase =args.adam_epsilon def UpperCamelCase__ ( self ) -> List[str]: if self.framework == "tf": return self.run_tf() return self.run_torch() def UpperCamelCase__ ( self ) -> Union[str, Any]: raise NotImplementedError def UpperCamelCase__ ( self ) -> List[Any]: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
58
0
def SCREAMING_SNAKE_CASE_ ( snake_case__ ) -> list: if len(snake_case__ ) < 2: return collection def circle_sort_util(snake_case__ , snake_case__ , snake_case__ ) -> bool: lowerCAmelCase = False if low == high: return swapped lowerCAmelCase = low lowerCAmelCase = high while left < right: if collection[left] > collection[right]: lowerCAmelCase , lowerCAmelCase = ( collection[right], collection[left], ) lowerCAmelCase = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: lowerCAmelCase , lowerCAmelCase = ( collection[right + 1], collection[left], ) lowerCAmelCase = True lowerCAmelCase = low + int((high - low) / 2 ) lowerCAmelCase = circle_sort_util(snake_case__ , snake_case__ , snake_case__ ) lowerCAmelCase = circle_sort_util(snake_case__ , mid + 1 , snake_case__ ) return swapped or left_swap or right_swap lowerCAmelCase = True while is_not_sorted is True: lowerCAmelCase = circle_sort_util(snake_case__ , 0 , len(snake_case__ ) - 1 ) return collection if __name__ == "__main__": lowercase__ : List[str] = input('''Enter numbers separated by a comma:\n''').strip() lowercase__ : List[str] = [int(item) for item in user_input.split(''',''')] print(circle_sort(unsorted))
312
import os lowercase__ : List[str] = {'''I''': 1, '''V''': 5, '''X''': 1_0, '''L''': 5_0, '''C''': 1_0_0, '''D''': 5_0_0, '''M''': 1_0_0_0} def SCREAMING_SNAKE_CASE_ ( snake_case__ ) -> int: lowerCAmelCase = 0 lowerCAmelCase = 0 while index < len(snake_case__ ) - 1: lowerCAmelCase = SYMBOLS[numerals[index]] lowerCAmelCase = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def SCREAMING_SNAKE_CASE_ ( snake_case__ ) -> str: lowerCAmelCase = '''''' lowerCAmelCase = num // 1_0_0_0 numerals += m_count * "M" num %= 1_0_0_0 lowerCAmelCase = num // 1_0_0 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_0_0 lowerCAmelCase = num // 1_0 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 1_0 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def SCREAMING_SNAKE_CASE_ ( snake_case__ = "/p089_roman.txt" ) -> int: lowerCAmelCase = 0 with open(os.path.dirname(snake_case__ ) + roman_numerals_filename ) as filea: lowerCAmelCase = filea.readlines() for line in lines: lowerCAmelCase = line.strip() lowerCAmelCase = parse_roman_numerals(snake_case__ ) lowerCAmelCase = generate_roman_numerals(snake_case__ ) savings += len(snake_case__ ) - len(snake_case__ ) return savings if __name__ == "__main__": print(f'{solution() = }')
312
1
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) lowercase = logging.getLogger(__name__) lowercase = '''Hello world! cécé herlolip''' lowercase = namedtuple( '''BertAbsConfig''', [ '''temp_dir''', '''large''', '''use_bert_emb''', '''finetune_bert''', '''encoder''', '''share_emb''', '''max_pos''', '''enc_layers''', '''enc_hidden_size''', '''enc_heads''', '''enc_ff_size''', '''enc_dropout''', '''dec_layers''', '''dec_hidden_size''', '''dec_heads''', '''dec_ff_size''', '''dec_dropout''', ], ) def UpperCAmelCase_ ( lowercase__ , lowercase__ ): '''simple docstring''' a_ =BertAbsConfig( temp_dir="." , finetune_bert=lowercase__ , large=lowercase__ , share_emb=lowercase__ , use_bert_emb=lowercase__ , encoder="bert" , max_pos=5_1_2 , enc_layers=6 , enc_hidden_size=5_1_2 , enc_heads=8 , enc_ff_size=5_1_2 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_6_8 , dec_heads=8 , dec_ff_size=2_0_4_8 , dec_dropout=0.2 , ) a_ =torch.load(lowercase__ , lambda lowercase__ , lowercase__ : storage ) a_ =AbsSummarizer(lowercase__ , torch.device("cpu" ) , lowercase__ ) original.eval() a_ =BertAbsSummarizer(lowercase__ , torch.device("cpu" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("convert the model" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("Make sure that the models' outputs are identical" ) a_ =BertTokenizer.from_pretrained("bert-base-uncased" ) # prepare the model inputs a_ =tokenizer.encode("This is sample éàalj'-." ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(lowercase__ )) ) a_ =torch.tensor(lowercase__ ).unsqueeze(0 ) a_ =tokenizer.encode("This is sample 3 éàalj'-." ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(lowercase__ )) ) a_ =torch.tensor(lowercase__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass a_ =encoder_input_ids a_ =decoder_input_ids a_ =a_ =None a_ =None a_ =a_ =None a_ =a_ =None a_ =None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical a_ =original(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] a_ =original.generator(lowercase__ ) a_ =new_model( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] a_ =new_model.generator(lowercase__ ) a_ =torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowercase__ ) ) a_ =torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("Maximum absolute difference beween weights: {:.2f}".format(lowercase__ ) ) a_ =torch.allclose(lowercase__ , lowercase__ , atol=1E-3 ) if are_identical: logging.info("all weights are equal up to 1e-3" ) else: raise ValueError("the weights are different. The new model is likely different from the original one." ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("saving the model's state dictionary" ) torch.save( new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin" ) if __name__ == "__main__": lowercase = argparse.ArgumentParser() parser.add_argument( '''--bertabs_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''', ) lowercase = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
41
'''simple docstring''' from collections.abc import Generator def UpperCAmelCase_ ( ): '''simple docstring''' a_ , a_ =0, 1 while True: a_ , a_ =b, a + b yield b def UpperCAmelCase_ ( lowercase__ = 1_0_0_0 ): '''simple docstring''' a_ =1 a_ =fibonacci_generator() while len(str(next(lowercase__ ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
41
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} # See all BART models at https://huggingface.co/models?filter=bart UpperCamelCase__ = { '''vocab_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''', }, '''merges_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json''', }, } UpperCamelCase__ = { '''facebook/bart-base''': 1_0_2_4, '''facebook/bart-large''': 1_0_2_4, '''facebook/bart-large-mnli''': 1_0_2_4, '''facebook/bart-large-cnn''': 1_0_2_4, '''facebook/bart-large-xsum''': 1_0_2_4, '''yjernite/bart_eli5''': 1_0_2_4, } class lowerCamelCase_ ( __a ): lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ = ['input_ids', 'attention_mask'] lowerCAmelCase__ = BartTokenizer def __init__( self : Tuple , _A : List[str]=None , _A : Optional[Any]=None , _A : Union[str, Any]=None , _A : Tuple="replace" , _A : Optional[Any]="<s>" , _A : int="</s>" , _A : Optional[Any]="</s>" , _A : List[str]="<s>" , _A : Optional[int]="<unk>" , _A : Optional[int]="<pad>" , _A : str="<mask>" , _A : Dict=False , _A : int=True , **_A : Optional[Any] , ): '''simple docstring''' super().__init__( _A , _A , tokenizer_file=_A , errors=_A , bos_token=_A , eos_token=_A , sep_token=_A , cls_token=_A , unk_token=_A , pad_token=_A , mask_token=_A , add_prefix_space=_A , trim_offsets=_A , **_A , ) UpperCAmelCase__ : Optional[int] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , _A ) != add_prefix_space: UpperCAmelCase__ : str = getattr(_A , pre_tok_state.pop('''type''' ) ) UpperCAmelCase__ : Any = add_prefix_space UpperCAmelCase__ : str = pre_tok_class(**_A ) UpperCAmelCase__ : Dict = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` UpperCAmelCase__ : Optional[Any] = '''post_processor''' UpperCAmelCase__ : List[Any] = getattr(self.backend_tokenizer , _A , _A ) if tokenizer_component_instance: UpperCAmelCase__ : Tuple = 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__ : Union[str, Any] = tuple(state['''sep'''] ) if "cls" in state: UpperCAmelCase__ : Union[str, Any] = tuple(state['''cls'''] ) UpperCAmelCase__ : Dict = False if state.get('''add_prefix_space''' , _A ) != add_prefix_space: UpperCAmelCase__ : Union[str, Any] = add_prefix_space UpperCAmelCase__ : Dict = True if state.get('''trim_offsets''' , _A ) != trim_offsets: UpperCAmelCase__ : List[Any] = trim_offsets UpperCAmelCase__ : List[Any] = True if changes_to_apply: UpperCAmelCase__ : Dict = getattr(_A , state.pop('''type''' ) ) UpperCAmelCase__ : Union[str, Any] = component_class(**_A ) setattr(self.backend_tokenizer , _A , _A ) @property def lowercase_ ( self : Dict ): '''simple docstring''' 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 lowercase_ ( self : Dict , _A : List[Any] ): '''simple docstring''' UpperCAmelCase__ : Tuple = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else value UpperCAmelCase__ : str = value def lowercase_ ( self : Optional[int] , *_A : List[str] , **_A : Dict ): '''simple docstring''' UpperCAmelCase__ : Any = kwargs.get('''is_split_into_words''' , _A ) 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(*_A , **_A ) def lowercase_ ( self : Optional[Any] , *_A : Union[str, Any] , **_A : List[Any] ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = kwargs.get('''is_split_into_words''' , _A ) 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(*_A , **_A ) def lowercase_ ( self : Optional[int] , _A : str , _A : Optional[str] = None ): '''simple docstring''' UpperCAmelCase__ : str = self._tokenizer.model.save(_A , name=_A ) return tuple(_A ) def lowercase_ ( self : Tuple , _A : Union[str, Any] , _A : Optional[int]=None ): '''simple docstring''' UpperCAmelCase__ : Any = [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 lowercase_ ( self : int , _A : List[int] , _A : Optional[List[int]] = None ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = [self.sep_token_id] UpperCAmelCase__ : int = [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]
75
import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants __A = Mapping[str, np.ndarray] __A = Mapping[str, Any] # Is a nested dict. __A = 0.01 @dataclasses.dataclass(frozen=snake_case ) class SCREAMING_SNAKE_CASE : """simple docstring""" A_ = 42 # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. A_ = 42 # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. A_ = 42 # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. A_ = 42 # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. A_ = 42 # [num_res, num_atom_type] # Chain indices for multi-chain predictions A_ = None # Optional remark about the protein. Included as a comment in output PDB # files A_ = None # Templates used to generate this protein (prediction-only) A_ = None # Chain corresponding to each parent A_ = None def __A ( _lowercase ): '''simple docstring''' _A = R'''(\[[A-Z]+\]\n)''' _A = [tag.strip() for tag in re.split(_lowercase , _lowercase ) if len(_lowercase ) > 0] _A = zip(tags[0::2] , [l.split('''\n''' ) for l in tags[1::2]] ) _A = ["N", "CA", "C"] _A = None _A = None _A = None for g in groups: if "[PRIMARY]" == g[0]: _A = g[1][0].strip() for i in range(len(_lowercase ) ): if seq[i] not in residue_constants.restypes: _A = '''X''' # FIXME: strings are immutable _A = np.array( [residue_constants.restype_order.get(_lowercase , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: _A = [] for axis in range(3 ): tertiary.append(list(map(_lowercase , g[1][axis].split() ) ) ) _A = np.array(_lowercase ) _A = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(_lowercase ): _A = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: _A = np.array(list(map({'''-''': 0, '''+''': 1}.get , g[1][0].strip() ) ) ) _A = np.zeros( ( len(_lowercase ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(_lowercase ): _A = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=_lowercase , atom_mask=_lowercase , aatype=_lowercase , residue_index=np.arange(len(_lowercase ) ) , b_factors=_lowercase , ) def __A ( _lowercase , _lowercase = 0 ): '''simple docstring''' _A = [] _A = prot.remark if remark is not None: pdb_headers.append(f"""REMARK {remark}""" ) _A = prot.parents _A = prot.parents_chain_index if parents is not None and parents_chain_index is not None: _A = [p for i, p in zip(_lowercase , _lowercase ) if i == chain_id] if parents is None or len(_lowercase ) == 0: _A = ['''N/A'''] pdb_headers.append(f"""PARENT {" ".join(_lowercase )}""" ) return pdb_headers def __A ( _lowercase , _lowercase ): '''simple docstring''' _A = [] _A = pdb_str.split('''\n''' ) _A = prot.remark if remark is not None: out_pdb_lines.append(f"""REMARK {remark}""" ) _A = 42 if prot.parents is not None and len(prot.parents ) > 0: _A = [] if prot.parents_chain_index is not None: _A = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(_lowercase ) , [] ) parent_dict[str(_lowercase )].append(_lowercase ) _A = max([int(_lowercase ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): _A = parent_dict.get(str(_lowercase ) , ['''N/A'''] ) parents_per_chain.append(_lowercase ) else: parents_per_chain.append(list(prot.parents ) ) else: _A = [['''N/A''']] def make_parent_line(_lowercase ) -> str: return f"""PARENT {" ".join(_lowercase )}""" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) _A = 0 for i, l in enumerate(_lowercase ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(_lowercase ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(_lowercase ): _A = parents_per_chain[chain_counter] else: _A = ['''N/A'''] out_pdb_lines.append(make_parent_line(_lowercase ) ) return "\n".join(_lowercase ) def __A ( _lowercase ): '''simple docstring''' _A = residue_constants.restypes + ['''X'''] def res_atoa(_lowercase ) -> str: return residue_constants.restype_atoa.get(restypes[r] , '''UNK''' ) _A = residue_constants.atom_types _A = [] _A = prot.atom_mask _A = prot.aatype _A = prot.atom_positions _A = prot.residue_index.astype(np.intaa ) _A = prot.b_factors _A = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('''Invalid aatypes.''' ) _A = get_pdb_headers(_lowercase ) if len(_lowercase ) > 0: pdb_lines.extend(_lowercase ) _A = aatype.shape[0] _A = 1 _A = 0 _A = string.ascii_uppercase _A = None # Add all atom sites. for i in range(_lowercase ): _A = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(_lowercase , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue _A = '''ATOM''' _A = atom_name if len(_lowercase ) == 4 else f""" {atom_name}""" _A = '''''' _A = '''''' _A = 1.00 _A = atom_name[0] # Protein supports only C, N, O, S, this works. _A = '''''' _A = '''A''' if chain_index is not None: _A = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! _A = ( f"""{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}""" f"""{res_name_a:>3} {chain_tag:>1}""" f"""{residue_index[i]:>4}{insertion_code:>1} """ f"""{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}""" f"""{occupancy:>6.2f}{b_factor:>6.2f} """ f"""{element:>2}{charge:>2}""" ) pdb_lines.append(_lowercase ) atom_index += 1 _A = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: _A = True _A = chain_index[i + 1] if should_terminate: # Close the chain. _A = '''TER''' _A = ( f"""{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}""" ) pdb_lines.append(_lowercase ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(_lowercase , _lowercase ) ) pdb_lines.append('''END''' ) pdb_lines.append('''''' ) return "\n".join(_lowercase ) def __A ( _lowercase ): '''simple docstring''' return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def __A ( _lowercase , _lowercase , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , _lowercase = None , ): '''simple docstring''' return Protein( aatype=features['''aatype'''] , atom_positions=result['''final_atom_positions'''] , atom_mask=result['''final_atom_mask'''] , residue_index=features['''residue_index'''] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result['''final_atom_mask'''] ) , chain_index=_lowercase , remark=_lowercase , parents=_lowercase , parents_chain_index=_lowercase , )
484
0
'''simple docstring''' import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class lowerCamelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : str , __A : int , __A : Tuple=13 , __A : Union[str, Any]=30 , __A : Tuple=2 , __A : Dict=3 , __A : Optional[Any]=True , __A : Union[str, Any]=True , __A : Dict=32 , __A : Union[str, Any]=5 , __A : List[str]=4 , __A : Dict=37 , __A : List[Any]="gelu" , __A : Optional[int]=0.1 , __A : Optional[int]=0.1 , __A : Dict=10 , __A : Optional[Any]=0.0_2 , ) -> Dict: '''simple docstring''' lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = num_patches + 1 def lowercase__ ( self : str ) -> int: '''simple docstring''' lowerCAmelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__A , initializer_range=self.initializer_range , ) return config, pixel_values def lowercase__ ( self : Tuple , __A : Any , __A : Union[str, Any] ) -> Optional[int]: '''simple docstring''' lowerCAmelCase__ = FlaxViTModel(config=__A ) lowerCAmelCase__ = model(__A ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) lowerCAmelCase__ = (self.image_size, self.image_size) lowerCAmelCase__ = (self.patch_size, self.patch_size) lowerCAmelCase__ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size) ) def lowercase__ ( self : str , __A : Optional[int] , __A : List[str] ) -> Optional[int]: '''simple docstring''' lowerCAmelCase__ = self.type_sequence_label_size lowerCAmelCase__ = FlaxViTForImageClassification(config=__A ) lowerCAmelCase__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowerCAmelCase__ = 1 lowerCAmelCase__ = FlaxViTForImageClassification(__A ) lowerCAmelCase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCAmelCase__ = model(__A ) def lowercase__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) , ) = config_and_inputs lowerCAmelCase__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_flax class lowerCamelCase__ ( _A, unittest.TestCase ): '''simple docstring''' A__ = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def lowercase__ ( self : Dict ) -> None: '''simple docstring''' lowerCAmelCase__ = FlaxViTModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=__A , has_text_modality=__A , hidden_size=37 ) def lowercase__ ( self : Optional[int] ) -> str: '''simple docstring''' self.config_tester.run_common_tests() def lowercase__ ( self : int ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def lowercase__ ( self : List[str] ) -> List[str]: '''simple docstring''' lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__A ) def lowercase__ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ ,lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(__A ) lowerCAmelCase__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __A ) def lowercase__ ( self : int ) -> Tuple: '''simple docstring''' lowerCAmelCase__ ,lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCAmelCase__ = self._prepare_for_class(__A , __A ) lowerCAmelCase__ = model_class(__A ) @jax.jit def model_jitted(__A : Tuple , **__A : List[Any] ): return model(pixel_values=__A , **__A ) with self.subTest("""JIT Enabled""" ): lowerCAmelCase__ = model_jitted(**__A ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): lowerCAmelCase__ = model_jitted(**__A ).to_tuple() self.assertEqual(len(__A ) , len(__A ) ) for jitted_output, output in zip(__A , __A ): self.assertEqual(jitted_output.shape , output.shape ) @slow def lowercase__ ( self : Any ) -> Tuple: '''simple docstring''' for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("""google/vit-base-patch16-224""" ) lowerCAmelCase__ = model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(__A )
709
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class lowerCamelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str] , __A : Tuple , __A : Union[str, Any]=7 , __A : Any=3 , __A : Dict=18 , __A : Dict=30 , __A : Dict=400 , __A : Dict=True , __A : Union[str, Any]=32 , __A : List[Any]=True , ) -> List[Any]: '''simple docstring''' lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = image_size lowerCAmelCase__ = min_resolution lowerCAmelCase__ = max_resolution lowerCAmelCase__ = do_resize lowerCAmelCase__ = size_divisor lowerCAmelCase__ = do_rescale def lowercase__ ( self : int ) -> List[Any]: '''simple docstring''' return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class lowerCamelCase__ ( _A, unittest.TestCase ): '''simple docstring''' A__ = GLPNImageProcessor if is_vision_available() else None def lowercase__ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = GLPNImageProcessingTester(self ) @property def lowercase__ ( self : int ) -> str: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowercase__ ( self : List[str] ) -> int: '''simple docstring''' lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__A , """do_resize""" ) ) self.assertTrue(hasattr(__A , """size_divisor""" ) ) self.assertTrue(hasattr(__A , """resample""" ) ) self.assertTrue(hasattr(__A , """do_rescale""" ) ) def lowercase__ ( self : Dict ) -> List[str]: '''simple docstring''' pass def lowercase__ ( self : Any ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A ) for image in image_inputs: self.assertIsInstance(__A , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowercase__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , numpify=__A ) for image in image_inputs: self.assertIsInstance(__A , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowercase__ ( self : List[str] ) -> str: '''simple docstring''' lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , torchify=__A ) for image in image_inputs: self.assertIsInstance(__A , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
211
0
"""simple docstring""" import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def __A ( a_ :Tuple , a_ :List[Any] , a_ :Optional[int]) -> Optional[int]: return params[F"""{prefix}/{prefix}/relpos_bias/rel_embedding"""][:, i, :] def __A ( a_ :int , a_ :List[Any] , a_ :Tuple , a_ :Any="attention") -> List[str]: __a : Union[str, Any] = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/key/kernel"""][:, i, :, :]) __a : Union[str, Any] = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2]) __a : str = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/out/kernel"""][:, i, :, :]) __a : Optional[int] = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2]) __a : int = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/query/kernel"""][:, i, :, :]) __a : List[str] = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2]) __a : Dict = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/value/kernel"""][:, i, :, :]) __a : List[str] = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2]) return k, o, q, v def __A ( a_ :int , a_ :List[str] , a_ :int , a_ :Union[str, Any]=False) -> List[str]: if split_mlp_wi: __a : List[str] = params[F"""{prefix}/{prefix}/mlp/wi_0/kernel"""][:, i, :] __a : Tuple = params[F"""{prefix}/{prefix}/mlp/wi_1/kernel"""][:, i, :] __a : Any = (wi_a, wi_a) else: __a : Any = params[F"""{prefix}/{prefix}/mlp/wi/kernel"""][:, i, :] __a : int = params[F"""{prefix}/{prefix}/mlp/wo/kernel"""][:, i, :] return wi, wo def __A ( a_ :List[Any] , a_ :Optional[int] , a_ :Optional[int] , a_ :List[str]) -> Any: return params[F"""{prefix}/{prefix}/{layer_name}/scale"""][:, i] def __A ( a_ :List[Any] , *, a_ :Optional[int] , a_ :Any , a_ :List[Any] = False) -> List[Any]: __a : List[Any] = traverse_util.flatten_dict(variables['''target''']) __a : Union[str, Any] = {'/'.join(UpperCAmelCase__): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi __a : Union[str, Any] = 'encoder/encoder/mlp/wi_0/kernel' in old print('''Split MLP:''' , UpperCAmelCase__) __a : Optional[Any] = collections.OrderedDict() # Shared embeddings. __a : Dict = old['token_embedder/embedding'] # Encoder. for i in range(UpperCAmelCase__): # Block i, layer 0 (Self Attention). __a : Optional[Any] = tax_layer_norm_lookup(UpperCAmelCase__ , UpperCAmelCase__ , '''encoder''' , '''pre_attention_layer_norm''') __a : Dict = tax_attention_lookup(UpperCAmelCase__ , UpperCAmelCase__ , '''encoder''' , '''attention''') __a : Any = layer_norm __a : Tuple = k.T __a : int = o.T __a : Optional[int] = q.T __a : str = v.T # Block i, layer 1 (MLP). __a : int = tax_layer_norm_lookup(UpperCAmelCase__ , UpperCAmelCase__ , '''encoder''' , '''pre_mlp_layer_norm''') __a : Dict = tax_mlp_lookup(UpperCAmelCase__ , UpperCAmelCase__ , '''encoder''' , UpperCAmelCase__) __a : int = layer_norm if split_mlp_wi: __a : Optional[int] = wi[0].T __a : Dict = wi[1].T else: __a : Optional[Any] = wi.T __a : int = wo.T if scalable_attention: # convert the rel_embedding of each layer __a : int = tax_relpos_bias_lookup( UpperCAmelCase__ , UpperCAmelCase__ , '''encoder''').T __a : int = old['encoder/encoder_norm/scale'] if not scalable_attention: __a : int = tax_relpos_bias_lookup( UpperCAmelCase__ , 0 , '''encoder''').T __a : List[str] = tax_relpos_bias_lookup( UpperCAmelCase__ , 0 , '''decoder''').T if not is_encoder_only: # Decoder. for i in range(UpperCAmelCase__): # Block i, layer 0 (Self Attention). __a : Dict = tax_layer_norm_lookup(UpperCAmelCase__ , UpperCAmelCase__ , '''decoder''' , '''pre_self_attention_layer_norm''') __a : Any = tax_attention_lookup(UpperCAmelCase__ , UpperCAmelCase__ , '''decoder''' , '''self_attention''') __a : str = layer_norm __a : Tuple = k.T __a : List[Any] = o.T __a : Optional[Any] = q.T __a : Optional[Any] = v.T # Block i, layer 1 (Cross Attention). __a : Tuple = tax_layer_norm_lookup(UpperCAmelCase__ , UpperCAmelCase__ , '''decoder''' , '''pre_cross_attention_layer_norm''') __a : Optional[Any] = tax_attention_lookup(UpperCAmelCase__ , UpperCAmelCase__ , '''decoder''' , '''encoder_decoder_attention''') __a : Optional[Any] = layer_norm __a : Union[str, Any] = k.T __a : Dict = o.T __a : Dict = q.T __a : Any = v.T # Block i, layer 2 (MLP). __a : Union[str, Any] = tax_layer_norm_lookup(UpperCAmelCase__ , UpperCAmelCase__ , '''decoder''' , '''pre_mlp_layer_norm''') __a : Optional[Any] = tax_mlp_lookup(UpperCAmelCase__ , UpperCAmelCase__ , '''decoder''' , UpperCAmelCase__) __a : Dict = layer_norm if split_mlp_wi: __a : Tuple = wi[0].T __a : List[str] = wi[1].T else: __a : Any = wi.T __a : Tuple = wo.T if scalable_attention: # convert the rel_embedding of each layer __a : int = tax_relpos_bias_lookup(UpperCAmelCase__ , UpperCAmelCase__ , '''decoder''').T __a : Any = old['decoder/decoder_norm/scale'] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: __a : Union[str, Any] = old['decoder/logits_dense/kernel'].T return new def __A ( a_ :List[Any] , a_ :List[Any]) -> int: __a : Union[str, Any] = collections.OrderedDict([(k, torch.from_numpy(v.copy())) for (k, v) in converted_params.items()]) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: __a : str = state_dict['shared.weight'] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: __a : List[Any] = state_dict['shared.weight'] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''') __a : str = state_dict['shared.weight'] return state_dict def __A ( a_ :List[Any] , a_ :Tuple , a_ :Union[str, Any] , a_ :List[str] , a_ :Optional[Any]) -> Optional[Any]: __a : Any = checkpoints.load_tax_checkpoint(UpperCAmelCase__) __a : int = convert_tax_to_pytorch( UpperCAmelCase__ , num_layers=config.num_layers , is_encoder_only=UpperCAmelCase__ , scalable_attention=UpperCAmelCase__) __a : Tuple = make_state_dict(UpperCAmelCase__ , UpperCAmelCase__) model.load_state_dict(UpperCAmelCase__ , strict=UpperCAmelCase__) def __A ( a_ :Union[str, Any] , a_ :Any , a_ :str , a_ :Tuple = False , a_ :Any = False , ) -> Any: __a : Any = MTaConfig.from_json_file(UpperCAmelCase__) print(F"""Building PyTorch model from configuration: {config}""") # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: __a : Optional[Any] = UMTaEncoderModel(UpperCAmelCase__) else: __a : Dict = UMTaForConditionalGeneration(UpperCAmelCase__) # Load weights from tf checkpoint load_tax_weights_in_ta(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""") model.save_pretrained(UpperCAmelCase__) # Verify that we can load the checkpoint. model.from_pretrained(UpperCAmelCase__) print('''Done''') if __name__ == "__main__": A = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) parser.add_argument( '''--scalable_attention''', action='''store_true''', help='''Whether the model uses scaled attention (umt5 model)''', default=False, ) A = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
52
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ : Tuple = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[Any] = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[Any] = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys A_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
'''simple docstring''' from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''''' lowerCamelCase__ = '''hf-legacy''' # "hf://"" is reserved for hffs def __init__( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): super().__init__(self , **__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = repo_info snake_case__ : Dict = token snake_case__ : Optional[int] = None def __UpperCamelCase ( self ): if self.dir_cache is None: snake_case__ : str = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes snake_case__ : Union[str, Any] = { """name""": hf_file.rfilename, """size""": None, """type""": """file""", } self.dir_cache.update( { str(__SCREAMING_SNAKE_CASE ): {"""name""": str(__SCREAMING_SNAKE_CASE ), """size""": None, """type""": """directory"""} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "rb" , **__SCREAMING_SNAKE_CASE , ): if not isinstance(self.repo_info , __SCREAMING_SNAKE_CASE ): raise NotImplementedError(f"Open is only implemented for dataset repositories, but got {self.repo_info}" ) snake_case__ : Dict = hf_hub_url(self.repo_info.id , __SCREAMING_SNAKE_CASE , revision=self.repo_info.sha ) return fsspec.open( __SCREAMING_SNAKE_CASE , mode=__SCREAMING_SNAKE_CASE , headers=get_authentication_headers_for_url(__SCREAMING_SNAKE_CASE , use_auth_token=self.token ) , client_kwargs={"""trust_env""": True} , ).open() def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self._get_dirs() snake_case__ : str = self._strip_protocol(__SCREAMING_SNAKE_CASE ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False , **__SCREAMING_SNAKE_CASE ): self._get_dirs() snake_case__ : str = PurePosixPath(path.strip("""/""" ) ) snake_case__ : int = {} for p, f in self.dir_cache.items(): snake_case__ : Optional[int] = PurePosixPath(p.strip("""/""" ) ) snake_case__ : int = p.parent if root == path: snake_case__ : List[str] = f snake_case__ : str = list(paths.values() ) if detail: return out else: return sorted(f["""name"""] for f in out )
419
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : str ) -> str: '''simple docstring''' snake_case__ : int = len(__magic_name__ ) snake_case__ : int = len(__magic_name__ ) snake_case__ : int = ( first_str_length if first_str_length > second_str_length else second_str_length ) snake_case__ : list = [] for char_count in range(__magic_name__ ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(__magic_name__ ) if __name__ == "__main__": print(alternative_string_arrange("AB", "XYZ"), end=" ")
419
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = {"""vocab_file""": """spm_char.model"""} UpperCamelCase_ = { """vocab_file""": { """microsoft/speecht5_asr""": """https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model""", """microsoft/speecht5_tts""": """https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model""", """microsoft/speecht5_vc""": """https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model""", } } UpperCamelCase_ = { """microsoft/speecht5_asr""": 10_24, """microsoft/speecht5_tts""": 10_24, """microsoft/speecht5_vc""": 10_24, } class a_ (_a ): __lowerCAmelCase : str = VOCAB_FILES_NAMES __lowerCAmelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase : Optional[Any] = ['input_ids', 'attention_mask'] def __init__( self , snake_case_ , snake_case_="<s>" , snake_case_="</s>" , snake_case_="<unk>" , snake_case_="<pad>" , snake_case_ = None , **snake_case_ , ): _lowerCAmelCase : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=snake_case_ , eos_token=snake_case_ , unk_token=snake_case_ , pad_token=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , **snake_case_ , ) _lowerCAmelCase : Optional[int] = vocab_file _lowerCAmelCase : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) @property def __UpperCamelCase ( self ): return self.sp_model.get_piece_size() def __UpperCamelCase ( self ): _lowerCAmelCase : List[Any] = {self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): _lowerCAmelCase : Any = self.__dict__.copy() _lowerCAmelCase : str = None return state def __setstate__( self , snake_case_ ): _lowerCAmelCase : Any = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): _lowerCAmelCase : Dict = {} _lowerCAmelCase : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __UpperCamelCase ( self , snake_case_ ): return self.sp_model.encode(snake_case_ , out_type=snake_case_ ) def __UpperCamelCase ( self , snake_case_ ): return self.sp_model.piece_to_id(snake_case_ ) def __UpperCamelCase ( self , snake_case_ ): _lowerCAmelCase : List[Any] = self.sp_model.IdToPiece(snake_case_ ) return token def __UpperCamelCase ( self , snake_case_ ): _lowerCAmelCase : Union[str, Any] = [] _lowerCAmelCase : Tuple = """""" 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(snake_case_ ) + token _lowerCAmelCase : Union[str, Any] = [] else: current_sub_tokens.append(snake_case_ ) out_string += self.sp_model.decode(snake_case_ ) return out_string.strip() def __UpperCamelCase ( self , snake_case_ , snake_case_=None ): if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def __UpperCamelCase ( self , snake_case_ , snake_case_ = None , snake_case_ = False ): 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_ ) _lowerCAmelCase : Optional[Any] = [1] if token_ids_a is None: return ([0] * len(snake_case_ )) + suffix_ones return ([0] * len(snake_case_ )) + ([0] * len(snake_case_ )) + suffix_ones def __UpperCamelCase ( self , snake_case_ , snake_case_ = None ): if not os.path.isdir(snake_case_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return _lowerCAmelCase : List[Any] = 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: _lowerCAmelCase : Optional[int] = self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,)
384
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer lowercase_ = logging.get_logger(__name__) lowercase_ = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} lowercase_ = { """vocab_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json""" ), }, } lowercase_ = { """yjernite/retribert-base-uncased""": 512, } lowercase_ = { """yjernite/retribert-base-uncased""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE (UpperCAmelCase ): _UpperCamelCase : Tuple = VOCAB_FILES_NAMES _UpperCamelCase : int = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Tuple = PRETRAINED_INIT_CONFIGURATION _UpperCamelCase : Optional[Any] = RetriBertTokenizer _UpperCamelCase : Dict = ['input_ids', 'attention_mask'] def __init__( self : str , a : Any=None , a : Optional[Any]=None , a : Dict=True , a : Union[str, Any]="[UNK]" , a : int="[SEP]" , a : Union[str, Any]="[PAD]" , a : str="[CLS]" , a : List[Any]="[MASK]" , a : Dict=True , a : Optional[Any]=None , **a : Any , )-> Optional[int]: """simple docstring""" super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) lowercase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , a ) != do_lower_case or normalizer_state.get('strip_accents' , a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , a ) != tokenize_chinese_chars ): lowercase__ = getattr(a , normalizer_state.pop('type' ) ) lowercase__ = do_lower_case lowercase__ = strip_accents lowercase__ = tokenize_chinese_chars lowercase__ = normalizer_class(**a ) lowercase__ = do_lower_case def SCREAMING_SNAKE_CASE_ ( self : Dict , a : List[Any] , a : int=None )-> Optional[Any]: """simple docstring""" lowercase__ = [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 : List[str] , a : List[int] , a : Optional[List[int]] = None )-> List[int]: """simple docstring""" lowercase__ = [self.sep_token_id] lowercase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE_ ( self : Any , a : str , a : Optional[str] = None )-> Tuple[str]: """simple docstring""" lowercase__ = self._tokenizer.model.save(a , name=a ) return tuple(a )
235
0
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class lowercase ( unittest.TestCase ): @slow def __snake_case( self : Optional[Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = FlaxMTaForConditionalGeneration.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE = tokenizer("Hello there" , return_tensors="np" ).input_ids SCREAMING_SNAKE_CASE = tokenizer("Hi I am" , return_tensors="np" ).input_ids SCREAMING_SNAKE_CASE = shift_tokens_right(_UpperCamelCase , model.config.pad_token_id , model.config.decoder_start_token_id ) SCREAMING_SNAKE_CASE = model(_UpperCamelCase , decoder_input_ids=_UpperCamelCase ).logits SCREAMING_SNAKE_CASE = optax.softmax_cross_entropy(_UpperCamelCase , onehot(_UpperCamelCase , logits.shape[-1] ) ).mean() SCREAMING_SNAKE_CASE = -(labels.shape[-1] * loss.item()) SCREAMING_SNAKE_CASE = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
714
from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) def __lowerCamelCase (UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] ): return [ int(1_0_0_0 * (box[0] / width) ), int(1_0_0_0 * (box[1] / height) ), int(1_0_0_0 * (box[2] / width) ), int(1_0_0_0 * (box[3] / height) ), ] def __lowerCamelCase (UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Optional[str] , UpperCAmelCase__ : Optional[str] = None ): SCREAMING_SNAKE_CASE = tesseract_config if tesseract_config is not None else "" # apply OCR SCREAMING_SNAKE_CASE = to_pil_image(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = pil_image.size SCREAMING_SNAKE_CASE = pytesseract.image_to_data(UpperCAmelCase__ , lang=UpperCAmelCase__ , output_type="dict" , config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = data["text"], data["left"], data["top"], data["width"], data["height"] # filter empty words and corresponding coordinates SCREAMING_SNAKE_CASE = [idx for idx, word in enumerate(UpperCAmelCase__ ) if not word.strip()] SCREAMING_SNAKE_CASE = [word for idx, word in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format SCREAMING_SNAKE_CASE = [] for x, y, w, h in zip(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ): SCREAMING_SNAKE_CASE = [x, y, x + w, y + h] actual_boxes.append(UpperCAmelCase__ ) # finally, normalize the bounding boxes SCREAMING_SNAKE_CASE = [] for box in actual_boxes: normalized_boxes.append(normalize_box(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) ) assert len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class lowercase ( a ): lowercase__ : Optional[int] = ["""pixel_values"""] def __init__( self : int , _UpperCamelCase : bool = True , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCamelCase : bool = True , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[str] = "" , **_UpperCamelCase : Optional[int] , ) -> None: '''simple docstring''' super().__init__(**_UpperCamelCase ) SCREAMING_SNAKE_CASE = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = resample SCREAMING_SNAKE_CASE = apply_ocr SCREAMING_SNAKE_CASE = ocr_lang SCREAMING_SNAKE_CASE = tesseract_config def __snake_case( self : List[Any] , _UpperCamelCase : np.ndarray , _UpperCamelCase : Dict[str, int] , _UpperCamelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : Any , ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) SCREAMING_SNAKE_CASE = (size["height"], size["width"]) return resize(_UpperCamelCase , size=_UpperCamelCase , resample=_UpperCamelCase , data_format=_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : Tuple , _UpperCamelCase : ImageInput , _UpperCamelCase : bool = None , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : PILImageResampling = None , _UpperCamelCase : bool = None , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[Union[str, TensorType]] = None , _UpperCamelCase : ChannelDimension = ChannelDimension.FIRST , **_UpperCamelCase : str , ) -> PIL.Image.Image: '''simple docstring''' SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE = apply_ocr if apply_ocr is not None else self.apply_ocr SCREAMING_SNAKE_CASE = ocr_lang if ocr_lang is not None else self.ocr_lang SCREAMING_SNAKE_CASE = tesseract_config if tesseract_config is not None else self.tesseract_config SCREAMING_SNAKE_CASE = make_list_of_images(_UpperCamelCase ) if not valid_images(_UpperCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(_UpperCamelCase ) for image in images] if apply_ocr: requires_backends(self , "pytesseract" ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for image in images: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = apply_tesseract(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) words_batch.append(_UpperCamelCase ) boxes_batch.append(_UpperCamelCase ) if do_resize: SCREAMING_SNAKE_CASE = [self.resize(image=_UpperCamelCase , size=_UpperCamelCase , resample=_UpperCamelCase ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) SCREAMING_SNAKE_CASE = [flip_channel_order(_UpperCamelCase ) for image in images] SCREAMING_SNAKE_CASE = [to_channel_dimension_format(_UpperCamelCase , _UpperCamelCase ) for image in images] SCREAMING_SNAKE_CASE = BatchFeature(data={"pixel_values": images} , tensor_type=_UpperCamelCase ) if apply_ocr: SCREAMING_SNAKE_CASE = words_batch SCREAMING_SNAKE_CASE = boxes_batch return data
647
0
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 SCREAMING_SNAKE_CASE = get_tests_dir('fixtures') SCREAMING_SNAKE_CASE = get_tests_dir('fixtures/dummy_feature_extractor_config.json') SCREAMING_SNAKE_CASE = get_tests_dir('fixtures/dummy-config.json') class __UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case_ ( self ): __a = 0 def snake_case_ ( self ): __a = AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h""" ) self.assertIsInstance(__A , __A ) def snake_case_ ( self ): __a = AutoFeatureExtractor.from_pretrained(__A ) self.assertIsInstance(__A , __A ) def snake_case_ ( self ): with tempfile.TemporaryDirectory() as tmpdirname: __a = WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally __a = AutoFeatureExtractor.from_pretrained(__A ).to_dict() config_dict.pop("""feature_extractor_type""" ) __a = WavaVecaFeatureExtractor(**__A ) # save in new folder model_config.save_pretrained(__A ) config.save_pretrained(__A ) __a = AutoFeatureExtractor.from_pretrained(__A ) # make sure private variable is not incorrectly saved __a = json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(__A , __A ) def snake_case_ ( self ): __a = AutoFeatureExtractor.from_pretrained(__A ) self.assertIsInstance(__A , __A ) def snake_case_ ( self ): with self.assertRaisesRegex( __A , """bert-base is not a local folder and is not a valid model identifier""" ): __a = AutoFeatureExtractor.from_pretrained("""bert-base""" ) def snake_case_ ( self ): with self.assertRaisesRegex( __A , R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): __a = AutoFeatureExtractor.from_pretrained(__A , revision="""aaaaaa""" ) def snake_case_ ( self ): with self.assertRaisesRegex( __A , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): __a = AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model""" ) def snake_case_ ( self ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__A ): __a = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__A ): __a = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=__A ) __a = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=__A ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(__A ) __a = AutoFeatureExtractor.from_pretrained(__A , trust_remote_code=__A ) self.assertEqual(reloaded_feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) def snake_case_ ( self ): try: AutoConfig.register("""custom""" , __A ) AutoFeatureExtractor.register(__A , __A ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__A ): AutoFeatureExtractor.register(__A , __A ) # Now that the config is registered, it can be used as any other config with the auto-API __a = CustomFeatureExtractor.from_pretrained(__A ) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(__A ) __a = AutoFeatureExtractor.from_pretrained(__A ) self.assertIsInstance(__A , __A ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def snake_case_ ( self ): class __UpperCAmelCase ( __A ): """simple docstring""" _lowerCamelCase = True try: AutoConfig.register("""custom""" , __A ) AutoFeatureExtractor.register(__A , __A ) # If remote code is not set, the default is to use local __a = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(feature_extractor.is_local ) # If remote code is disabled, we load the local one. __a = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=__A ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(feature_extractor.is_local ) # If remote is enabled, we load from the Hub __a = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=__A ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(not hasattr(__A , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
99
'''simple docstring''' def lowerCamelCase__ ( __lowerCamelCase : str = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' _UpperCAmelCase : Optional[Any] =set() # Replace all the whitespace in our sentence _UpperCAmelCase : Dict =input_str.replace(' ' , '' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(__lowerCamelCase ) == 2_6 def lowerCamelCase__ ( __lowerCamelCase : str = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' _UpperCAmelCase : Tuple =[False] * 2_6 for char in input_str: if char.islower(): _UpperCAmelCase : Dict =True elif char.isupper(): _UpperCAmelCase : List[str] =True return all(__lowerCamelCase ) def lowerCamelCase__ ( __lowerCamelCase : str = "The quick brown fox jumps over the lazy dog" , ): '''simple docstring''' return len({char for char in input_str.lower() if char.isalpha()} ) == 2_6 def lowerCamelCase__ ( ): '''simple docstring''' from timeit import timeit _UpperCAmelCase : List[Any] ='from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest' print(timeit('is_pangram()' , setup=__lowerCamelCase ) ) print(timeit('is_pangram_faster()' , setup=__lowerCamelCase ) ) print(timeit('is_pangram_fastest()' , setup=__lowerCamelCase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
446
0
from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( snake_case_ : list[int] , snake_case_ : list[int] , snake_case_ : list[int] , snake_case_ : list[list[str]] , snake_case_ : int , ) -> None: SCREAMING_SNAKE_CASE : int = len(SCREAMING_SNAKE_CASE_ ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append(['. ' * i + 'Q ' + '. ' * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(SCREAMING_SNAKE_CASE_ ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) def SCREAMING_SNAKE_CASE_ ( snake_case_ : int ) -> None: SCREAMING_SNAKE_CASE : list[list[str]] = [] depth_first_search([] , [] , [] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Print all the boards for board in boards: for column in board: print(SCREAMING_SNAKE_CASE_ ) print('' ) print(len(SCREAMING_SNAKE_CASE_ ) , 'solutions were found.' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
702
'''simple docstring''' from pathlib import Path import numpy as np from PIL import Image def SCREAMING_SNAKE_CASE_ ( snake_case_ : np.ndarray ) -> np.ndarray: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def SCREAMING_SNAKE_CASE_ ( snake_case_ : np.ndarray ) -> np.ndarray: return (gray > 127) & (gray <= 255) def SCREAMING_SNAKE_CASE_ ( snake_case_ : np.ndarray , snake_case_ : np.ndarray ) -> np.ndarray: SCREAMING_SNAKE_CASE : List[Any] = np.zeros_like(snake_case_ ) SCREAMING_SNAKE_CASE : Tuple = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE : Optional[int] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE : Optional[int] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE : int = int(summation > 0 ) return output if __name__ == "__main__": # read original image __UpperCAmelCase = Path(__file__).resolve().parent / 'image_data' / 'lena.jpg' __UpperCAmelCase = np.array(Image.open(lena_path)) # kernel to be applied __UpperCAmelCase = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) __UpperCAmelCase = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image __UpperCAmelCase = Image.fromarray(output).convert('RGB') pil_img.save('result_dilation.png')
220
0
import math import qiskit def a_ ( lowerCAmelCase_ : int = 1, lowerCAmelCase_ : int = 1, lowerCAmelCase_ : int = 1 ): if ( isinstance(lowerCAmelCase_, lowerCAmelCase_ ) or isinstance(lowerCAmelCase_, lowerCAmelCase_ ) or isinstance(lowerCAmelCase_, lowerCAmelCase_ ) ): raise TypeError('inputs must be integers.' ) if (input_a < 0) or (input_a < 0) or (carry_in < 0): raise ValueError('inputs must be positive.' ) if ( (math.floor(lowerCAmelCase_ ) != input_a) or (math.floor(lowerCAmelCase_ ) != input_a) or (math.floor(lowerCAmelCase_ ) != carry_in) ): raise ValueError('inputs must be exact integers.' ) if (input_a > 2) or (input_a > 2) or (carry_in > 2): raise ValueError('inputs must be less or equal to 2.' ) # build registers __lowerCAmelCase = qiskit.QuantumRegister(4, 'qr' ) __lowerCAmelCase = qiskit.ClassicalRegister(2, 'cr' ) # list the entries __lowerCAmelCase = [input_a, input_a, carry_in] __lowerCAmelCase = qiskit.QuantumCircuit(lowerCAmelCase_, lowerCAmelCase_ ) for i in range(0, 3 ): if entry[i] == 2: quantum_circuit.h(lowerCAmelCase_ ) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(lowerCAmelCase_ ) # for 1 entries elif entry[i] == 0: quantum_circuit.i(lowerCAmelCase_ ) # for 0 entries # build the circuit quantum_circuit.ccx(0, 1, 3 ) # ccx = toffoli gate quantum_circuit.cx(0, 1 ) quantum_circuit.ccx(1, 2, 3 ) quantum_circuit.cx(1, 2 ) quantum_circuit.cx(0, 1 ) quantum_circuit.measure([2, 3], lowerCAmelCase_ ) # measure the last two qbits __lowerCAmelCase = qiskit.Aer.get_backend('aer_simulator' ) __lowerCAmelCase = qiskit.execute(lowerCAmelCase_, lowerCAmelCase_, shots=1000 ) return job.result().get_counts(lowerCAmelCase_ ) if __name__ == "__main__": print(F"""Total sum count for state is: {quantum_full_adder(1, 1, 1)}""")
53
"""simple docstring""" import argparse import json from tqdm import tqdm def lowerCAmelCase__ ( ): '''simple docstring''' _a : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--src_path""" , type=UpperCamelCase__ , default="""biencoder-nq-dev.json""" , help="""Path to raw DPR training data""" , ) parser.add_argument( """--evaluation_set""" , type=UpperCamelCase__ , help="""where to store parsed evaluation_set file""" , ) parser.add_argument( """--gold_data_path""" , type=UpperCamelCase__ , help="""where to store parsed gold_data_path file""" , ) _a : Optional[int] = parser.parse_args() with open(args.src_path , """r""" ) as src_file, open(args.evaluation_set , """w""" ) as eval_file, open( args.gold_data_path , """w""" ) as gold_file: _a : Dict = json.load(UpperCamelCase__ ) for dpr_record in tqdm(UpperCamelCase__ ): _a : int = dpr_record["""question"""] _a : Dict = [context["""title"""] for context in dpr_record["""positive_ctxs"""]] eval_file.write(question + """\n""" ) gold_file.write("""\t""".join(UpperCamelCase__ ) + """\n""" ) if __name__ == "__main__": main()
389
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : int = { '''ut/deta''': '''https://huggingface.co/ut/deta/resolve/main/config.json''', } class UpperCAmelCase__ ( A__ ): """simple docstring""" a = "deta" a = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : str , __lowerCamelCase : int=None , __lowerCamelCase : List[str]=900 , __lowerCamelCase : int=2048 , __lowerCamelCase : Optional[int]=6 , __lowerCamelCase : Optional[int]=2048 , __lowerCamelCase : Optional[int]=8 , __lowerCamelCase : str=6 , __lowerCamelCase : int=1024 , __lowerCamelCase : Any=8 , __lowerCamelCase : Tuple=0.0 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Any="relu" , __lowerCamelCase : int=256 , __lowerCamelCase : List[Any]=0.1 , __lowerCamelCase : List[str]=0.0 , __lowerCamelCase : List[str]=0.0 , __lowerCamelCase : int=0.02 , __lowerCamelCase : Union[str, Any]=1.0 , __lowerCamelCase : Dict=True , __lowerCamelCase : List[Any]=False , __lowerCamelCase : List[Any]="sine" , __lowerCamelCase : Union[str, Any]=5 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : int=4 , __lowerCamelCase : Union[str, Any]=True , __lowerCamelCase : Optional[Any]=300 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Dict=True , __lowerCamelCase : List[str]=1 , __lowerCamelCase : Optional[Any]=5 , __lowerCamelCase : str=2 , __lowerCamelCase : Tuple=1 , __lowerCamelCase : List[str]=1 , __lowerCamelCase : Dict=5 , __lowerCamelCase : int=2 , __lowerCamelCase : List[str]=0.1 , __lowerCamelCase : List[str]=0.25 , **__lowerCamelCase : Any , ) -> List[Any]: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) SCREAMING_SNAKE_CASE__ = CONFIG_MAPPING['''resnet'''](out_features=['''stage2''', '''stage3''', '''stage4'''] ) else: if isinstance(__lowerCamelCase , __lowerCamelCase ): SCREAMING_SNAKE_CASE__ = backbone_config.pop('''model_type''' ) SCREAMING_SNAKE_CASE__ = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE__ = config_class.from_dict(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = backbone_config SCREAMING_SNAKE_CASE__ = num_queries SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = d_model SCREAMING_SNAKE_CASE__ = encoder_ffn_dim SCREAMING_SNAKE_CASE__ = encoder_layers SCREAMING_SNAKE_CASE__ = encoder_attention_heads SCREAMING_SNAKE_CASE__ = decoder_ffn_dim SCREAMING_SNAKE_CASE__ = decoder_layers SCREAMING_SNAKE_CASE__ = decoder_attention_heads SCREAMING_SNAKE_CASE__ = dropout SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = activation_dropout SCREAMING_SNAKE_CASE__ = activation_function SCREAMING_SNAKE_CASE__ = init_std SCREAMING_SNAKE_CASE__ = init_xavier_std SCREAMING_SNAKE_CASE__ = encoder_layerdrop SCREAMING_SNAKE_CASE__ = auxiliary_loss SCREAMING_SNAKE_CASE__ = position_embedding_type # deformable attributes SCREAMING_SNAKE_CASE__ = num_feature_levels SCREAMING_SNAKE_CASE__ = encoder_n_points SCREAMING_SNAKE_CASE__ = decoder_n_points SCREAMING_SNAKE_CASE__ = two_stage SCREAMING_SNAKE_CASE__ = two_stage_num_proposals SCREAMING_SNAKE_CASE__ = with_box_refine SCREAMING_SNAKE_CASE__ = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('''If two_stage is True, with_box_refine must be True.''' ) # Hungarian matcher SCREAMING_SNAKE_CASE__ = class_cost SCREAMING_SNAKE_CASE__ = bbox_cost SCREAMING_SNAKE_CASE__ = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE__ = mask_loss_coefficient SCREAMING_SNAKE_CASE__ = dice_loss_coefficient SCREAMING_SNAKE_CASE__ = bbox_loss_coefficient SCREAMING_SNAKE_CASE__ = giou_loss_coefficient SCREAMING_SNAKE_CASE__ = eos_coefficient SCREAMING_SNAKE_CASE__ = focal_alpha super().__init__(is_encoder_decoder=__lowerCamelCase , **__lowerCamelCase ) @property def lowercase_ ( self : Dict ) -> int: return self.encoder_attention_heads @property def lowercase_ ( self : Optional[int] ) -> int: return self.d_model def lowercase_ ( self : Union[str, Any] ) -> Dict: SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
472
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP 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 from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class UpperCAmelCase__ ( A__ , unittest.TestCase ): """simple docstring""" a = KandinskyImgaImgPipeline a = ["prompt", "image_embeds", "negative_image_embeds", "image"] a = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", ] a = [ "generator", "height", "width", "strength", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] a = False @property def lowercase_ ( self : str ) -> List[str]: return 32 @property def lowercase_ ( self : Optional[int] ) -> int: return 32 @property def lowercase_ ( self : Union[str, Any] ) -> int: return self.time_input_dim @property def lowercase_ ( self : List[str] ) -> int: return self.time_input_dim * 4 @property def lowercase_ ( self : Union[str, Any] ) -> Any: return 100 @property def lowercase_ ( self : Any ) -> List[Any]: SCREAMING_SNAKE_CASE__ = XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base''' ) return tokenizer @property def lowercase_ ( self : List[Any] ) -> List[Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) SCREAMING_SNAKE_CASE__ = MultilingualCLIP(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = text_encoder.eval() return text_encoder @property def lowercase_ ( self : str ) -> Dict: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = { '''in_channels''': 4, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''text_image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''text_image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE__ = UNetaDConditionModel(**__lowerCamelCase ) return model @property def lowercase_ ( self : Dict ) -> Optional[Any]: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def lowercase_ ( self : Tuple ) -> Optional[int]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = VQModel(**self.dummy_movq_kwargs ) return model def lowercase_ ( self : int ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ = self.dummy_tokenizer SCREAMING_SNAKE_CASE__ = self.dummy_unet SCREAMING_SNAKE_CASE__ = self.dummy_movq SCREAMING_SNAKE_CASE__ = { '''num_train_timesteps''': 1000, '''beta_schedule''': '''linear''', '''beta_start''': 0.00085, '''beta_end''': 0.012, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } SCREAMING_SNAKE_CASE__ = DDIMScheduler(**__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = { '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def lowercase_ ( self : List[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any]=0 ) -> str: SCREAMING_SNAKE_CASE__ = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(__lowerCamelCase ) # create init_image SCREAMING_SNAKE_CASE__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ = Image.fromarray(np.uinta(__lowerCamelCase ) ).convert('''RGB''' ).resize((256, 256) ) if str(__lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE__ = torch.manual_seed(__lowerCamelCase ) else: SCREAMING_SNAKE_CASE__ = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = { '''prompt''': '''horse''', '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def lowercase_ ( self : int ) -> Any: SCREAMING_SNAKE_CASE__ = '''cpu''' SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = pipe(**self.get_dummy_inputs(__lowerCamelCase ) ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = pipe( **self.get_dummy_inputs(__lowerCamelCase ) , return_dict=__lowerCamelCase , )[0] SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ = np.array( [0.61474943, 0.6073539, 0.43308544, 0.5928269, 0.47493595, 0.46755973, 0.4613838, 0.45368797, 0.50119233] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def lowercase_ ( self : Tuple ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self : List[str] ) -> List[str]: SCREAMING_SNAKE_CASE__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/kandinsky_img2img_frog.npy''' ) SCREAMING_SNAKE_CASE__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) SCREAMING_SNAKE_CASE__ = '''A red cartoon frog, 4k''' SCREAMING_SNAKE_CASE__ = KandinskyPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = KandinskyImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-1''' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ = pipeline.to(__lowerCamelCase ) pipeline.set_progress_bar_config(disable=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = torch.Generator(device='''cpu''' ).manual_seed(0 ) SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ = pipe_prior( __lowerCamelCase , generator=__lowerCamelCase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() SCREAMING_SNAKE_CASE__ = pipeline( __lowerCamelCase , image=__lowerCamelCase , image_embeds=__lowerCamelCase , negative_image_embeds=__lowerCamelCase , generator=__lowerCamelCase , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='''np''' , ) SCREAMING_SNAKE_CASE__ = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__lowerCamelCase , __lowerCamelCase )
472
1
'''simple docstring''' from __future__ import annotations def _UpperCamelCase (_lowerCamelCase : int , _lowerCamelCase : int )-> list[str]: '''simple docstring''' if partitions <= 0: raise ValueError('''partitions must be a positive number!''' ) if partitions > number_of_bytes: raise ValueError('''partitions can not > number_of_bytes!''' ) __snake_case = number_of_bytes // partitions __snake_case = [] for i in range(_lowerCamelCase ): __snake_case = i * bytes_per_partition + 1 __snake_case = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
24
import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( 'The `inpainting.py` script is outdated. Please use directly `from diffusers import' ' StableDiffusionInpaintPipeline` instead.' )
408
0
import unittest import numpy as np from transformers import BertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.bert.modeling_flax_bert import ( FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, ) class lowerCamelCase_ ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=4 , ): a_ = parent a_ = batch_size a_ = seq_length a_ = is_training a_ = use_attention_mask a_ = use_token_type_ids a_ = use_labels a_ = vocab_size a_ = hidden_size a_ = num_hidden_layers a_ = num_attention_heads a_ = intermediate_size a_ = hidden_act a_ = hidden_dropout_prob a_ = attention_probs_dropout_prob a_ = max_position_embeddings a_ = type_vocab_size a_ = type_sequence_label_size a_ = initializer_range a_ = num_choices def __magic_name__ ( self ): a_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ = None if self.use_attention_mask: a_ = random_attention_mask([self.batch_size, self.seq_length] ) a_ = None if self.use_token_type_ids: a_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCamelCase_ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() a_ = config_and_inputs a_ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask} return config, inputs_dict def __magic_name__ ( self ): a_ = self.prepare_config_and_inputs() a_ = config_and_inputs a_ = True a_ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) a_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, attention_mask, encoder_hidden_states, encoder_attention_mask, ) @require_flax class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): _lowerCamelCase : Optional[int] = True _lowerCamelCase : Optional[int] = ( ( FlaxBertModel, FlaxBertForPreTraining, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForQuestionAnswering, FlaxBertForNextSentencePrediction, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertForQuestionAnswering, ) if is_flax_available() else () ) def __magic_name__ ( self ): a_ = FlaxBertModelTester(self ) @slow def __magic_name__ ( self ): a_ = FlaxBertModel.from_pretrained("""bert-base-cased""" ) a_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCamelCase_ )
704
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __SCREAMING_SNAKE_CASE ( UpperCamelCase : Tuple , UpperCamelCase : Optional[Any] ) -> Tuple: """simple docstring""" if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer a_ = flax_key_tuple[:-1] + ("""weight""",) a_ = torch.permute(UpperCamelCase , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(UpperCamelCase ): # linear layer a_ = flax_key_tuple[:-1] + ("""weight""",) a_ = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: a_ = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def __SCREAMING_SNAKE_CASE ( UpperCamelCase : List[Any] , UpperCamelCase : Dict , UpperCamelCase : Optional[Any] ) -> Tuple: """simple docstring""" if "metadata" in layer: a_ = layer.split("""metadata""" ) a_ = """""".join(split_layer[0] )[:-1] a_ = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: a_ = layer.split("""kvstore""" ) a_ = """""".join(split_layer[0] )[:-1] a_ = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: a_ = layer.split("""/""" ) a_ = """/""".join(split_layer[:-1] ) a_ = (split_layer[-1],) if "kvstore/path" in layer: a_ = F"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: a_ = """file""" else: a_ = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __SCREAMING_SNAKE_CASE ( UpperCamelCase : str , UpperCamelCase : Any ) -> List[str]: """simple docstring""" a_ = rename_keys(UpperCamelCase ) a_ = {} for k, v in current_block.items(): a_ = v a_ = new_current_block torch.save(UpperCamelCase , UpperCamelCase ) def __SCREAMING_SNAKE_CASE ( UpperCamelCase : Optional[int] , UpperCamelCase : Dict , UpperCamelCase : List[Any] , UpperCamelCase : List[Any] , UpperCamelCase : str = WEIGHTS_NAME ) -> Any: """simple docstring""" a_ = convert_file_size_to_int(UpperCamelCase ) a_ = [] a_ = {} a_ = 0 a_ = 0 os.makedirs(UpperCamelCase , exist_ok=UpperCamelCase ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: a_ = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] a_ = flatten_dict(UpperCamelCase , sep="""/""" ) a_ = {} for layer in checkpoint_info.keys(): a_ , a_ , a_ = get_key_and_tensorstore_dict( UpperCamelCase , UpperCamelCase , UpperCamelCase ) if curr_real_layer_name in all_layers: a_ = content else: a_ = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file a_ = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() a_ = torch.tensor(UpperCamelCase ) a_ = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts a_ , a_ = rename_base_flax_keys(tuple(key.split("""/""" ) ) , UpperCamelCase ) a_ = """/""".join(UpperCamelCase ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: a_ = os.path.join( UpperCamelCase , weights_name.replace(""".bin""" , F"""-{len(UpperCamelCase )+1:05d}-of-???.bin""" ) ) rename_and_save_block(UpperCamelCase , UpperCamelCase ) sharded_state_dicts.append(current_block.keys() ) del current_block a_ = {} a_ = 0 a_ = raw_weights.to(getattr(UpperCamelCase , UpperCamelCase ) ) current_block_size += weight_size total_size += weight_size # Add the last block a_ = os.path.join(UpperCamelCase , weights_name.replace(""".bin""" , F"""-{len(UpperCamelCase )+1:05d}-of-???.bin""" ) ) rename_and_save_block(UpperCamelCase , UpperCamelCase ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(UpperCamelCase ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index a_ = {} a_ = {} for idx, shard in enumerate(UpperCamelCase ): a_ = weights_name.replace( """.bin""" , F"""-{idx+1:05d}-of-{len(UpperCamelCase ):05d}.bin""" ) # len(sharded_state_dicts):05d} a_ = os.path.join(UpperCamelCase , weights_name.replace(""".bin""" , F"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(UpperCamelCase , os.path.join(UpperCamelCase , UpperCamelCase ) ) a_ = shard for key in shard: a_ = shard_file # Add the metadata a_ = {"""total_size""": total_size} a_ = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(UpperCamelCase , UpperCamelCase ) , """w""" , encoding="""utf-8""" ) as f: a_ = json.dumps(UpperCamelCase , indent=2 , sort_keys=UpperCamelCase ) + """\n""" f.write(UpperCamelCase ) return metadata, index if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--max_shard_size', default='10GB', required=False, help='Max shard size') parser.add_argument('--dtype', default='bfloat16', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted', type=str, required=False, help='Path to the output pytorch model.', ) _A = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __SCREAMING_SNAKE_CASE ( ) -> List[Any]: """simple docstring""" from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer a_ = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) a_ = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) a_ = TaTokenizer.from_pretrained("""t5-small""" ) a_ = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" a_ = tokenizer(UpperCamelCase , return_tensors="""pt""" ).input_ids a_ = model.generate(UpperCamelCase , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
403
0
import os import sys import unittest __UpperCamelCase: int = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path __UpperCamelCase: int = os.path.join(git_repo_path, """src""", """diffusers""") class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def snake_case__( self: Dict ): lowercase__ : List[Any] = find_backend(' if not is_torch_available():' ) self.assertEqual(lowerCamelCase_, 'torch' ) # backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") # self.assertEqual(backend_with_underscore, "tensorflow_text") lowercase__ : List[Any] = find_backend(' if not (is_torch_available() and is_transformers_available()):' ) self.assertEqual(lowerCamelCase_, 'torch_and_transformers' ) # double_backend_with_underscore = find_backend( # " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" # ) # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") lowercase__ : Dict = find_backend( ' if not (is_torch_available() and is_transformers_available() and is_onnx_available()):' ) self.assertEqual(lowerCamelCase_, 'torch_and_transformers_and_onnx' ) def snake_case__( self: Tuple ): lowercase__ : Optional[Any] = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('torch', lowerCamelCase_ ) self.assertIn('torch_and_transformers', lowerCamelCase_ ) self.assertIn('flax_and_transformers', lowerCamelCase_ ) self.assertIn('torch_and_transformers_and_onnx', lowerCamelCase_ ) # Likewise, we can't assert on the exact content of a key self.assertIn('UNet2DModel', objects['torch'] ) self.assertIn('FlaxUNet2DConditionModel', objects['flax'] ) self.assertIn('StableDiffusionPipeline', objects['torch_and_transformers'] ) self.assertIn('FlaxStableDiffusionPipeline', objects['flax_and_transformers'] ) self.assertIn('LMSDiscreteScheduler', objects['torch_and_scipy'] ) self.assertIn('OnnxStableDiffusionPipeline', objects['torch_and_transformers_and_onnx'] ) def snake_case__( self: Optional[Any] ): lowercase__ : Union[str, Any] = create_dummy_object('CONSTANT', '\'torch\'' ) self.assertEqual(lowerCamelCase_, '\nCONSTANT = None\n' ) lowercase__ : List[str] = create_dummy_object('function', '\'torch\'' ) self.assertEqual( lowerCamelCase_, '\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n' ) lowercase__ : int = '\nclass FakeClass(metaclass=DummyObject):\n _backends = \'torch\'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, \'torch\')\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, \'torch\')\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, \'torch\')\n' lowercase__ : Optional[Any] = create_dummy_object('FakeClass', '\'torch\'' ) self.assertEqual(lowerCamelCase_, lowerCamelCase_ ) def snake_case__( self: Any ): lowercase__ : Union[str, Any] = '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = ["torch"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, ["torch"])\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, ["torch"])\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, ["torch"])\n' lowercase__ : Dict = create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']} ) self.assertEqual(dummy_files['torch'], lowerCamelCase_ )
266
import argparse import os import re __UpperCamelCase: Any = """src/transformers/models/auto""" # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict __UpperCamelCase: Dict = re.compile(r"""[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict""") # re pattern that matches identifiers in mappings __UpperCamelCase: List[str] = re.compile(r"""\s*\(\s*\"(\S[^\"]+)\"""") def SCREAMING_SNAKE_CASE__ ( _lowercase : int , _lowercase : bool = False ) -> List[str]: '''simple docstring''' with open(_lowercase , 'r' , encoding='utf-8' ) as f: lowercase__ : Union[str, Any] = f.read() lowercase__ : Optional[Any] = content.split('\n' ) lowercase__ : Optional[int] = [] lowercase__ : int = 0 while line_idx < len(_lowercase ): if _re_intro_mapping.search(lines[line_idx] ) is not None: lowercase__ : Tuple = len(re.search(r'^(\s*)\S' , lines[line_idx] ).groups()[0] ) + 8 # Start of a new mapping! while not lines[line_idx].startswith(' ' * indent + '(' ): new_lines.append(lines[line_idx] ) line_idx += 1 lowercase__ : Tuple = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": lowercase__ : Any = line_idx while not lines[line_idx].startswith(' ' * indent + ')' ): line_idx += 1 blocks.append('\n'.join(lines[start_idx : line_idx + 1] ) ) else: blocks.append(lines[line_idx] ) line_idx += 1 # Sort blocks by their identifiers lowercase__ : List[str] = sorted(_lowercase , key=lambda _lowercase : _re_identifier.search(_lowercase ).groups()[0] ) new_lines += blocks else: new_lines.append(lines[line_idx] ) line_idx += 1 if overwrite: with open(_lowercase , 'w' , encoding='utf-8' ) as f: f.write('\n'.join(_lowercase ) ) elif "\n".join(_lowercase ) != content: return True def SCREAMING_SNAKE_CASE__ ( _lowercase : bool = False ) -> List[Any]: '''simple docstring''' lowercase__ : List[Any] = [os.path.join(_lowercase , _lowercase ) for f in os.listdir(_lowercase ) if f.endswith('.py' )] lowercase__ : str = [sort_auto_mapping(_lowercase , overwrite=_lowercase ) for fname in fnames] if not overwrite and any(_lowercase ): lowercase__ : List[Any] = [f for f, d in zip(_lowercase , _lowercase ) if d] raise ValueError( f"""The following files have auto mappings that need sorting: {", ".join(_lowercase )}. Run `make style` to fix""" ' this.' ) if __name__ == "__main__": __UpperCamelCase: Tuple = argparse.ArgumentParser() parser.add_argument("""--check_only""", action="""store_true""", help="""Whether to only check or fix style.""") __UpperCamelCase: List[Any] = parser.parse_args() sort_all_auto_mappings(not args.check_only)
266
1
def lowerCAmelCase_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" return int(input_a == input_a == 0 ) def lowerCAmelCase_ ( ) -> None: """simple docstring""" print("Truth Table of NOR Gate:" ) print("| Input 1 | Input 2 | Output |" ) print(F"""| 0 | 0 | {nor_gate(0 , 0 )} |""" ) print(F"""| 0 | 1 | {nor_gate(0 , 1 )} |""" ) print(F"""| 1 | 0 | {nor_gate(1 , 0 )} |""" ) print(F"""| 1 | 1 | {nor_gate(1 , 1 )} |""" ) if __name__ == "__main__": import doctest doctest.testmod() main()
328
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __lowerCamelCase = TypeVar('KEY') __lowerCamelCase = TypeVar('VAL') @dataclass(frozen=SCREAMING_SNAKE_CASE , slots=SCREAMING_SNAKE_CASE ) class _UpperCamelCase( Generic[KEY, VAL] ): __A: KEY __A: VAL class _UpperCamelCase( _Item ): def __init__( self : Optional[Any] ): super().__init__(_lowerCamelCase , _lowerCamelCase ) def __bool__( self : Optional[int] ): return False __lowerCamelCase = _DeletedItem() class _UpperCamelCase( MutableMapping[KEY, VAL] ): def __init__( self : Optional[Any] , _lowerCamelCase : int = 8 , _lowerCamelCase : float = 0.75 ): _UpperCAmelCase : List[str] = initial_block_size _UpperCAmelCase : list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 _UpperCAmelCase : Optional[Any] = capacity_factor _UpperCAmelCase : List[Any] = 0 def a__ ( self : List[Any] , _lowerCamelCase : KEY ): return hash(_lowerCamelCase ) % len(self._buckets ) def a__ ( self : List[str] , _lowerCamelCase : int ): return (ind + 1) % len(self._buckets ) def a__ ( self : Any , _lowerCamelCase : int , _lowerCamelCase : KEY , _lowerCamelCase : VAL ): _UpperCAmelCase : Optional[Any] = self._buckets[ind] if not stored: _UpperCAmelCase : Union[str, Any] = _Item(_lowerCamelCase , _lowerCamelCase ) self._len += 1 return True elif stored.key == key: _UpperCAmelCase : List[Any] = _Item(_lowerCamelCase , _lowerCamelCase ) return True else: return False def a__ ( self : Any ): _UpperCAmelCase : Dict = len(self._buckets ) * self._capacity_factor return len(self ) >= int(_lowerCamelCase ) def a__ ( self : Any ): if len(self._buckets ) <= self._initial_block_size: return False _UpperCAmelCase : Tuple = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def a__ ( self : Union[str, Any] , _lowerCamelCase : int ): _UpperCAmelCase : Dict = self._buckets _UpperCAmelCase : Union[str, Any] = [None] * new_size _UpperCAmelCase : Union[str, Any] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def a__ ( self : Any ): self._resize(len(self._buckets ) * 2 ) def a__ ( self : int ): self._resize(len(self._buckets ) // 2 ) def a__ ( self : Any , _lowerCamelCase : KEY ): _UpperCAmelCase : Any = self._get_bucket_index(_lowerCamelCase ) for _ in range(len(self._buckets ) ): yield ind _UpperCAmelCase : Union[str, Any] = self._get_next_ind(_lowerCamelCase ) def a__ ( self : Union[str, Any] , _lowerCamelCase : KEY , _lowerCamelCase : VAL ): for ind in self._iterate_buckets(_lowerCamelCase ): if self._try_set(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): break def __setitem__( self : Optional[int] , _lowerCamelCase : KEY , _lowerCamelCase : VAL ): if self._is_full(): self._size_up() self._add_item(_lowerCamelCase , _lowerCamelCase ) def __delitem__( self : int , _lowerCamelCase : KEY ): for ind in self._iterate_buckets(_lowerCamelCase ): _UpperCAmelCase : List[str] = self._buckets[ind] if item is None: raise KeyError(_lowerCamelCase ) if item is _deleted: continue if item.key == key: _UpperCAmelCase : Union[str, Any] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : str , _lowerCamelCase : KEY ): for ind in self._iterate_buckets(_lowerCamelCase ): _UpperCAmelCase : Any = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(_lowerCamelCase ) def __len__( self : List[str] ): return self._len def __iter__( self : List[str] ): yield from (item.key for item in self._buckets if item) def __repr__( self : Tuple ): _UpperCAmelCase : Optional[int] = " ,".join( f"""{item.key}: {item.val}""" for item in self._buckets if item ) return f"""HashMap({val_string})"""
328
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Union[str, Any]=4 , __A :Dict=3 , __A :str=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Tuple=[2, 4, 8, 16] , __A :List[str]=7 , __A :Optional[Any]=3.0 , __A :Tuple=True , __A :Tuple=0.0 , __A :Dict=0.0 , __A :Tuple=0.1 , __A :str="gelu" , __A :Tuple=0.0_2 , __A :str=1E-5 , __A :Tuple=0.0 , __A :List[str]=None , __A :Optional[Any]=None , **__A :Optional[Any] , ) -> List[str]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
6
'''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 __UpperCAmelCase ( lowerCAmelCase ,unittest.TestCase ): '''simple docstring''' _UpperCamelCase = CTRLTokenizer _UpperCamelCase = False _UpperCamelCase = False def __snake_case ( self : str) -> List[Any]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A_ = ['adapt', 're@@', 'a@@', 'apt', 'c@@', 't', '<unk>'] A_ = dict(zip(_lowercase , range(len(_lowercase)))) A_ = ['#version: 0.2', 'a p', 'ap t</w>', 'r e', 'a d', 'ad apt</w>', ''] A_ = {'unk_token': '<unk>'} A_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file']) A_ = 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(_lowercase) + '\n') with open(self.merges_file , 'w' , encoding='utf-8') as fp: fp.write('\n'.join(_lowercase)) def __snake_case ( self : Optional[int] , **_lowercase : Optional[int]) -> Union[str, Any]: kwargs.update(self.special_tokens_map) return CTRLTokenizer.from_pretrained(self.tmpdirname , **_lowercase) def __snake_case ( self : List[Any] , _lowercase : Union[str, Any]) -> Dict: A_ = 'adapt react readapt apt' A_ = 'adapt react readapt apt' return input_text, output_text def __snake_case ( self : Any) -> Any: A_ = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map) A_ = 'adapt react readapt apt' A_ = 'adapt re@@ a@@ c@@ t re@@ adapt apt'.split() A_ = tokenizer.tokenize(_lowercase) self.assertListEqual(_lowercase , _lowercase) A_ = tokens + [tokenizer.unk_token] A_ = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowercase) , _lowercase)
366
0
from __future__ import annotations import time _lowercase = list[tuple[int, int]] _lowercase = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _lowercase = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class lowerCamelCase__ : def __init__( self : List[Any] , __a : int , __a : int , __a : int , __a : int , __a : Node | None ): '''simple docstring''' lowerCamelCase__: List[Any] = pos_x lowerCamelCase__: Optional[Any] = pos_y lowerCamelCase__: str = (pos_y, pos_x) lowerCamelCase__: Union[str, Any] = goal_x lowerCamelCase__: str = goal_y lowerCamelCase__: Union[str, Any] = parent class lowerCamelCase__ : def __init__( self : Optional[Any] , __a : tuple[int, int] , __a : tuple[int, int] ): '''simple docstring''' lowerCamelCase__: Optional[int] = Node(start[1] , start[0] , goal[1] , goal[0] , __a ) lowerCamelCase__: List[Any] = Node(goal[1] , goal[0] , goal[1] , goal[0] , __a ) lowerCamelCase__: Any = [self.start] lowerCamelCase__: Optional[int] = False def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' while self.node_queue: lowerCamelCase__: Dict = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: lowerCamelCase__: int = True return self.retrace_path(__a ) lowerCamelCase__: Union[str, Any] = self.get_successors(__a ) for node in successors: self.node_queue.append(__a ) if not self.reached: return [self.start.pos] return None def lowerCamelCase_ ( self : List[str] , __a : Node ): '''simple docstring''' lowerCamelCase__: int = [] for action in delta: lowerCamelCase__: str = parent.pos_x + action[1] lowerCamelCase__: List[str] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__a ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(__a , __a , self.target.pos_y , self.target.pos_x , __a ) ) return successors def lowerCamelCase_ ( self : Tuple , __a : Node | None ): '''simple docstring''' lowerCamelCase__: Union[str, Any] = node lowerCamelCase__: str = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) lowerCamelCase__: str = current_node.parent path.reverse() return path class lowerCamelCase__ : def __init__( self : List[Any] , __a : str , __a : Dict ): '''simple docstring''' lowerCamelCase__: int = BreadthFirstSearch(__a , __a ) lowerCamelCase__: Dict = BreadthFirstSearch(__a , __a ) lowerCamelCase__: str = False def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: lowerCamelCase__: Dict = self.fwd_bfs.node_queue.pop(0 ) lowerCamelCase__: Optional[int] = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: lowerCamelCase__: str = True return self.retrace_bidirectional_path( __a , __a ) lowerCamelCase__: int = current_bwd_node lowerCamelCase__: List[Any] = current_fwd_node lowerCamelCase__: List[str] = { self.fwd_bfs: self.fwd_bfs.get_successors(__a ), self.bwd_bfs: self.bwd_bfs.get_successors(__a ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(__a ) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCamelCase_ ( self : Dict , __a : Node , __a : Node ): '''simple docstring''' lowerCamelCase__: str = self.fwd_bfs.retrace_path(__a ) lowerCamelCase__: Optional[int] = self.bwd_bfs.retrace_path(__a ) bwd_path.pop() bwd_path.reverse() lowerCamelCase__: Tuple = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() _lowercase = (0, 0) _lowercase = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _lowercase = time.time() _lowercase = BreadthFirstSearch(init, goal) _lowercase = bfs.search() _lowercase = time.time() - start_bfs_time print('Unidirectional BFS computation time : ', bfs_time) _lowercase = time.time() _lowercase = BidirectionalBreadthFirstSearch(init, goal) _lowercase = bd_bfs.search() _lowercase = time.time() - start_bd_bfs_time print('Bidirectional BFS computation time : ', bd_bfs_time)
242
def __lowerCAmelCase ( _UpperCamelCase , _UpperCamelCase ) -> int: '''simple docstring''' if b == 0: return 1 if (b % 2) == 0: return actual_power(_UpperCamelCase , int(b / 2 ) ) * actual_power(_UpperCamelCase , int(b / 2 ) ) else: return a * actual_power(_UpperCamelCase , int(b / 2 ) ) * actual_power(_UpperCamelCase , int(b / 2 ) ) def __lowerCAmelCase ( _UpperCamelCase , _UpperCamelCase ) -> float: '''simple docstring''' if b < 0: return 1 / actual_power(_UpperCamelCase , _UpperCamelCase ) return actual_power(_UpperCamelCase , _UpperCamelCase ) if __name__ == "__main__": print(power(-2, -3))
242
1
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin __magic_name__ : int = False @skip_mps class __SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = StableDiffusionAttendAndExcitePipeline UpperCAmelCase__ : Any = False UpperCAmelCase__ : Optional[int] = TEXT_TO_IMAGE_PARAMS UpperCAmelCase__ : Dict = TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''} ) UpperCAmelCase__ : List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS UpperCAmelCase__ : Any = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def UpperCamelCase( cls ): super().setUpClass() torch.use_deterministic_algorithms(lowerCamelCase ) @classmethod def UpperCamelCase( cls ): super().tearDownClass() torch.use_deterministic_algorithms(lowerCamelCase ) def UpperCamelCase( self ): torch.manual_seed(0 ) _snake_case = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=lowerCamelCase , ) _snake_case = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=lowerCamelCase , set_alpha_to_one=lowerCamelCase , ) torch.manual_seed(0 ) _snake_case = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) _snake_case = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) _snake_case = CLIPTextModel(lowerCamelCase ) _snake_case = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) _snake_case = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def UpperCamelCase( self , lowerCamelCase , lowerCamelCase=0 ): if str(lowerCamelCase ).startswith("mps" ): _snake_case = torch.manual_seed(lowerCamelCase ) else: _snake_case = torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) _snake_case = _snake_case = { "prompt": "a cat and a frog", "token_indices": [2, 5], "generator": generator, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", "max_iter_to_alter": 2, "thresholds": {0: 0.7}, } return inputs def UpperCamelCase( self ): _snake_case = "cpu" _snake_case = self.get_dummy_components() _snake_case = self.pipeline_class(**lowerCamelCase ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) _snake_case = self.get_dummy_inputs(lowerCamelCase ) _snake_case = pipe(**lowerCamelCase ).images _snake_case = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 64, 64, 3) ) _snake_case = np.array( [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496] ) _snake_case = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(lowerCamelCase , 1e-3 ) def UpperCamelCase( self ): super().test_cpu_offload_forward_pass(expected_max_diff=5e-4 ) def UpperCamelCase( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCamelCase( self ): self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7e-4 ) def UpperCamelCase( self ): super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def UpperCamelCase( self ): super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4 ) def UpperCamelCase( self ): super().test_save_load_local(expected_max_difference=5e-4 ) def UpperCamelCase( self ): super().test_save_load_optional_components(expected_max_difference=4e-4 ) @require_torch_gpu @slow class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @classmethod def UpperCamelCase( cls ): super().setUpClass() torch.use_deterministic_algorithms(lowerCamelCase ) @classmethod def UpperCamelCase( cls ): super().tearDownClass() torch.use_deterministic_algorithms(lowerCamelCase ) def UpperCamelCase( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase( self ): _snake_case = torch.manual_seed(51 ) _snake_case = StableDiffusionAttendAndExcitePipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , safety_checker=lowerCamelCase , torch_dtype=torch.floataa ) pipe.to("cuda" ) _snake_case = "a painting of an elephant with glasses" _snake_case = [5, 7] _snake_case = pipe( prompt=lowerCamelCase , token_indices=lowerCamelCase , guidance_scale=7.5 , generator=lowerCamelCase , num_inference_steps=5 , max_iter_to_alter=5 , output_type="numpy" , ).images[0] _snake_case = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy" ) assert np.abs((expected_image - image).max() ) < 5e-1
672
'''simple docstring''' from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging __magic_name__ : Dict = logging.get_logger(__name__) def snake_case_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): return list(tensor.shape ) _snake_case = tf.shape(SCREAMING_SNAKE_CASE__ ) if tensor.shape == tf.TensorShape(SCREAMING_SNAKE_CASE__ ): return dynamic _snake_case = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(SCREAMING_SNAKE_CASE__ )] def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' return tf.nn.softmax(logits=logits + 1E-9 , axis=SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=-1 ): '''simple docstring''' if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise NotImplementedError("Only 1D weight and bias tensors are supported for now, with only a single axis." ) # Get mean and variance on the axis to be normalized _snake_case , _snake_case = tf.nn.moments(SCREAMING_SNAKE_CASE__ , axes=[axis] , keepdims=SCREAMING_SNAKE_CASE__ ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis _snake_case = [1] * inputs.shape.rank _snake_case = shape_list(SCREAMING_SNAKE_CASE__ )[axis] _snake_case = tf.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _snake_case = tf.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Compute layer normalization using the batch_normalization # function. _snake_case = tf.nn.batch_normalization( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , offset=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , variance_epsilon=SCREAMING_SNAKE_CASE__ , ) return outputs def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=-1 ): '''simple docstring''' if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input _snake_case = tf.shape(SCREAMING_SNAKE_CASE__ ) _snake_case = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) _snake_case = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def snake_case_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if not isinstance(SCREAMING_SNAKE_CASE__ , tf.Tensor ): _snake_case = tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: _snake_case = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: _snake_case = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) _snake_case = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "input_ids" ): '''simple docstring''' tf.debugging.assert_less( SCREAMING_SNAKE_CASE__ , tf.cast(SCREAMING_SNAKE_CASE__ , dtype=tensor.dtype ) , message=( f'''The maximum value of {tensor_name} ({tf.math.reduce_max(SCREAMING_SNAKE_CASE__ )}) must be smaller than the embedding ''' f'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.''' ) , ) def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' _snake_case = 6_45_12 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. _snake_case = [x for x in data if len(SCREAMING_SNAKE_CASE__ ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( "The following attributes cannot be saved to HDF5 file because " f'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} ''' f'''bytes: {bad_attributes}''' ) _snake_case = np.asarray(SCREAMING_SNAKE_CASE__ ) _snake_case = 1 _snake_case = np.array_split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 _snake_case = np.array_split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(SCREAMING_SNAKE_CASE__ ): _snake_case = chunk_data else: _snake_case = data def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if name in group.attrs: _snake_case = [n.decode("utf8" ) if hasattr(SCREAMING_SNAKE_CASE__ , "decode" ) else n for n in group.attrs[name]] else: _snake_case = [] _snake_case = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode("utf8" ) if hasattr(SCREAMING_SNAKE_CASE__ , "decode" ) else n for n in group.attrs["%s%d" % (name, chunk_id)]] ) chunk_id += 1 return data def snake_case_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def _expand_single_ad_tensor(SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(SCREAMING_SNAKE_CASE__ , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , SCREAMING_SNAKE_CASE__ )
672
1
'''simple docstring''' from __future__ import annotations __snake_case: Optional[int] = "Muhammad Umer Farooq" __snake_case: Optional[int] = "MIT" __snake_case: Tuple = "1.0.0" __snake_case: Optional[Any] = "Muhammad Umer Farooq" __snake_case: Any = "contact@muhammadumerfarooq.me" __snake_case: int = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class _UpperCAmelCase ( __a ): """simple docstring""" def __init__( self , lowerCAmelCase_ ): '''simple docstring''' super().__init__() a_ : Any = [] a_ : List[str] = domain def _lowerCAmelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' 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: a_ : int = parse.urljoin(self.domain , lowerCAmelCase_ ) self.urls.append(lowerCAmelCase_ ) def _snake_case ( A_ : Dict ): """simple docstring""" return ".".join(get_sub_domain_name(lowercase__ ).split(""".""" )[-2:] ) def _snake_case ( A_ : List[str] ): """simple docstring""" return parse.urlparse(lowercase__ ).netloc def _snake_case ( A_ : Dict = "https://github.com" ): """simple docstring""" a_ : Optional[int] = get_domain_name(lowercase__ ) # Initialize the parser a_ : List[str] = Parser(lowercase__ ) try: # Open URL a_ : Any = requests.get(lowercase__ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through a_ : Tuple = set() for link in parser.urls: # open URL. # read = requests.get(link) try: a_ : Dict = requests.get(lowercase__ ) # Get the valid email. a_ : int = re.findall("""[a-zA-Z0-9]+@""" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(lowercase__ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(lowercase__ ) if __name__ == "__main__": __snake_case: List[Any] = emails_from_url("https://github.com") print(F"""{len(emails)} emails found:""") print("\n".join(sorted(emails)))
719
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __snake_case: Tuple = logging.get_logger(__name__) __snake_case: Tuple = { "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 _UpperCAmelCase ( lowerCAmelCase__ ): """simple docstring""" a_ = "t5" a_ = ["past_key_values"] a_ = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self , lowerCAmelCase_=3_21_28 , lowerCAmelCase_=5_12 , lowerCAmelCase_=64 , lowerCAmelCase_=20_48 , lowerCAmelCase_=6 , lowerCAmelCase_=None , lowerCAmelCase_=8 , lowerCAmelCase_=32 , lowerCAmelCase_=1_28 , lowerCAmelCase_=0.1 , lowerCAmelCase_=1E-6 , lowerCAmelCase_=1.0 , lowerCAmelCase_="relu" , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=0 , lowerCAmelCase_=1 , **lowerCAmelCase_ , ): '''simple docstring''' a_ : List[Any] = vocab_size a_ : List[str] = d_model a_ : Union[str, Any] = d_kv a_ : List[Any] = d_ff a_ : int = num_layers a_ : Any = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a_ : Union[str, Any] = num_heads a_ : int = relative_attention_num_buckets a_ : Dict = relative_attention_max_distance a_ : Union[str, Any] = dropout_rate a_ : Union[str, Any] = layer_norm_epsilon a_ : List[Any] = initializer_factor a_ : Any = feed_forward_proj a_ : List[Any] = use_cache a_ : Dict = self.feed_forward_proj.split("""-""" ) a_ : Union[str, Any] = act_info[-1] a_ : str = act_info[0] == """gated""" if len(lowerCAmelCase_ ) > 1 and act_info[0] != "gated" or len(lowerCAmelCase_ ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """'gated-gelu' or 'relu'""" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a_ : List[str] = """gelu_new""" super().__init__( pad_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , is_encoder_decoder=lowerCAmelCase_ , **lowerCAmelCase_ , ) class _UpperCAmelCase ( lowerCAmelCase__ ): """simple docstring""" @property def _lowerCAmelCase ( self ): '''simple docstring''' a_ : List[Any] = { """input_ids""": {0: """batch""", 1: """encoder_sequence"""}, """attention_mask""": {0: """batch""", 1: """encoder_sequence"""}, } if self.use_past: a_ : Tuple = """past_encoder_sequence + sequence""" a_ : str = {0: """batch"""} a_ : Any = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: a_ : List[Any] = {0: """batch""", 1: """decoder_sequence"""} a_ : Optional[int] = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(lowerCAmelCase_ , direction="""inputs""" ) return common_inputs @property def _lowerCAmelCase ( self ): '''simple docstring''' return 13
460
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 lowercase_ : """simple docstring""" def __init__( self : str , __lowerCamelCase : int , __lowerCamelCase : Dict=9_9 , __lowerCamelCase : Any=1_3 , __lowerCamelCase : Tuple=7 , __lowerCamelCase : int=9 , __lowerCamelCase : List[str]=True , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : int=False , __lowerCamelCase : str=3_2 , __lowerCamelCase : Dict=5 , __lowerCamelCase : Union[str, Any]=4 , __lowerCamelCase : int=3_7 , __lowerCamelCase : Optional[int]=8 , __lowerCamelCase : Any=0.1 , __lowerCamelCase : Tuple=0.0_0_2 , __lowerCamelCase : Optional[int]=1 , __lowerCamelCase : int=0 , __lowerCamelCase : str=0 , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Optional[Any]=None , ): """simple docstring""" _SCREAMING_SNAKE_CASE = parent _SCREAMING_SNAKE_CASE = batch_size _SCREAMING_SNAKE_CASE = encoder_seq_length _SCREAMING_SNAKE_CASE = decoder_seq_length # For common tests _SCREAMING_SNAKE_CASE = self.decoder_seq_length _SCREAMING_SNAKE_CASE = is_training _SCREAMING_SNAKE_CASE = use_attention_mask _SCREAMING_SNAKE_CASE = use_labels _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = d_ff _SCREAMING_SNAKE_CASE = relative_attention_num_buckets _SCREAMING_SNAKE_CASE = dropout_rate _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = eos_token_id _SCREAMING_SNAKE_CASE = pad_token_id _SCREAMING_SNAKE_CASE = decoder_start_token_id _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = decoder_layers def lowerCAmelCase_ ( self : Dict ): """simple docstring""" return TaConfig.from_pretrained("google/umt5-base" ) def lowerCAmelCase_ ( self : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Tuple=None , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Optional[Any]=None , ): """simple docstring""" if attention_mask is None: _SCREAMING_SNAKE_CASE = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: _SCREAMING_SNAKE_CASE = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: _SCREAMING_SNAKE_CASE = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=snake_case__ ) if decoder_head_mask is None: _SCREAMING_SNAKE_CASE = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=snake_case__ ) if cross_attn_head_mask is None: _SCREAMING_SNAKE_CASE = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=snake_case__ ) 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 lowerCAmelCase_ ( self : Optional[int] ): """simple docstring""" _SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE = 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 _SCREAMING_SNAKE_CASE = input_ids.clamp(self.pad_token_id + 1 ) _SCREAMING_SNAKE_CASE = decoder_input_ids.clamp(self.pad_token_id + 1 ) _SCREAMING_SNAKE_CASE = self.get_config() _SCREAMING_SNAKE_CASE = config.num_attention_heads _SCREAMING_SNAKE_CASE = self.prepare_inputs_dict(snake_case__ , snake_case__ , snake_case__ ) return config, input_dict def lowerCAmelCase_ ( self : Tuple ): """simple docstring""" _SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() return config, inputs_dict def lowerCAmelCase_ ( self : Any ): """simple docstring""" return TaConfig( vocab_size=1_6_6 , 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 lowerCAmelCase_ ( self : Optional[Any] ): """simple docstring""" 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 lowerCAmelCase_ ( self : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Dict , __lowerCamelCase : str , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : str , ): """simple docstring""" _SCREAMING_SNAKE_CASE = UMTaModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() _SCREAMING_SNAKE_CASE = model( input_ids=snake_case__ , decoder_input_ids=snake_case__ , attention_mask=snake_case__ , decoder_attention_mask=snake_case__ , ) _SCREAMING_SNAKE_CASE = model(input_ids=snake_case__ , decoder_input_ids=snake_case__ ) _SCREAMING_SNAKE_CASE = result.last_hidden_state _SCREAMING_SNAKE_CASE = result.past_key_values _SCREAMING_SNAKE_CASE = 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(snake_case__ ) , 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 lowerCAmelCase_ ( self : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : List[str] , ): """simple docstring""" _SCREAMING_SNAKE_CASE = UMTaModel(config=snake_case__ ).get_decoder().to(snake_case__ ).eval() # first forward pass _SCREAMING_SNAKE_CASE = model(snake_case__ , use_cache=snake_case__ ) _SCREAMING_SNAKE_CASE = model(snake_case__ ) _SCREAMING_SNAKE_CASE = model(snake_case__ , use_cache=snake_case__ ) self.parent.assertTrue(len(snake_case__ ) == len(snake_case__ ) ) self.parent.assertTrue(len(snake_case__ ) == len(snake_case__ ) + 1 ) _SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and _SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) _SCREAMING_SNAKE_CASE = model(snake_case__ )['last_hidden_state'] _SCREAMING_SNAKE_CASE = model(snake_case__ , past_key_values=snake_case__ )['last_hidden_state'] # select random slice _SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() _SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() _SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case__ , snake_case__ , atol=1e-3 ) ) def lowerCAmelCase_ ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , ): """simple docstring""" _SCREAMING_SNAKE_CASE = UMTaModel(config=snake_case__ ).to(snake_case__ ).half().eval() _SCREAMING_SNAKE_CASE = model(**snake_case__ )['last_hidden_state'] self.parent.assertFalse(torch.isnan(snake_case__ ).any().item() ) @require_torch class lowercase_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" lowerCamelCase_ = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) lowerCamelCase_ = (UMTaForConditionalGeneration,) if is_torch_available() else () lowerCamelCase_ = ( { '''conversational''': UMTaForConditionalGeneration, '''feature-extraction''': UMTaModel, '''summarization''': UMTaForConditionalGeneration, '''text2text-generation''': UMTaForConditionalGeneration, '''translation''': UMTaForConditionalGeneration, '''question-answering''': UMTaForQuestionAnswering, } if is_torch_available() else {} ) lowerCamelCase_ = True lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = True # The small UMT5 model needs higher percentages for CPU/MP tests lowerCamelCase_ = [0.8, 0.9] def lowerCAmelCase_ ( self : List[str] ): """simple docstring""" _SCREAMING_SNAKE_CASE = UMTaModelTester(self ) @unittest.skip("Test has a segmentation fault on torch 1.8.0" ) def lowerCAmelCase_ ( self : Optional[Any] ): """simple docstring""" _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE = UMTaModel(config_and_inputs[0] ).to(snake_case__ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( snake_case__ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"""{tmpdirname}/t5_test.onnx""" , export_params=snake_case__ , opset_version=9 , input_names=["input_ids", "decoder_input_ids"] , ) @unittest.skipIf(torch_device == "cpu" , "Cant do half precision" ) def lowerCAmelCase_ ( self : List[str] ): """simple docstring""" _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*snake_case__ ) def lowerCAmelCase_ ( self : int ): """simple docstring""" _SCREAMING_SNAKE_CASE = ['encoder_attentions', 'decoder_attentions', 'cross_attentions'] _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE = config_and_inputs[0] _SCREAMING_SNAKE_CASE = UMTaForConditionalGeneration(snake_case__ ).eval() model.to(snake_case__ ) _SCREAMING_SNAKE_CASE = { 'head_mask': torch.zeros(config.num_layers , config.num_heads , device=snake_case__ ), 'decoder_head_mask': torch.zeros(config.num_decoder_layers , config.num_heads , device=snake_case__ ), 'cross_attn_head_mask': torch.zeros(config.num_decoder_layers , config.num_heads , device=snake_case__ ), } for attn_name, (name, mask) in zip(snake_case__ , head_masking.items() ): _SCREAMING_SNAKE_CASE = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": _SCREAMING_SNAKE_CASE = torch.ones( config.num_decoder_layers , config.num_heads , device=snake_case__ ) _SCREAMING_SNAKE_CASE = model.generate( config_and_inputs[1]["input_ids"] , num_beams=1 , max_length=3 , output_attentions=snake_case__ , return_dict_in_generate=snake_case__ , **snake_case__ , ) # We check the state of decoder_attentions and cross_attentions just from the last step _SCREAMING_SNAKE_CASE = 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 lowerCAmelCase_ ( self : int ): """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class lowercase_ ( unittest.TestCase ): """simple docstring""" @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 lowerCAmelCase_ ( self : str ): """simple docstring""" _SCREAMING_SNAKE_CASE = UMTaForConditionalGeneration.from_pretrained("google/umt5-small" , return_dict=snake_case__ ).to(snake_case__ ) _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("google/umt5-small" , use_fast=snake_case__ , legacy=snake_case__ ) _SCREAMING_SNAKE_CASE = [ '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>.', ] _SCREAMING_SNAKE_CASE = tokenizer(snake_case__ , return_tensors="pt" , padding=snake_case__ ).input_ids # fmt: off _SCREAMING_SNAKE_CASE = torch.tensor( [ [ 3_8_5_3_0, 2_1_0_7_0_3, 2_5_6_2_9_9, 1_4_1_0, 2_5_6_2_9_8, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 8_2_6, 3_2_1, 6_7_1, 2_5_9_2_2, 2_5_6_2_9_9, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_4_6_0, 3_3_9, 3_1_2, 1_9_0_1_4, 1_0_6_2_0, 7_5_8, 2_5_6_2_9_9, 2_3_5_5,2_7_4, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 5_1_7, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 3_0_1, 2_5_6_2_9_8, 2_7_5, 1_1_9_9_8_3,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 3_2_0, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 2_2_3_4, 2_8_9, 2_2_7_5, 3_3_3,6_1_3_9_1, 2_8_9, 2_5_6_2_9_8, 5_4_3, 2_5_6_2_9_7, 1_6_8_7_1_4, 3_2_9, 2_5_6_2_9_6,2_7_4, 1], ] ) # fmt: on torch.testing.assert_allclose(snake_case__ , snake_case__ ) _SCREAMING_SNAKE_CASE = model.generate(input_ids.to(snake_case__ ) ) _SCREAMING_SNAKE_CASE = [ '<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>', ] _SCREAMING_SNAKE_CASE = tokenizer.batch_decode(snake_case__ ) self.assertEqual(snake_case__ , snake_case__ )
418
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) lowerCAmelCase : Optional[Any] = logging.getLogger(__name__) @dataclass class UpperCamelCase__ : """simple docstring""" __magic_name__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __magic_name__ = field( default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __magic_name__ = field( default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __magic_name__ = field( default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) __magic_name__ = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Whether tp freeze the encoder."} ) __magic_name__ = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class UpperCamelCase__ : """simple docstring""" __magic_name__ = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) __magic_name__ = field( default="summarization" , metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"} , ) __magic_name__ = field( default=1_0_2_4 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __magic_name__ = field( default=1_2_8 , metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __magic_name__ = field( default=1_4_2 , metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) } , ) __magic_name__ = field( default=1_4_2 , metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __magic_name__ = field(default=-1 , metadata={"help": "# training examples. -1 means use all."} ) __magic_name__ = field(default=-1 , metadata={"help": "# validation examples. -1 means use all."} ) __magic_name__ = field(default=-1 , metadata={"help": "# test examples. -1 means use all."} ) __magic_name__ = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Source language id for translation."} ) __magic_name__ = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Target language id for translation."} ) __magic_name__ = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "# num_beams to use for evaluation."} ) __magic_name__ = field( default=SCREAMING_SNAKE_CASE_ , metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."} , ) def lowercase (_A , _A , _A ): """simple docstring""" logger.info(f'***** {split} metrics *****' ) for key in sorted(metrics.keys() ): logger.info(f' {key} = {metrics[key]}' ) save_json(_A , os.path.join(_A , f'{split}_results.json' ) ) def lowercase (): """simple docstring""" _lowerCAmelCase : int = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Tuple = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Optional[int] = parser.parse_args_into_dataclasses() check_output_dir(_A ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('Training/evaluation parameters %s' , _A ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _lowerCAmelCase : Optional[int] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _lowerCAmelCase : Tuple = ('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout') for p in extra_model_params: if getattr(_A , _A , _A ): assert hasattr(_A , _A ), f'({config.__class__.__name__}) doesn\'t have a `{p}` attribute' setattr(_A , _A , getattr(_A , _A ) ) _lowerCAmelCase : Any = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _lowerCAmelCase : str = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='.ckpt' in model_args.model_name_or_path , config=_A , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(_A , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: _lowerCAmelCase : Union[str, Any] = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(_A , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(_A , _A ): _lowerCAmelCase : Union[str, Any] = tokenizer.lang_code_to_id[data_args.tgt_lang] else: _lowerCAmelCase : Union[str, Any] = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(_A ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) _lowerCAmelCase : Any = SeqaSeqDataset # Get datasets _lowerCAmelCase : List[Any] = ( dataset_class( _A , type_path='train' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_train else None ) _lowerCAmelCase : Optional[Any] = ( dataset_class( _A , type_path='val' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) _lowerCAmelCase : Union[str, Any] = ( dataset_class( _A , type_path='test' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_predict else None ) # Initialize our Trainer _lowerCAmelCase : Optional[Any] = ( build_compute_metrics_fn(data_args.task , _A ) if training_args.predict_with_generate else None ) _lowerCAmelCase : int = SeqaSeqTrainer( model=_A , args=_A , data_args=_A , train_dataset=_A , eval_dataset=_A , data_collator=SeqaSeqDataCollator( _A , _A , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=_A , tokenizer=_A , ) _lowerCAmelCase : str = {} # Training if training_args.do_train: logger.info('*** Train ***' ) _lowerCAmelCase : Dict = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) _lowerCAmelCase : Any = train_result.metrics _lowerCAmelCase : str = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('train' , _A , training_args.output_dir ) all_metrics.update(_A ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , 'trainer_state.json' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) _lowerCAmelCase : List[str] = trainer.evaluate(metric_key_prefix='val' ) _lowerCAmelCase : int = data_args.n_val _lowerCAmelCase : List[str] = round(metrics['val_loss'] , 4 ) if trainer.is_world_process_zero(): handle_metrics('val' , _A , training_args.output_dir ) all_metrics.update(_A ) if training_args.do_predict: logger.info('*** Predict ***' ) _lowerCAmelCase : Any = trainer.predict(test_dataset=_A , metric_key_prefix='test' ) _lowerCAmelCase : Optional[int] = test_output.metrics _lowerCAmelCase : Optional[int] = data_args.n_test if trainer.is_world_process_zero(): _lowerCAmelCase : Dict = round(metrics['test_loss'] , 4 ) handle_metrics('test' , _A , training_args.output_dir ) all_metrics.update(_A ) if training_args.predict_with_generate: _lowerCAmelCase : Union[str, Any] = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=_A , clean_up_tokenization_spaces=_A ) _lowerCAmelCase : List[Any] = lmap(str.strip , _A ) write_txt_file(_A , os.path.join(training_args.output_dir , 'test_generations.txt' ) ) if trainer.is_world_process_zero(): save_json(_A , os.path.join(training_args.output_dir , 'all_results.json' ) ) return all_metrics def lowercase (_A ): """simple docstring""" main() if __name__ == "__main__": main()
444
0
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class UpperCAmelCase__ ( lowercase__ , lowercase__ ): """simple docstring""" __UpperCAmelCase : Any = 1 @register_to_config def __init__( self : Tuple ,_a : Dict=2000 ,_a : Union[str, Any]=0.1 ,_a : Dict=20 ,_a : List[Any]=1E-3 ): '''simple docstring''' _a : Dict = None _a : int = None _a : Union[str, Any] = None def __lowercase ( self : Any ,_a : Dict ,_a : Union[str, torch.device] = None ): '''simple docstring''' _a : List[Any] = torch.linspace(1 ,self.config.sampling_eps ,_a ,device=_a ) def __lowercase ( self : Union[str, Any] ,_a : str ,_a : Optional[int] ,_a : Any ,_a : Union[str, Any]=None ): '''simple docstring''' if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score _a : int = ( -0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) _a : Union[str, Any] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) _a : Dict = std.flatten() while len(std.shape ) < len(score.shape ): _a : Any = std.unsqueeze(-1 ) _a : int = -score / std # compute _a : List[Any] = -1.0 / len(self.timesteps ) _a : str = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) _a : Union[str, Any] = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): _a : List[str] = beta_t.unsqueeze(-1 ) _a : Any = -0.5 * beta_t * x _a : Any = torch.sqrt(_a ) _a : Optional[Any] = drift - diffusion**2 * score _a : List[Any] = x + drift * dt # add noise _a : int = randn_tensor(x.shape ,layout=x.layout ,generator=_a ,device=x.device ,dtype=x.dtype ) _a : Optional[Any] = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self : Optional[int] ): '''simple docstring''' return self.config.num_train_timesteps
319
'''simple docstring''' import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : int = '''AutoTokenizer''' __UpperCAmelCase : Optional[Any] = ['''tokenizer'''] __UpperCAmelCase : str = { '''semantic_prompt''': 1, '''coarse_prompt''': 2, '''fine_prompt''': 2, } def __init__( self : Union[str, Any] ,_a : Union[str, Any] ,_a : Dict=None ): '''simple docstring''' super().__init__(_a ) _a : List[str] = speaker_embeddings @classmethod def __lowercase ( cls : Any ,_a : Optional[int] ,_a : Union[str, Any]="speaker_embeddings_path.json" ,**_a : Union[str, Any] ): '''simple docstring''' if speaker_embeddings_dict_path is not None: _a : Tuple = get_file_from_repo( _a ,_a ,subfolder=kwargs.pop('subfolder' ,_a ) ,cache_dir=kwargs.pop('cache_dir' ,_a ) ,force_download=kwargs.pop('force_download' ,_a ) ,proxies=kwargs.pop('proxies' ,_a ) ,resume_download=kwargs.pop('resume_download' ,_a ) ,local_files_only=kwargs.pop('local_files_only' ,_a ) ,use_auth_token=kwargs.pop('use_auth_token' ,_a ) ,revision=kwargs.pop('revision' ,_a ) ,) if speaker_embeddings_path is None: logger.warning( F"""`{os.path.join(_a ,_a )}` does not exists , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`.""" ) _a : List[Any] = None else: with open(_a ) as speaker_embeddings_json: _a : List[str] = json.load(_a ) else: _a : str = None _a : Any = AutoTokenizer.from_pretrained(_a ,**_a ) return cls(tokenizer=_a ,speaker_embeddings=_a ) def __lowercase ( self : List[str] ,_a : Tuple ,_a : Any="speaker_embeddings_path.json" ,_a : Optional[int]="speaker_embeddings" ,_a : bool = False ,**_a : Optional[int] ,): '''simple docstring''' if self.speaker_embeddings is not None: os.makedirs(os.path.join(_a ,_a ,'v2' ) ,exist_ok=_a ) _a : Optional[Any] = {} _a : List[str] = save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": _a : Any = self._load_voice_preset(_a ) _a : Tuple = {} for key in self.speaker_embeddings[prompt_key]: np.save( os.path.join( embeddings_dict['repo_or_path'] ,_a ,F"""{prompt_key}_{key}""" ) ,voice_preset[key] ,allow_pickle=_a ,) _a : Dict = os.path.join(_a ,F"""{prompt_key}_{key}.npy""" ) _a : Any = tmp_dict with open(os.path.join(_a ,_a ) ,'w' ) as fp: json.dump(_a ,_a ) super().save_pretrained(_a ,_a ,**_a ) def __lowercase ( self : Tuple ,_a : str = None ,**_a : List[Any] ): '''simple docstring''' _a : Optional[Any] = self.speaker_embeddings[voice_preset] _a : Optional[Any] = {} for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset_paths: raise ValueError( F"""Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}].""" ) _a : List[Any] = get_file_from_repo( self.speaker_embeddings.get('repo_or_path' ,'/' ) ,voice_preset_paths[key] ,subfolder=kwargs.pop('subfolder' ,_a ) ,cache_dir=kwargs.pop('cache_dir' ,_a ) ,force_download=kwargs.pop('force_download' ,_a ) ,proxies=kwargs.pop('proxies' ,_a ) ,resume_download=kwargs.pop('resume_download' ,_a ) ,local_files_only=kwargs.pop('local_files_only' ,_a ) ,use_auth_token=kwargs.pop('use_auth_token' ,_a ) ,revision=kwargs.pop('revision' ,_a ) ,) if path is None: raise ValueError( F"""`{os.path.join(self.speaker_embeddings.get('repo_or_path' ,'/' ) ,voice_preset_paths[key] )}` does not exists , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset} embeddings.""" ) _a : Tuple = np.load(_a ) return voice_preset_dict def __lowercase ( self : List[Any] ,_a : Optional[dict] = None ): '''simple docstring''' for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset: raise ValueError(F"""Voice preset unrecognized, missing {key} as a key.""" ) if not isinstance(voice_preset[key] ,np.ndarray ): raise ValueError(F"""{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.""" ) if len(voice_preset[key].shape ) != self.preset_shape[key]: raise ValueError(F"""{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.""" ) def __call__( self : Any ,_a : List[str]=None ,_a : Tuple=None ,_a : Tuple="pt" ,_a : Any=256 ,_a : Optional[Any]=False ,_a : List[str]=True ,_a : Optional[Any]=False ,**_a : Dict ,): '''simple docstring''' if voice_preset is not None and not isinstance(_a ,_a ): if ( isinstance(_a ,_a ) and self.speaker_embeddings is not None and voice_preset in self.speaker_embeddings ): _a : Union[str, Any] = self._load_voice_preset(_a ) else: if isinstance(_a ,_a ) and not voice_preset.endswith('.npz' ): _a : str = voice_preset + '.npz' _a : Optional[int] = np.load(_a ) if voice_preset is not None: self._validate_voice_preset_dict(_a ,**_a ) _a : List[str] = BatchFeature(data=_a ,tensor_type=_a ) _a : List[Any] = self.tokenizer( _a ,return_tensors=_a ,padding='max_length' ,max_length=_a ,return_attention_mask=_a ,return_token_type_ids=_a ,add_special_tokens=_a ,**_a ,) if voice_preset is not None: _a : Dict = voice_preset return encoded_text
319
1
import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def _lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def wrapper(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ): A_ = timeit.default_timer() A_ = func(*_UpperCamelCase , **_UpperCamelCase ) A_ = timeit.default_timer() - starttime return delta A_ = func.__name__ return wrapper def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=100 , SCREAMING_SNAKE_CASE=None ): '''simple docstring''' A_ = [] A_ = seq_shapes or {} for i in range(_UpperCamelCase ): A_ = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(_UpperCamelCase , _ArrayXD ): A_ = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(_UpperCamelCase , datasets.Value ): if v.dtype == "string": A_ = '''The small grey turtle was surprisingly fast when challenged.''' else: A_ = np.random.randint(10 , size=1 ).astype(v.dtype ).item() elif isinstance(_UpperCamelCase , datasets.Sequence ): while isinstance(_UpperCamelCase , datasets.Sequence ): A_ = v.feature A_ = seq_shapes[k] A_ = np.random.rand(*_UpperCamelCase ).astype(v.dtype ) A_ = data dummy_data.append((i, example) ) return dummy_data def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=100 , SCREAMING_SNAKE_CASE=None ): '''simple docstring''' A_ = generate_examples(_UpperCamelCase , num_examples=_UpperCamelCase , seq_shapes=_UpperCamelCase ) with ArrowWriter(features=_UpperCamelCase , path=_UpperCamelCase ) as writer: for key, record in dummy_data: A_ = features.encode_example(_UpperCamelCase ) writer.write(_UpperCamelCase ) A_ ,A_ = writer.finalize() if not num_final_examples == num_examples: raise ValueError( f"Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}." ) A_ = datasets.Dataset.from_file(filename=_UpperCamelCase , info=datasets.DatasetInfo(features=_UpperCamelCase ) ) return dataset
203
from __future__ import annotations from math import gcd def __lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : int = 2 , _UpperCamelCase : int = 1 , _UpperCamelCase : int = 3 , ) -> int | None: '''simple docstring''' if num < 2: raise ValueError('The input value cannot be less than 2' ) # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(_UpperCamelCase : int , _UpperCamelCase : int , _UpperCamelCase : int ) -> int: return (pow(_UpperCamelCase , 2 ) + step) % modulus for _ in range(_UpperCamelCase ): # These track the position within the cycle detection logic. SCREAMING_SNAKE_CASE = seed SCREAMING_SNAKE_CASE = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. SCREAMING_SNAKE_CASE = rand_fn(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) SCREAMING_SNAKE_CASE = rand_fn(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) SCREAMING_SNAKE_CASE = rand_fn(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. SCREAMING_SNAKE_CASE = gcd(hare - tortoise , _UpperCamelCase ) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. SCREAMING_SNAKE_CASE = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse a_ : int = argparse.ArgumentParser() parser.add_argument( "num", type=int, help="The value to find a divisor of", ) parser.add_argument( "--attempts", type=int, default=3, help="The number of attempts before giving up", ) a_ : Tuple = parser.parse_args() a_ : int = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(F"""{args.num} is probably prime""") else: a_ : Union[str, Any] = args.num // divisor print(F"""{args.num} = {divisor} * {quotient}""")
439
0
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class lowerCAmelCase ( __UpperCamelCase ): def __init__( self : List[Any] , UpperCAmelCase : pyspark.sql.DataFrame , UpperCAmelCase : Optional[NamedSplit] = None , UpperCAmelCase : Optional[Features] = None , UpperCAmelCase : bool = True , UpperCAmelCase : str = None , UpperCAmelCase : bool = False , UpperCAmelCase : str = None , UpperCAmelCase : bool = True , UpperCAmelCase : str = "arrow" , **UpperCAmelCase : Tuple , ) -> int: super().__init__( split=UpperCAmelCase , features=UpperCAmelCase , cache_dir=UpperCAmelCase , keep_in_memory=UpperCAmelCase , streaming=UpperCAmelCase , **UpperCAmelCase , ) lowerCamelCase__ : Union[str, Any] = load_from_cache_file lowerCamelCase__ : List[Any] = file_format lowerCamelCase__ : List[Any] = Spark( df=UpperCAmelCase , features=UpperCAmelCase , cache_dir=UpperCAmelCase , working_dir=UpperCAmelCase , **UpperCAmelCase , ) def A_ ( self : str ) -> Union[str, Any]: if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) lowerCamelCase__ : List[str] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=UpperCAmelCase , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
715
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class lowerCAmelCase ( unittest.TestCase ): def A_ ( self : str ) -> Union[str, Any]: lowerCamelCase__ : Optional[int] = 'laion/clap-htsat-unfused' lowerCamelCase__ : List[Any] = tempfile.mkdtemp() def A_ ( self : Optional[int] , **UpperCAmelCase : int ) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase ) def A_ ( self : Union[str, Any] , **UpperCAmelCase : Any ) -> List[str]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **UpperCAmelCase ) def A_ ( self : List[str] ) -> Dict: shutil.rmtree(self.tmpdirname ) def A_ ( self : Optional[Any] ) -> Optional[Any]: lowerCamelCase__ : Tuple = self.get_tokenizer() lowerCamelCase__ : Dict = self.get_feature_extractor() lowerCamelCase__ : Dict = ClapProcessor(tokenizer=UpperCAmelCase , feature_extractor=UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase__ : List[Any] = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , UpperCAmelCase ) def A_ ( self : str ) -> int: lowerCamelCase__ : Optional[Any] = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase__ : Dict = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowerCamelCase__ : Dict = self.get_feature_extractor(do_normalize=UpperCAmelCase , padding_value=1.0 ) lowerCamelCase__ : str = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , UpperCAmelCase ) def A_ ( self : List[Any] ) -> int: lowerCamelCase__ : Any = self.get_feature_extractor() lowerCamelCase__ : str = self.get_tokenizer() lowerCamelCase__ : Optional[Any] = ClapProcessor(tokenizer=UpperCAmelCase , feature_extractor=UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = floats_list((3, 1000) ) lowerCamelCase__ : Tuple = feature_extractor(UpperCAmelCase , return_tensors='np' ) lowerCamelCase__ : Tuple = processor(audios=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 A_ ( self : List[str] ) -> Tuple: lowerCamelCase__ : Dict = self.get_feature_extractor() lowerCamelCase__ : List[Any] = self.get_tokenizer() lowerCamelCase__ : Any = ClapProcessor(tokenizer=UpperCAmelCase , feature_extractor=UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = 'This is a test string' lowerCamelCase__ : Union[str, Any] = processor(text=UpperCAmelCase ) lowerCamelCase__ : Any = tokenizer(UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : Optional[int] ) -> Tuple: lowerCamelCase__ : Tuple = self.get_feature_extractor() lowerCamelCase__ : List[str] = self.get_tokenizer() lowerCamelCase__ : Optional[int] = ClapProcessor(tokenizer=UpperCAmelCase , feature_extractor=UpperCAmelCase ) lowerCamelCase__ : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCamelCase__ : List[Any] = processor.batch_decode(UpperCAmelCase ) lowerCamelCase__ : Tuple = tokenizer.batch_decode(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> int: lowerCamelCase__ : str = self.get_feature_extractor() lowerCamelCase__ : str = self.get_tokenizer() lowerCamelCase__ : Dict = ClapProcessor(tokenizer=UpperCAmelCase , feature_extractor=UpperCAmelCase ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
188
0
def UpperCamelCase_ ( __a ) -> bool: a__ : List[Any] = 0 for ch in input_str: a__ : str = ord(__a ) a__ : Any = pow(2 , __a ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
37
def lowerCamelCase ( UpperCamelCase : int ) -> bool: _lowerCamelCase = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def lowerCamelCase ( UpperCamelCase : int = 50_00 ) -> int: _lowerCamelCase = [(i * (3 * i - 1)) // 2 for i in range(1 , UpperCamelCase )] for i, pentagonal_i in enumerate(UpperCamelCase ): for j in range(UpperCamelCase , len(UpperCamelCase ) ): _lowerCamelCase = pentagonal_nums[j] _lowerCamelCase = pentagonal_i + pentagonal_j _lowerCamelCase = pentagonal_j - pentagonal_i if is_pentagonal(UpperCamelCase ) and is_pentagonal(UpperCamelCase ): return b return -1 if __name__ == "__main__": print(F'''{solution() = }''')
544
0
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
260
from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _lowercase ( A__ ): '''simple docstring''' def __init__( self :List[str] , lowerCAmelCase__ :TransformeraDModel , lowerCAmelCase__ :AutoencoderKL , lowerCAmelCase__ :KarrasDiffusionSchedulers , lowerCAmelCase__ :Optional[Dict[int, str]] = None , ) -> List[Any]: super().__init__() self.register_modules(transformer=lowerCAmelCase__ , vae=lowerCAmelCase__ , scheduler=lowerCAmelCase__ ) # create a imagenet -> id dictionary for easier use __SCREAMING_SNAKE_CASE : Dict = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split(''',''' ): __SCREAMING_SNAKE_CASE : int = int(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = dict(sorted(self.labels.items() ) ) def __magic_name__( self :List[Any] , lowerCAmelCase__ :Union[str, List[str]] ) -> List[int]: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __SCREAMING_SNAKE_CASE : Optional[Any] = list(lowerCAmelCase__ ) for l in label: if l not in self.labels: raise ValueError( f'''{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.''' ) return [self.labels[l] for l in label] @torch.no_grad() def __call__( self :Tuple , lowerCAmelCase__ :List[int] , lowerCAmelCase__ :float = 4.0 , lowerCAmelCase__ :Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCAmelCase__ :int = 50 , lowerCAmelCase__ :Optional[str] = "pil" , lowerCAmelCase__ :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: __SCREAMING_SNAKE_CASE : Any = len(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.transformer.config.sample_size __SCREAMING_SNAKE_CASE : Optional[Any] = self.transformer.config.in_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size) , generator=lowerCAmelCase__ , device=self.device , dtype=self.transformer.dtype , ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat([latents] * 2 ) if guidance_scale > 1 else latents __SCREAMING_SNAKE_CASE : str = torch.tensor(lowerCAmelCase__ , device=self.device ).reshape(-1 ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_000] * batch_size , device=self.device ) __SCREAMING_SNAKE_CASE : Tuple = torch.cat([class_labels, class_null] , 0 ) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(lowerCAmelCase__ ) for t in self.progress_bar(self.scheduler.timesteps ): if guidance_scale > 1: __SCREAMING_SNAKE_CASE : Optional[int] = latent_model_input[: len(lowerCAmelCase__ ) // 2] __SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat([half, half] , dim=0 ) __SCREAMING_SNAKE_CASE : Dict = self.scheduler.scale_model_input(lowerCAmelCase__ , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : List[str] = t if not torch.is_tensor(lowerCAmelCase__ ): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) __SCREAMING_SNAKE_CASE : Optional[int] = latent_model_input.device.type == '''mps''' if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __SCREAMING_SNAKE_CASE : Tuple = torch.floataa if is_mps else torch.floataa else: __SCREAMING_SNAKE_CASE : List[Any] = torch.intaa if is_mps else torch.intaa __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([timesteps] , dtype=lowerCAmelCase__ , device=latent_model_input.device ) elif len(timesteps.shape ) == 0: __SCREAMING_SNAKE_CASE : str = timesteps[None].to(latent_model_input.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __SCREAMING_SNAKE_CASE : str = timesteps.expand(latent_model_input.shape[0] ) # predict noise model_output __SCREAMING_SNAKE_CASE : Optional[Any] = self.transformer( lowerCAmelCase__ , timestep=lowerCAmelCase__ , class_labels=lowerCAmelCase__ ).sample # perform guidance if guidance_scale > 1: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = torch.split(lowerCAmelCase__ , len(lowerCAmelCase__ ) // 2 , dim=0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = uncond_eps + guidance_scale * (cond_eps - uncond_eps) __SCREAMING_SNAKE_CASE : Any = torch.cat([half_eps, half_eps] , dim=0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat([eps, rest] , dim=1 ) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = torch.split(lowerCAmelCase__ , lowerCAmelCase__ , dim=1 ) else: __SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred # compute previous image: x_t -> x_t-1 __SCREAMING_SNAKE_CASE : Tuple = self.scheduler.step(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ).prev_sample if guidance_scale > 1: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = latent_model_input.chunk(2 , dim=0 ) else: __SCREAMING_SNAKE_CASE : List[str] = latent_model_input __SCREAMING_SNAKE_CASE : Dict = 1 / self.vae.config.scaling_factor * latents __SCREAMING_SNAKE_CASE : Tuple = self.vae.decode(lowerCAmelCase__ ).sample __SCREAMING_SNAKE_CASE : int = (samples / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 __SCREAMING_SNAKE_CASE : Dict = samples.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __SCREAMING_SNAKE_CASE : str = self.numpy_to_pil(lowerCAmelCase__ ) if not return_dict: return (samples,) return ImagePipelineOutput(images=lowerCAmelCase__ )
260
1
'''simple docstring''' from typing import Dict from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, get_torch_dist_unique_port, require_torch_multi_gpu, require_torch_neuroncore, ) from transformers.training_args import ParallelMode from transformers.utils import logging a : Union[str, Any] = logging.get_logger(__name__) if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset from transformers import Trainer class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ): def __init__( self : Union[str, Any] , a_ : int = 101 ): """simple docstring""" __snake_case = length def __len__( self : Optional[Any] ): """simple docstring""" return self.length def __getitem__( self : Optional[Any] , a_ : Any ): """simple docstring""" return i class SCREAMING_SNAKE_CASE__ : def __call__( self : List[Any] , a_ : Any ): """simple docstring""" return {"input_ids": torch.tensor(a_ ), "labels": torch.tensor(a_ )} class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : Union[str, Any] ): """simple docstring""" super().__init__() # Add some (unused) params otherwise DDP will complain. __snake_case = nn.Linear(120 , 80 ) def A ( self : int , a_ : Optional[int] , a_ : List[Any]=None ): """simple docstring""" if labels is not None: return torch.tensor(0.0 , device=input_ids.device ), input_ids else: return input_ids class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ): @require_torch_neuroncore def A ( self : List[Any] ): """simple docstring""" __snake_case = f'''--nproc_per_node=2 --master_port={get_torch_dist_unique_port()} {self.test_file_dir}/test_trainer_distributed.py '''.split() __snake_case = self.get_auto_remove_tmp_dir() __snake_case = f'''--output_dir {output_dir}'''.split() __snake_case = ["torchrun"] + distributed_args + args execute_subprocess_async(a_ , env=self.get_env() ) # successful return here == success - any errors would have caused an error in the sub-call class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ): @require_torch_multi_gpu def A ( self : Any ): """simple docstring""" __snake_case = f'''--nproc_per_node={torch.cuda.device_count()} --master_port={get_torch_dist_unique_port()} {self.test_file_dir}/test_trainer_distributed.py '''.split() __snake_case = self.get_auto_remove_tmp_dir() __snake_case = f'''--output_dir {output_dir}'''.split() __snake_case = ["torchrun"] + distributed_args + args execute_subprocess_async(a_ , env=self.get_env() ) # successful return here == success - any errors would have caused an error in the sub-call if __name__ == "__main__": # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs: # # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_trainer_distributed.py a : Optional[Any] = HfArgumentParser((TrainingArguments,)) a : List[str] = parser.parse_args_into_dataclasses()[0] logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, ''' F'''distributed training: {training_args.parallel_mode != ParallelMode.NOT_DISTRIBUTED}''' ) # Essentially, what we want to verify in the distributed case is that we get all samples back, # in the right order. (this is crucial for prediction for instance) for dataset_length in [101, 40, 7]: a : Union[str, Any] = DummyDataset(dataset_length) def __UpperCAmelCase ( _UpperCAmelCase : EvalPrediction ) -> Dict: __snake_case = list(range(len(_UpperCAmelCase ) ) ) __snake_case = p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential if not success and training_args.local_rank == 0: logger.warning( "Predictions and/or labels do not match expected results:\n - predictions: " F'''{p.predictions.tolist()}\n - labels: {p.label_ids.tolist()}\n - expected: {sequential}''' ) return {"success": success} a : List[Any] = Trainer( model=DummyModel(), args=training_args, data_collator=DummyDataCollator(), eval_dataset=dataset, compute_metrics=compute_metrics, ) a : Optional[Any] = trainer.evaluate() logger.info(metrics) if metrics["eval_success"] is not True: logger.error(metrics) exit(1) a : Tuple = trainer.predict(dataset) logger.info(p.metrics) if p.metrics["test_success"] is not True: logger.error(p.metrics) exit(1) a : Any = 2 a : Union[str, Any] = trainer.evaluate() logger.info(metrics) if metrics["eval_success"] is not True: logger.error(metrics) exit(1) a : int = trainer.predict(dataset) logger.info(p.metrics) if p.metrics["test_success"] is not True: logger.error(p.metrics) exit(1) a : str = None
69
'''simple docstring''' import mpmath # for roots of unity import numpy as np class SCREAMING_SNAKE_CASE__ : def __init__( self : Tuple , a_ : Optional[int]=None , a_ : int=None ): """simple docstring""" __snake_case = list(poly_a or [0] )[:] __snake_case = list(poly_b or [0] )[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() __snake_case = len(self.polyA ) while self.polyB[-1] == 0: self.polyB.pop() __snake_case = len(self.polyB ) # Add 0 to make lengths equal a power of 2 __snake_case = int( 2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) ) while len(self.polyA ) < self.c_max_length: self.polyA.append(0 ) while len(self.polyB ) < self.c_max_length: self.polyB.append(0 ) # A complex root used for the fourier transform __snake_case = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) ) # The product __snake_case = self.__multiply() def A ( self : Any , a_ : Optional[Any] ): """simple docstring""" __snake_case = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB] # Corner case if len(a_ ) <= 1: return dft[0] # __snake_case = self.c_max_length // 2 while next_ncol > 0: __snake_case = [[] for i in range(a_ )] __snake_case = self.root**next_ncol # First half of next step __snake_case = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(a_ ): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] ) current_root *= root # Second half of next step __snake_case = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(a_ ): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] ) current_root *= root # Update __snake_case = new_dft __snake_case = next_ncol // 2 return dft[0] def A ( self : Union[str, Any] ): """simple docstring""" __snake_case = self.__dft("A" ) __snake_case = self.__dft("B" ) __snake_case = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]] del dft_a del dft_b # Corner Case if len(inverce_c[0] ) <= 1: return inverce_c[0] # Inverse DFT __snake_case = 2 while next_ncol <= self.c_max_length: __snake_case = [[] for i in range(a_ )] __snake_case = self.root ** (next_ncol // 2) __snake_case = 1 # First half of next step for j in range(self.c_max_length // next_ncol ): for i in range(next_ncol // 2 ): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update __snake_case = new_inverse_c next_ncol *= 2 # Unpack __snake_case = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self : Optional[int] ): """simple docstring""" __snake_case = "A = " + " + ".join( f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyA[: self.len_A] ) ) __snake_case = "B = " + " + ".join( f'''{coef}*x^{i}''' for coef, i in enumerate(self.polyB[: self.len_B] ) ) __snake_case = "A*B = " + " + ".join( f'''{coef}*x^{i}''' for coef, i in enumerate(self.product ) ) return f'''{a}\n{b}\n{c}''' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
69
1
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class _lowerCAmelCase ( UpperCamelCase_ ): """simple docstring""" lowerCAmelCase = 'EncodecFeatureExtractor' lowerCAmelCase = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self : List[Any] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : List[Any] ) -> Optional[int]: """simple docstring""" super().__init__(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) lowerCAmelCase = self.feature_extractor lowerCAmelCase = False def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE : str=None , SCREAMING_SNAKE_CASE : Union[str, Any]=None , SCREAMING_SNAKE_CASE : Union[str, Any]=True ) -> str: """simple docstring""" return self.tokenizer.get_decoder_prompt_ids(task=SCREAMING_SNAKE_CASE , language=SCREAMING_SNAKE_CASE , no_timestamps=SCREAMING_SNAKE_CASE ) def __call__( self : Optional[Any] , *SCREAMING_SNAKE_CASE : Tuple , **SCREAMING_SNAKE_CASE : str ) -> Optional[Any]: """simple docstring""" if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) lowerCAmelCase = kwargs.pop("audio" , SCREAMING_SNAKE_CASE ) lowerCAmelCase = kwargs.pop("sampling_rate" , SCREAMING_SNAKE_CASE ) lowerCAmelCase = kwargs.pop("text" , SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) > 0: lowerCAmelCase = args[0] lowerCAmelCase = args[1:] if audio is None and text is None: raise ValueError("You need to specify either an `audio` or `text` input to process." ) if text is not None: lowerCAmelCase = self.tokenizer(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if audio is not None: lowerCAmelCase = self.feature_extractor(SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , sampling_rate=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if audio is None: return inputs elif text is None: return audio_inputs else: lowerCAmelCase = audio_inputs["input_values"] if "padding_mask" in audio_inputs: lowerCAmelCase = audio_inputs["padding_mask"] return inputs def __A ( self : Dict , *SCREAMING_SNAKE_CASE : str , **SCREAMING_SNAKE_CASE : str ) -> int: """simple docstring""" lowerCAmelCase = kwargs.pop("audio" , SCREAMING_SNAKE_CASE ) lowerCAmelCase = kwargs.pop("padding_mask" , SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) > 0: lowerCAmelCase = args[0] lowerCAmelCase = args[1:] if audio_values is not None: return self._decode_audio(SCREAMING_SNAKE_CASE , padding_mask=SCREAMING_SNAKE_CASE ) else: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __A ( self : Dict , *SCREAMING_SNAKE_CASE : Optional[int] , **SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Optional[int]: """simple docstring""" return self.tokenizer.decode(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional = None ) -> List[np.ndarray]: """simple docstring""" lowerCAmelCase = to_numpy(SCREAMING_SNAKE_CASE ) lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = audio_values.shape if padding_mask is None: return list(SCREAMING_SNAKE_CASE ) lowerCAmelCase = to_numpy(SCREAMING_SNAKE_CASE ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) lowerCAmelCase = seq_len - padding_mask.shape[-1] lowerCAmelCase = 1 - self.feature_extractor.padding_value lowerCAmelCase = np.pad(SCREAMING_SNAKE_CASE , ((0, 0), (0, difference)) , "constant" , constant_values=SCREAMING_SNAKE_CASE ) lowerCAmelCase = audio_values.tolist() for i in range(SCREAMING_SNAKE_CASE ): lowerCAmelCase = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] lowerCAmelCase = sliced_audio.reshape(SCREAMING_SNAKE_CASE , -1 ) return audio_values
716
'''simple docstring''' import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Tuple , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : List[str]=1_3 , SCREAMING_SNAKE_CASE : Optional[Any]=7 , SCREAMING_SNAKE_CASE : Any=True , SCREAMING_SNAKE_CASE : List[Any]=True , SCREAMING_SNAKE_CASE : Union[str, Any]=True , SCREAMING_SNAKE_CASE : Optional[int]=True , SCREAMING_SNAKE_CASE : Optional[int]=9_9 , SCREAMING_SNAKE_CASE : Dict=3_2 , SCREAMING_SNAKE_CASE : Dict=5 , SCREAMING_SNAKE_CASE : Optional[int]=4 , SCREAMING_SNAKE_CASE : Optional[Any]=3_7 , SCREAMING_SNAKE_CASE : int="gelu" , SCREAMING_SNAKE_CASE : Any=0.1 , SCREAMING_SNAKE_CASE : int=0.1 , SCREAMING_SNAKE_CASE : Dict=5_1_2 , SCREAMING_SNAKE_CASE : Union[str, Any]=1_6 , SCREAMING_SNAKE_CASE : Dict=2 , SCREAMING_SNAKE_CASE : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE : Optional[int]=4 , ) -> Optional[int]: """simple docstring""" lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = seq_length lowerCAmelCase = is_training lowerCAmelCase = use_attention_mask lowerCAmelCase = use_token_type_ids lowerCAmelCase = use_labels lowerCAmelCase = vocab_size lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_act lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = max_position_embeddings lowerCAmelCase = type_vocab_size lowerCAmelCase = type_sequence_label_size lowerCAmelCase = initializer_range lowerCAmelCase = num_choices def __A ( self : List[str] ) -> List[str]: """simple docstring""" lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase = None if self.use_attention_mask: lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase = None if self.use_token_type_ids: lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase = RobertaConfig( 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=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __A ( self : Optional[int] ) -> Dict: """simple docstring""" lowerCAmelCase = self.prepare_config_and_inputs() lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = config_and_inputs lowerCAmelCase = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def __A ( self : List[Any] ) -> Any: """simple docstring""" lowerCAmelCase = self.prepare_config_and_inputs() lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = config_and_inputs lowerCAmelCase = True lowerCAmelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class _lowerCAmelCase ( UpperCamelCase_ , unittest.TestCase ): """simple docstring""" lowerCAmelCase = True lowerCAmelCase = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def __A ( self : Union[str, Any] ) -> Any: """simple docstring""" lowerCAmelCase = FlaxRobertaModelTester(self ) @slow def __A ( self : str ) -> Optional[Any]: """simple docstring""" for model_class_name in self.all_model_classes: lowerCAmelCase = model_class_name.from_pretrained("roberta-base" , from_pt=SCREAMING_SNAKE_CASE ) lowerCAmelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE )
159
0
import argparse import json import os import torch from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _A( UpperCamelCase__ : int , UpperCamelCase__ : Dict , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any] ) -> List[Any]: '''simple docstring''' with open(UpperCamelCase__ ) as metadata_file: __lowercase = json.load(UpperCamelCase__ ) __lowercase = LukeConfig(use_entity_aware_attention=UpperCamelCase__ , **metadata['''model_config'''] ) # Load in the weights from the checkpoint_path __lowercase = torch.load(UpperCamelCase__ , map_location='''cpu''' ) # Load the entity vocab file __lowercase = load_entity_vocab(UpperCamelCase__ ) __lowercase = RobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] ) # Add special tokens to the token vocabulary for downstream tasks __lowercase = AddedToken('''<ent>''' , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) __lowercase = AddedToken('''<ent2>''' , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'Saving tokenizer to {pytorch_dump_folder_path}' ) tokenizer.save_pretrained(UpperCamelCase__ ) with open(os.path.join(UpperCamelCase__ , LukeTokenizer.vocab_files_names['''entity_vocab_file'''] ) , '''w''' ) as f: json.dump(UpperCamelCase__ , UpperCamelCase__ ) __lowercase = LukeTokenizer.from_pretrained(UpperCamelCase__ ) # Initialize the embeddings of the special tokens __lowercase = state_dict['''embeddings.word_embeddings.weight'''] __lowercase = word_emb[tokenizer.convert_tokens_to_ids(['''@'''] )[0]].unsqueeze(0 ) __lowercase = word_emb[tokenizer.convert_tokens_to_ids(['''#'''] )[0]].unsqueeze(0 ) __lowercase = torch.cat([word_emb, ent_emb, enta_emb] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: __lowercase = F'encoder.layer.{layer_index}.attention.self.' __lowercase = state_dict[prefix + matrix_name] __lowercase = state_dict[prefix + matrix_name] __lowercase = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks __lowercase = state_dict['''entity_embeddings.entity_embeddings.weight'''] __lowercase = entity_emb[entity_vocab['''[MASK]''']] __lowercase = LukeModel(config=UpperCamelCase__ ).eval() __lowercase , __lowercase = model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) if not (len(UpperCamelCase__ ) == 1 and missing_keys[0] == "embeddings.position_ids"): raise ValueError(F'Missing keys {", ".join(UpperCamelCase__ )}. Expected only missing embeddings.position_ids' ) if not (all(key.startswith('''entity_predictions''' ) or key.startswith('''lm_head''' ) for key in unexpected_keys )): raise ValueError( '''Unexpected keys''' F' {", ".join([key for key in unexpected_keys if not (key.startswith("entity_predictions" ) or key.startswith("lm_head" ))] )}' ) # Check outputs __lowercase = LukeTokenizer.from_pretrained(UpperCamelCase__ , task='''entity_classification''' ) __lowercase = ( '''Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the''' ''' new world number one avoid a humiliating second- round exit at Wimbledon .''' ) __lowercase = (39, 42) __lowercase = tokenizer(UpperCamelCase__ , entity_spans=[span] , add_prefix_space=UpperCamelCase__ , return_tensors='''pt''' ) __lowercase = model(**UpperCamelCase__ ) # Verify word hidden states if model_size == "large": __lowercase = torch.Size((1, 42, 1024) ) __lowercase = torch.tensor( [[0.0133, 0.0865, 0.0095], [0.3093, -0.2576, -0.7418], [-0.1720, -0.2117, -0.2869]] ) else: # base __lowercase = torch.Size((1, 42, 768) ) __lowercase = torch.tensor([[0.0037, 0.1368, -0.0091], [0.1099, 0.3329, -0.1095], [0.0765, 0.5335, 0.1179]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCamelCase__ , atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": __lowercase = torch.Size((1, 1, 1024) ) __lowercase = torch.tensor([[0.0466, -0.0106, -0.0179]] ) else: # base __lowercase = torch.Size((1, 1, 768) ) __lowercase = torch.tensor([[0.1457, 0.1044, 0.0174]] ) if not (outputs.entity_last_hidden_state.shape != expected_shape): raise ValueError( F'Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is' F' {expected_shape}' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , UpperCamelCase__ , atol=1e-4 ): raise ValueError # Finally, save our PyTorch model and tokenizer print('''Saving PyTorch model to {}'''.format(UpperCamelCase__ ) ) model.save_pretrained(UpperCamelCase__ ) def _A( UpperCamelCase__ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __lowercase = {} with open(UpperCamelCase__ , '''r''' , encoding='''utf-8''' ) as f: for index, line in enumerate(UpperCamelCase__ ): __lowercase , __lowercase = line.rstrip().split('''\t''' ) __lowercase = index return entity_vocab if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument("--checkpoint_path", type=str, help="Path to a pytorch_model.bin file.") parser.add_argument( "--metadata_path", default=None, type=str, help="Path to a metadata.json file, defining the configuration." ) parser.add_argument( "--entity_vocab_path", default=None, type=str, help="Path to an entity_vocab.tsv file, containing the entity vocabulary.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to where to dump the output PyTorch model." ) parser.add_argument( "--model_size", default="base", type=str, choices=["base", "large"], help="Size of the model to be converted." ) UpperCAmelCase__ = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
332
import unittest from knapsack import knapsack as k class a ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: """simple docstring""" __lowercase = 0 __lowercase = [0] __lowercase = [0] __lowercase = len(lowerCamelCase__ ) self.assertEqual(k.knapsack(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , 0 ) __lowercase = [60] __lowercase = [10] __lowercase = len(lowerCamelCase__ ) self.assertEqual(k.knapsack(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , 0 ) def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: """simple docstring""" __lowercase = 3 __lowercase = [1, 2, 3] __lowercase = [3, 2, 1] __lowercase = len(lowerCamelCase__ ) self.assertEqual(k.knapsack(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , 5 ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: """simple docstring""" __lowercase = 50 __lowercase = [60, 100, 120] __lowercase = [10, 20, 30] __lowercase = len(lowerCamelCase__ ) self.assertEqual(k.knapsack(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , 220 ) if __name__ == "__main__": unittest.main()
332
1
"""simple docstring""" import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed _UpperCAmelCase = """true""" def __magic_name__ ( lowercase , lowercase=82 , lowercase=16 ): set_seed(42 ) SCREAMING_SNAKE_CASE_: List[str] =RegressionModel() SCREAMING_SNAKE_CASE_: Dict =deepcopy(lowercase ) SCREAMING_SNAKE_CASE_: str =RegressionDataset(length=lowercase ) SCREAMING_SNAKE_CASE_: Dict =DataLoader(lowercase , batch_size=lowercase ) model.to(accelerator.device ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =accelerator.prepare(lowercase , lowercase ) return model, ddp_model, dataloader def __magic_name__ ( lowercase , lowercase=False ): SCREAMING_SNAKE_CASE_: Optional[int] =AutoTokenizer.from_pretrained("""hf-internal-testing/mrpc-bert-base-cased""" ) SCREAMING_SNAKE_CASE_: List[str] =load_dataset("""glue""" , """mrpc""" , split="""validation""" ) def tokenize_function(lowercase ): SCREAMING_SNAKE_CASE_: int =tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowercase , max_length=lowercase ) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE_: Optional[Any] =dataset.map( lowercase , batched=lowercase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) SCREAMING_SNAKE_CASE_: Dict =tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(lowercase ): if use_longest: return tokenizer.pad(lowercase , padding="""longest""" , return_tensors="""pt""" ) return tokenizer.pad(lowercase , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return DataLoader(lowercase , shuffle=lowercase , collate_fn=lowercase , batch_size=16 ) def __magic_name__ ( lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Optional[int] =Accelerator(dispatch_batches=lowercase , split_batches=lowercase ) SCREAMING_SNAKE_CASE_: str =get_dataloader(lowercase , not dispatch_batches ) SCREAMING_SNAKE_CASE_: Optional[Any] =AutoModelForSequenceClassification.from_pretrained( """hf-internal-testing/mrpc-bert-base-cased""" , return_dict=lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =accelerator.prepare(lowercase , lowercase ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def __magic_name__ ( lowercase , lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Dict =[] for batch in dataloader: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE_: Union[str, Any] =model(lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Any =[], [] for logit, targ in logits_and_targets: logits.append(lowercase ) targs.append(lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =torch.cat(lowercase ), torch.cat(lowercase ) return logits, targs def __magic_name__ ( lowercase , lowercase=82 , lowercase=False , lowercase=False , lowercase=16 ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =get_basic_setup(lowercase , lowercase , lowercase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: int =generate_predictions(lowercase , lowercase , lowercase ) assert ( len(lowercase ) == num_samples ), f'''Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(lowercase )}''' def __magic_name__ ( lowercase = False , lowercase = False ): SCREAMING_SNAKE_CASE_: Dict =evaluate.load("""glue""" , """mrpc""" ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =get_mrpc_setup(lowercase , lowercase ) # First do baseline SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =setup["""no"""] model.to(lowercase ) model.eval() for batch in dataloader: batch.to(lowercase ) with torch.inference_mode(): SCREAMING_SNAKE_CASE_: Optional[int] =model(**lowercase ) SCREAMING_SNAKE_CASE_: int =outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=lowercase , references=batch["""labels"""] ) SCREAMING_SNAKE_CASE_: Optional[int] =metric.compute() # Then do distributed SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =setup["""ddp"""] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE_: Optional[Any] =model(**lowercase ) SCREAMING_SNAKE_CASE_: Any =outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE_: Dict =batch["""labels"""] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Tuple =accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=lowercase , references=lowercase ) SCREAMING_SNAKE_CASE_: str =metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key] ), f'''Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n''' def __magic_name__ ( ): SCREAMING_SNAKE_CASE_: Optional[Any] =Accelerator(split_batches=lowercase , dispatch_batches=lowercase ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print("""**Testing gather_for_metrics**""" ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(f'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`''' ) test_mrpc(lowercase , lowercase ) accelerator.state._reset_state() if accelerator.is_local_main_process: print("""**Test torch metrics**""" ) for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE_: Dict =Accelerator(split_batches=lowercase , dispatch_batches=lowercase ) if accelerator.is_local_main_process: print(f'''With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99''' ) test_torch_metrics(lowercase , 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print("""**Test last batch is not dropped when perfectly divisible**""" ) SCREAMING_SNAKE_CASE_: List[str] =Accelerator() test_torch_metrics(lowercase , 512 ) accelerator.state._reset_state() def __magic_name__ ( lowercase ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
36
"""simple docstring""" def __magic_name__ ( lowercase ): SCREAMING_SNAKE_CASE_: int =False while is_sorted is False: # Until all the indices are traversed keep looping SCREAMING_SNAKE_CASE_: Tuple =True for i in range(0 , len(lowercase ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: Tuple =False for i in range(1 , len(lowercase ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: str =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE_: str =False return input_list if __name__ == "__main__": print("""Enter list to be sorted""") _UpperCAmelCase = [int(x) for x in input().split()] # inputing elements of the list in one line _UpperCAmelCase = odd_even_sort(input_list) print("""The sorted list is""") print(sorted_list)
36
1
import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params A_ : Optional[Any] = getLogger(__name__) A_ : List[str] = 'cuda' if torch.cuda.is_available() else 'cpu' def __a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 8 , SCREAMING_SNAKE_CASE = DEFAULT_DEVICE , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="summarization" , SCREAMING_SNAKE_CASE=None , **SCREAMING_SNAKE_CASE , ) -> Dict: '''simple docstring''' __UpperCAmelCase = Path(SCREAMING_SNAKE_CASE ).open('''w''' , encoding='''utf-8''' ) __UpperCAmelCase = str(SCREAMING_SNAKE_CASE ) __UpperCAmelCase = AutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE ).to(SCREAMING_SNAKE_CASE ) if fpaa: __UpperCAmelCase = model.half() __UpperCAmelCase = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) logger.info(f'''Inferred tokenizer type: {tokenizer.__class__}''' ) # if this is wrong, check config.model_type. __UpperCAmelCase = time.time() # update config with task specific params use_task_specific_params(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if prefix is None: __UpperCAmelCase = prefix or getattr(model.config , '''prefix''' , '''''' ) or '''''' for examples_chunk in tqdm(list(chunks(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ): __UpperCAmelCase = [prefix + text for text in examples_chunk] __UpperCAmelCase = tokenizer(SCREAMING_SNAKE_CASE , return_tensors='''pt''' , truncation=SCREAMING_SNAKE_CASE , padding='''longest''' ).to(SCREAMING_SNAKE_CASE ) __UpperCAmelCase = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **SCREAMING_SNAKE_CASE , ) __UpperCAmelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE ) for hypothesis in dec: fout.write(hypothesis + '''\n''' ) fout.flush() fout.close() __UpperCAmelCase = int(time.time() - start_time ) # seconds __UpperCAmelCase = len(SCREAMING_SNAKE_CASE ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def __a ( ) -> Tuple: '''simple docstring''' return datetime.datetime.now().strftime('''%Y-%m-%d %H:%M:%S''' ) def __a ( SCREAMING_SNAKE_CASE=True ) -> int: '''simple docstring''' __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('''model_name''' , type=SCREAMING_SNAKE_CASE , help='''like facebook/bart-large-cnn,t5-base, etc.''' ) parser.add_argument('''input_path''' , type=SCREAMING_SNAKE_CASE , help='''like cnn_dm/test.source''' ) parser.add_argument('''save_path''' , type=SCREAMING_SNAKE_CASE , help='''where to save summaries''' ) parser.add_argument('''--reference_path''' , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , help='''like cnn_dm/test.target''' ) parser.add_argument('''--score_path''' , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , default='''metrics.json''' , help='''where to save metrics''' ) parser.add_argument('''--device''' , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , help='''cuda, cuda:1, cpu etc.''' ) parser.add_argument( '''--prefix''' , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , help='''will be added to the begininng of src examples''' ) parser.add_argument('''--task''' , type=SCREAMING_SNAKE_CASE , default='''summarization''' , help='''used for task_specific_params + metrics''' ) parser.add_argument('''--bs''' , type=SCREAMING_SNAKE_CASE , default=8 , required=SCREAMING_SNAKE_CASE , help='''batch size''' ) parser.add_argument( '''--n_obs''' , type=SCREAMING_SNAKE_CASE , default=-1 , required=SCREAMING_SNAKE_CASE , help='''How many observations. Defaults to all.''' ) parser.add_argument('''--fp16''' , action='''store_true''' ) parser.add_argument('''--dump-args''' , action='''store_true''' , help='''print the custom hparams with the results''' ) parser.add_argument( '''--info''' , nargs='''?''' , type=SCREAMING_SNAKE_CASE , const=datetime_now() , help=( '''use in conjunction w/ --dump-args to print with the results whatever other info you\'d like, e.g.''' ''' lang=en-ru. If no value is passed, the current datetime string will be used.''' ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate __UpperCAmelCase , __UpperCAmelCase = parser.parse_known_args() __UpperCAmelCase = parse_numeric_n_bool_cl_kwargs(SCREAMING_SNAKE_CASE ) if parsed_args and verbose: print(f'''parsed the following generate kwargs: {parsed_args}''' ) __UpperCAmelCase = [''' ''' + x.rstrip() if '''t5''' in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: __UpperCAmelCase = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=SCREAMING_SNAKE_CASE ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(f'''score_path {args.score_path} will be overwritten unless you type ctrl-c.''' ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError('''Can\'t mix --fp16 and --device cpu''' ) __UpperCAmelCase = generate_summaries_or_translations( SCREAMING_SNAKE_CASE , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **SCREAMING_SNAKE_CASE , ) if args.reference_path is None: return {} # Compute scores __UpperCAmelCase = calculate_bleu if '''translation''' in args.task else calculate_rouge __UpperCAmelCase = [x.rstrip() for x in open(args.save_path ).readlines()] __UpperCAmelCase = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(SCREAMING_SNAKE_CASE )] __UpperCAmelCase = score_fn(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) scores.update(SCREAMING_SNAKE_CASE ) if args.dump_args: scores.update(SCREAMING_SNAKE_CASE ) if args.info: __UpperCAmelCase = args.info if verbose: print(SCREAMING_SNAKE_CASE ) if args.score_path is not None: json.dump(SCREAMING_SNAKE_CASE , open(args.score_path , '''w''' ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
303
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable 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 .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
303
1
from PIL import Image def A__ ( __lowerCamelCase ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = image.size SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = image.load() for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): SCREAMING_SNAKE_CASE_ = pixels[j, i] mean += pixel mean //= width * height for j in range(__lowerCamelCase ): for i in range(__lowerCamelCase ): SCREAMING_SNAKE_CASE_ = 2_55 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": __UpperCAmelCase = mean_threshold(Image.open("path_to_image").convert("L")) image.save("output_image_path")
597
from PIL import Image def A__ ( __lowerCamelCase ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = image.size SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = image.load() for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): SCREAMING_SNAKE_CASE_ = pixels[j, i] mean += pixel mean //= width * height for j in range(__lowerCamelCase ): for i in range(__lowerCamelCase ): SCREAMING_SNAKE_CASE_ = 2_55 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": __UpperCAmelCase = mean_threshold(Image.open("path_to_image").convert("L")) image.save("output_image_path")
597
1
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class __magic_name__ : _lowerCAmelCase = 42 # setable values _lowerCAmelCase = 42 _lowerCAmelCase = 42 _lowerCAmelCase = None @classmethod def _A ( cls : List[str] , lowerCamelCase__ : CommonSchedulerState , lowerCamelCase__ : jnp.ndarray , lowerCamelCase__ : jnp.ndarray ): return cls(common=lowerCamelCase__ , init_noise_sigma=lowerCamelCase__ , timesteps=lowerCamelCase__ ) @dataclass class __magic_name__ ( snake_case ): _lowerCAmelCase = 42 class __magic_name__ ( snake_case, snake_case ): _lowerCAmelCase = [e.name for e in FlaxKarrasDiffusionSchedulers] _lowerCAmelCase = 42 @property def _A ( self : Union[str, Any] ): return True @register_to_config def __init__( self : Dict , lowerCamelCase__ : int = 1_0_0_0 , lowerCamelCase__ : float = 0.0_0_0_1 , lowerCamelCase__ : float = 0.0_2 , lowerCamelCase__ : str = "linear" , lowerCamelCase__ : Optional[jnp.ndarray] = None , lowerCamelCase__ : str = "fixed_small" , lowerCamelCase__ : bool = True , lowerCamelCase__ : str = "epsilon" , lowerCamelCase__ : jnp.dtype = jnp.floataa , ): lowerCAmelCase : Dict = dtype def _A ( self : List[Any] , lowerCamelCase__ : Optional[CommonSchedulerState] = None ): if common is None: lowerCAmelCase : List[Any] = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowerCAmelCase : List[str] = jnp.array(1.0 , dtype=self.dtype ) lowerCAmelCase : Union[str, Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=lowerCamelCase__ , init_noise_sigma=lowerCamelCase__ , timesteps=lowerCamelCase__ , ) def _A ( self : List[Any] , lowerCamelCase__ : DDPMSchedulerState , lowerCamelCase__ : jnp.ndarray , lowerCamelCase__ : Optional[int] = None ): return sample def _A ( self : Dict , lowerCamelCase__ : DDPMSchedulerState , lowerCamelCase__ : int , lowerCamelCase__ : Tuple = () ): lowerCAmelCase : Tuple = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowerCAmelCase : Tuple = (jnp.arange(0 , lowerCamelCase__ ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=lowerCamelCase__ , timesteps=lowerCamelCase__ , ) def _A ( self : List[str] , lowerCamelCase__ : DDPMSchedulerState , lowerCamelCase__ : Dict , lowerCamelCase__ : Optional[int]=None , lowerCamelCase__ : Union[str, Any]=None ): lowerCAmelCase : Optional[Any] = state.common.alphas_cumprod[t] lowerCAmelCase : List[str] = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowerCAmelCase : Optional[Any] = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowerCAmelCase : Dict = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowerCAmelCase : Tuple = jnp.clip(lowerCamelCase__ , a_min=1E-20 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowerCAmelCase : List[str] = jnp.log(jnp.clip(lowerCamelCase__ , a_min=1E-20 ) ) elif variance_type == "fixed_large": lowerCAmelCase : int = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowerCAmelCase : List[Any] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowerCAmelCase : Optional[int] = variance lowerCAmelCase : Dict = state.common.betas[t] lowerCAmelCase : Tuple = (predicted_variance + 1) / 2 lowerCAmelCase : Optional[int] = frac * max_log + (1 - frac) * min_log return variance def _A ( self : List[str] , lowerCamelCase__ : DDPMSchedulerState , lowerCamelCase__ : jnp.ndarray , lowerCamelCase__ : int , lowerCamelCase__ : jnp.ndarray , lowerCamelCase__ : Optional[jax.random.KeyArray] = None , lowerCamelCase__ : bool = True , ): lowerCAmelCase : Optional[int] = timestep if key is None: lowerCAmelCase : Optional[Any] = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowerCAmelCase , lowerCAmelCase : Dict = jnp.split(lowerCamelCase__ , sample.shape[1] , axis=1 ) else: lowerCAmelCase : Optional[int] = None # 1. compute alphas, betas lowerCAmelCase : List[Any] = state.common.alphas_cumprod[t] lowerCAmelCase : Dict = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) lowerCAmelCase : int = 1 - alpha_prod_t lowerCAmelCase : List[Any] = 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 self.config.prediction_type == "epsilon": lowerCAmelCase : Any = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowerCAmelCase : Tuple = model_output elif self.config.prediction_type == "v_prediction": lowerCAmelCase : List[str] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowerCAmelCase : int = jnp.clip(lowerCamelCase__ , -1 , 1 ) # 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 lowerCAmelCase : Union[str, Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowerCAmelCase : int = state.common.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 lowerCAmelCase : Tuple = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowerCAmelCase : Optional[int] = jax.random.split(lowerCamelCase__ , num=1 ) lowerCAmelCase : str = jax.random.normal(lowerCamelCase__ , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(lowerCamelCase__ , lowerCamelCase__ , predicted_variance=lowerCamelCase__ ) ** 0.5) * noise lowerCAmelCase : int = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) lowerCAmelCase : List[Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=lowerCamelCase__ , state=lowerCamelCase__ ) def _A ( self : List[str] , lowerCamelCase__ : DDPMSchedulerState , lowerCamelCase__ : jnp.ndarray , lowerCamelCase__ : jnp.ndarray , lowerCamelCase__ : jnp.ndarray , ): return add_noise_common(state.common , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def _A ( self : int , lowerCamelCase__ : DDPMSchedulerState , lowerCamelCase__ : jnp.ndarray , lowerCamelCase__ : jnp.ndarray , lowerCamelCase__ : jnp.ndarray , ): return get_velocity_common(state.common , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def __len__( self : Any ): return self.config.num_train_timesteps
348
import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class __magic_name__ : def __init__( self : Any , lowerCamelCase__ : List[str] , lowerCamelCase__ : str=None , lowerCamelCase__ : Optional[int]=None , lowerCamelCase__ : List[str]=None , lowerCamelCase__ : List[str]="resnet50" , lowerCamelCase__ : str=3 , lowerCamelCase__ : List[Any]=3_2 , lowerCamelCase__ : Dict=3 , lowerCamelCase__ : int=True , lowerCamelCase__ : Dict=True , ): lowerCAmelCase : Tuple = parent lowerCAmelCase : List[Any] = out_indices if out_indices is not None else [4] lowerCAmelCase : Optional[Any] = stage_names lowerCAmelCase : List[Any] = out_features lowerCAmelCase : Optional[Any] = backbone lowerCAmelCase : str = batch_size lowerCAmelCase : List[Any] = image_size lowerCAmelCase : List[str] = num_channels lowerCAmelCase : int = use_pretrained_backbone lowerCAmelCase : Optional[Any] = is_training def _A ( self : Any ): lowerCAmelCase : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase : Union[str, Any] = self.get_config() return config, pixel_values def _A ( self : int ): return TimmBackboneConfig( image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , ) def _A ( self : Optional[Any] , lowerCamelCase__ : int , lowerCamelCase__ : str ): lowerCAmelCase : List[str] = TimmBackbone(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() with torch.no_grad(): lowerCAmelCase : Optional[Any] = model(lowerCamelCase__ ) self.parent.assertEqual( result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 1_4, 1_4) , ) def _A ( self : int ): lowerCAmelCase : Any = self.prepare_config_and_inputs() lowerCAmelCase , lowerCAmelCase : str = config_and_inputs lowerCAmelCase : Optional[int] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch @require_timm class __magic_name__ ( snake_case, snake_case, snake_case, unittest.TestCase ): _lowerCAmelCase = (TimmBackbone,) if is_torch_available() else () _lowerCAmelCase = {"feature-extraction": TimmBackbone} if is_torch_available() else {} _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def _A ( self : Optional[Any] ): lowerCAmelCase : Optional[int] = TimmBackboneModelTester(self ) lowerCAmelCase : Tuple = ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ ) def _A ( self : Optional[Any] ): 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 _A ( self : int ): lowerCAmelCase : Any = '''resnet18''' lowerCAmelCase : Optional[Any] = '''microsoft/resnet-18''' lowerCAmelCase : Union[str, Any] = AutoBackbone.from_pretrained(lowerCamelCase__ , use_timm_backbone=lowerCamelCase__ ) lowerCAmelCase : Dict = AutoBackbone.from_pretrained(lowerCamelCase__ ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices , (-1,) ) self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] ) lowerCAmelCase : Optional[int] = AutoBackbone.from_pretrained(lowerCamelCase__ , use_timm_backbone=lowerCamelCase__ , out_indices=[1, 2, 3] ) lowerCAmelCase : Optional[int] = AutoBackbone.from_pretrained(lowerCamelCase__ , out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices , transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) @unittest.skip('''TimmBackbone doesn\'t support feed forward chunking''' ) def _A ( self : List[str] ): pass @unittest.skip('''TimmBackbone doesn\'t have num_hidden_layers attribute''' ) def _A ( self : Optional[int] ): pass @unittest.skip('''TimmBackbone initialization is managed on the timm side''' ) def _A ( self : int ): pass @unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''' ) def _A ( self : str ): pass @unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''' ) def _A ( self : Dict ): pass @unittest.skip('''TimmBackbone model cannot be created without specifying a backbone checkpoint''' ) def _A ( self : List[Any] ): pass @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''' ) def _A ( self : List[str] ): pass @unittest.skip('''model weights aren\'t tied in TimmBackbone.''' ) def _A ( self : Optional[int] ): pass @unittest.skip('''model weights aren\'t tied in TimmBackbone.''' ) def _A ( self : List[Any] ): pass @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''' ) def _A ( self : int ): pass @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''' ) def _A ( self : Tuple ): pass @unittest.skip('''TimmBackbone doesn\'t have hidden size info in its configuration.''' ) def _A ( self : List[Any] ): pass @unittest.skip('''TimmBackbone doesn\'t support output_attentions.''' ) def _A ( self : Tuple ): pass @unittest.skip('''Safetensors is not supported by timm.''' ) def _A ( self : Tuple ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def _A ( self : int ): pass def _A ( self : Union[str, Any] ): lowerCAmelCase , lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase : Union[str, Any] = model_class(lowerCamelCase__ ) lowerCAmelCase : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase : Optional[int] = [*signature.parameters.keys()] lowerCAmelCase : Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowerCamelCase__ ) def _A ( self : int ): lowerCAmelCase , lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Tuple = True lowerCAmelCase : Any = self.has_attentions # no need to test all models as different heads yield the same functionality lowerCAmelCase : Dict = self.all_model_classes[0] lowerCAmelCase : Optional[int] = model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) lowerCAmelCase : Any = self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ ) lowerCAmelCase : int = model(**lowerCamelCase__ ) lowerCAmelCase : Optional[Any] = outputs[0][-1] # Encoder-/Decoder-only models lowerCAmelCase : Any = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: lowerCAmelCase : Optional[Any] = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=lowerCamelCase__ ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def _A ( self : Tuple ): lowerCAmelCase , lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase : Union[str, Any] = model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() lowerCAmelCase : Optional[int] = model(**lowerCamelCase__ ) self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) ) self.assertEqual(len(model.channels ) , len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None lowerCAmelCase : str = copy.deepcopy(lowerCamelCase__ ) lowerCAmelCase : int = None lowerCAmelCase : Optional[int] = model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() lowerCAmelCase : Any = model(**lowerCamelCase__ ) self.assertEqual(len(result.feature_maps ) , 1 ) self.assertEqual(len(model.channels ) , 1 ) # Check backbone can be initialized with fresh weights lowerCAmelCase : Optional[Any] = copy.deepcopy(lowerCamelCase__ ) lowerCAmelCase : Any = False lowerCAmelCase : Dict = model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() lowerCAmelCase : List[Any] = model(**lowerCamelCase__ )
348
1
# Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries import numpy as np from matplotlib import pyplot as plt from sklearn import datasets def _lowerCamelCase ( A_ : Any ) -> str: '''simple docstring''' return 1 / (1 + np.exp(-z )) def _lowerCamelCase ( A_ : Optional[Any] , A_ : int ) -> str: '''simple docstring''' return (-y * np.log(A_ ) - (1 - y) * np.log(1 - h )).mean() def _lowerCamelCase ( A_ : Any , A_ : Union[str, Any] , A_ : str ) -> Dict: '''simple docstring''' UpperCamelCase__ : Dict =np.dot(A_ , A_ ) return np.sum(y * scores - np.log(1 + np.exp(A_ ) ) ) def _lowerCamelCase ( A_ : Optional[int] , A_ : List[str] , A_ : Any , A_ : Dict=7_0_0_0_0 ) -> Dict: '''simple docstring''' UpperCamelCase__ : Tuple =np.zeros(x.shape[1] ) for iterations in range(A_ ): UpperCamelCase__ : List[Any] =np.dot(A_ , A_ ) UpperCamelCase__ : Optional[int] =sigmoid_function(A_ ) UpperCamelCase__ : Optional[Any] =np.dot(x.T , h - y ) / y.size UpperCamelCase__ : Optional[int] =theta - alpha * gradient # updating the weights UpperCamelCase__ : Union[str, Any] =np.dot(A_ , A_ ) UpperCamelCase__ : Any =sigmoid_function(A_ ) UpperCamelCase__ : Dict =cost_function(A_ , A_ ) if iterations % 1_0_0 == 0: print(f'''loss: {j} \t''' ) # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": __UpperCAmelCase = datasets.load_iris() __UpperCAmelCase = iris.data[:, :2] __UpperCAmelCase = (iris.target != 0) * 1 __UpperCAmelCase = 0.1 __UpperCAmelCase = logistic_reg(alpha, x, y, max_iterations=7_0000) print("""theta: """, theta) # printing the theta i.e our weights vector def _lowerCamelCase ( A_ : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' return sigmoid_function( np.dot(A_ , A_ ) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color="""b""", label="""0""") plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color="""r""", label="""1""") ((__UpperCAmelCase) , (__UpperCAmelCase)) = (x[:, 0].min(), x[:, 0].max()) ((__UpperCAmelCase) , (__UpperCAmelCase)) = (x[:, 1].min(), x[:, 1].max()) ((__UpperCAmelCase) , (__UpperCAmelCase)) = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max)) __UpperCAmelCase = np.c_[xxa.ravel(), xxa.ravel()] __UpperCAmelCase = predict_prob(grid).reshape(xxa.shape) plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors="""black""") plt.legend() plt.show()
582
from math import factorial __UpperCAmelCase = {str(digit): factorial(digit) for digit in range(10)} def _lowerCamelCase ( A_ : int ) -> int: '''simple docstring''' if not isinstance(A_ , A_ ): raise TypeError("Parameter number must be int" ) if number < 0: raise ValueError("Parameter number must be greater than or equal to 0" ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(A_ ) ) def _lowerCamelCase ( A_ : int = 6_0 , A_ : int = 1_0_0_0_0_0_0 ) -> int: '''simple docstring''' if not isinstance(A_ , A_ ) or not isinstance(A_ , A_ ): raise TypeError("Parameters chain_length and number_limit must be int" ) if chain_length <= 0 or number_limit <= 0: raise ValueError( "Parameters chain_length and number_limit must be greater than 0" ) # the counter for the chains with the exact desired length UpperCamelCase__ : str =0 # the cached sizes of the previous chains UpperCamelCase__ : dict[int, int] ={} for start_chain_element in range(1 , A_ ): # The temporary set will contain the elements of the chain UpperCamelCase__ : Any =set() UpperCamelCase__ : Optional[Any] =0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. UpperCamelCase__ : str =start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(A_ ) chain_set_length += 1 UpperCamelCase__ : Tuple =digit_factorial_sum(A_ ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] UpperCamelCase__ : List[str] =chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
582
1
import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging A_ : List[Any] = logging.get_logger(__name__) logging.set_verbosity_info() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> int: if "xprophetnet" in prophetnet_checkpoint_path: UpperCamelCase_: Union[str, Any] = XLMProphetNetForConditionalGenerationOld.from_pretrained(__SCREAMING_SNAKE_CASE ) UpperCamelCase_ ,UpperCamelCase_: str = XLMProphetNetForConditionalGeneration.from_pretrained( __SCREAMING_SNAKE_CASE , output_loading_info=__SCREAMING_SNAKE_CASE ) else: UpperCamelCase_: List[Any] = ProphetNetForConditionalGenerationOld.from_pretrained(__SCREAMING_SNAKE_CASE ) UpperCamelCase_ ,UpperCamelCase_: List[Any] = ProphetNetForConditionalGeneration.from_pretrained( __SCREAMING_SNAKE_CASE , output_loading_info=__SCREAMING_SNAKE_CASE ) UpperCamelCase_: int = ['key_proj', 'value_proj', 'query_proj'] UpperCamelCase_: List[Any] = { 'self_attn': 'ngram_self_attn', 'cross_attn': 'encoder_attn', 'cross_attn_layer_norm': 'encoder_attn_layer_norm', 'feed_forward_layer_norm': 'final_layer_norm', 'feed_forward': '', 'intermediate': 'fc1', 'output': 'fc2', 'key_proj': 'k_proj', 'query_proj': 'q_proj', 'value_proj': 'v_proj', 'word_embeddings': 'embed_tokens', 'embeddings_layer_norm': 'emb_layer_norm', 'relative_pos_embeddings': 'relative_linear', 'ngram_embeddings': 'ngram_input_embed', 'position_embeddings': 'embed_positions', } for key in loading_info["missing_keys"]: UpperCamelCase_: int = key.split('.' ) if attributes[0] == "lm_head": UpperCamelCase_: List[str] = prophet UpperCamelCase_: Union[str, Any] = prophet_old else: UpperCamelCase_: Dict = prophet.prophetnet UpperCamelCase_: List[Any] = prophet_old.model UpperCamelCase_: int = False for attribute in attributes: if attribute in mapping: UpperCamelCase_: Optional[int] = mapping[attribute] if not hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and len(__SCREAMING_SNAKE_CASE ) > 0: UpperCamelCase_: Dict = attribute elif hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): UpperCamelCase_: Union[str, Any] = attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" UpperCamelCase_: int = old_model.weight logger.info(F'''{attribute} is initialized.''' ) UpperCamelCase_: Tuple = True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" UpperCamelCase_: Optional[Any] = old_model.bias logger.info(F'''{attribute} is initialized''' ) UpperCamelCase_: Dict = True break elif attribute in special_keys and hasattr(__SCREAMING_SNAKE_CASE , 'in_proj_weight' ): UpperCamelCase_: Optional[int] = old_model.in_proj_weight.shape[0] // 3 UpperCamelCase_: Tuple = getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": UpperCamelCase_: List[str] = nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) UpperCamelCase_: int = nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": UpperCamelCase_: Tuple = nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) UpperCamelCase_: List[Any] = nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": UpperCamelCase_: List[Any] = nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) UpperCamelCase_: Union[str, Any] = nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) UpperCamelCase_: Dict = True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 5_1_2, "We want 512 position_embeddings." UpperCamelCase_: Optional[int] = nn.Parameter(old_model.embed_positions.weight[:5_1_2, :] ) UpperCamelCase_: Optional[Any] = True break if attribute.isdigit(): UpperCamelCase_: Tuple = model[int(__SCREAMING_SNAKE_CASE )] UpperCamelCase_: Tuple = old_model[int(__SCREAMING_SNAKE_CASE )] else: UpperCamelCase_: Optional[Any] = getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if old_attribute == "": UpperCamelCase_: int = old_model else: if not hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError(F'''{old_model} does not have {old_attribute}''' ) UpperCamelCase_: int = getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if not is_key_init: raise ValueError(F'''{key} was not correctly initialized!''' ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) prophet.save_pretrained(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": A_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--prophetnet_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) A_ : Union[str, Any] = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
57
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class A_ ( __lowerCamelCase ): '''simple docstring''' _UpperCamelCase : jnp.ndarray _UpperCamelCase : jnp.ndarray class A_ ( nn.Module ): '''simple docstring''' _UpperCamelCase : int _UpperCamelCase : Tuple[int] = (16, 32, 96, 256) _UpperCamelCase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE__ ( self ): lowercase = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) lowercase = [] for i in range(len(self.block_out_channels ) - 1 ): lowercase = self.block_out_channels[i] lowercase = self.block_out_channels[i + 1] lowercase = nn.Conv( snake_case , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(snake_case ) lowercase = nn.Conv( snake_case , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(snake_case ) lowercase = blocks lowercase = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , snake_case ): lowercase = self.conv_in(snake_case ) lowercase = nn.silu(snake_case ) for block in self.blocks: lowercase = block(snake_case ) lowercase = nn.silu(snake_case ) lowercase = self.conv_out(snake_case ) return embedding @flax_register_to_config class A_ ( nn.Module , __lowerCamelCase , __lowerCamelCase ): '''simple docstring''' _UpperCamelCase : int = 32 _UpperCamelCase : int = 4 _UpperCamelCase : Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _UpperCamelCase : Union[bool, Tuple[bool]] = False _UpperCamelCase : Tuple[int] = (320, 640, 1280, 1280) _UpperCamelCase : int = 2 _UpperCamelCase : Union[int, Tuple[int]] = 8 _UpperCamelCase : Optional[Union[int, Tuple[int]]] = None _UpperCamelCase : int = 1280 _UpperCamelCase : float = 0.0 _UpperCamelCase : bool = False _UpperCamelCase : jnp.dtype = jnp.floataa _UpperCamelCase : bool = True _UpperCamelCase : int = 0 _UpperCamelCase : str = "rgb" _UpperCamelCase : Tuple[int] = (16, 32, 96, 256) def SCREAMING_SNAKE_CASE__ ( self , snake_case ): # init input tensors lowercase = (1, self.in_channels, self.sample_size, self.sample_size) lowercase = jnp.zeros(snake_case , dtype=jnp.floataa ) lowercase = jnp.ones((1,) , dtype=jnp.intaa ) lowercase = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) lowercase = (1, 3, self.sample_size * 8, self.sample_size * 8) lowercase = jnp.zeros(snake_case , dtype=jnp.floataa ) lowercase , lowercase = jax.random.split(snake_case ) lowercase = {'params': params_rng, 'dropout': dropout_rng} return self.init(snake_case , snake_case , snake_case , snake_case , snake_case )["params"] def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.block_out_channels lowercase = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. lowercase = self.num_attention_heads or self.attention_head_dim # input lowercase = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time lowercase = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) lowercase = FlaxTimestepEmbedding(snake_case , dtype=self.dtype ) lowercase = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) lowercase = self.only_cross_attention if isinstance(snake_case , snake_case ): lowercase = (only_cross_attention,) * len(self.down_block_types ) if isinstance(snake_case , snake_case ): lowercase = (num_attention_heads,) * len(self.down_block_types ) # down lowercase = [] lowercase = [] lowercase = block_out_channels[0] lowercase = nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case ) for i, down_block_type in enumerate(self.down_block_types ): lowercase = output_channel lowercase = block_out_channels[i] lowercase = i == len(snake_case ) - 1 if down_block_type == "CrossAttnDownBlock2D": lowercase = FlaxCrossAttnDownBlockaD( in_channels=snake_case , out_channels=snake_case , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: lowercase = FlaxDownBlockaD( in_channels=snake_case , out_channels=snake_case , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(snake_case ) for _ in range(self.layers_per_block ): lowercase = nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case ) if not is_final_block: lowercase = nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case ) lowercase = down_blocks lowercase = controlnet_down_blocks # mid lowercase = block_out_channels[-1] lowercase = FlaxUNetMidBlockaDCrossAttn( in_channels=snake_case , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) lowercase = nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , snake_case , snake_case , snake_case , snake_case , snake_case = 1.0 , snake_case = True , snake_case = False , ): lowercase = self.controlnet_conditioning_channel_order if channel_order == "bgr": lowercase = jnp.flip(snake_case , axis=1 ) # 1. time if not isinstance(snake_case , jnp.ndarray ): lowercase = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(snake_case , jnp.ndarray ) and len(timesteps.shape ) == 0: lowercase = timesteps.astype(dtype=jnp.floataa ) lowercase = jnp.expand_dims(snake_case , 0 ) lowercase = self.time_proj(snake_case ) lowercase = self.time_embedding(snake_case ) # 2. pre-process lowercase = jnp.transpose(snake_case , (0, 2, 3, 1) ) lowercase = self.conv_in(snake_case ) lowercase = jnp.transpose(snake_case , (0, 2, 3, 1) ) lowercase = self.controlnet_cond_embedding(snake_case ) sample += controlnet_cond # 3. down lowercase = (sample,) for down_block in self.down_blocks: if isinstance(snake_case , snake_case ): lowercase , lowercase = down_block(snake_case , snake_case , snake_case , deterministic=not train ) else: lowercase , lowercase = down_block(snake_case , snake_case , deterministic=not train ) down_block_res_samples += res_samples # 4. mid lowercase = self.mid_block(snake_case , snake_case , snake_case , deterministic=not train ) # 5. contronet blocks lowercase = () for down_block_res_sample, controlnet_block in zip(snake_case , self.controlnet_down_blocks ): lowercase = controlnet_block(snake_case ) controlnet_down_block_res_samples += (down_block_res_sample,) lowercase = controlnet_down_block_res_samples lowercase = self.controlnet_mid_block(snake_case ) # 6. scaling lowercase = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=snake_case , mid_block_res_sample=snake_case )
84
0
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand _lowerCAmelCase : int = ( "4S 3H 2C 7S 5H", "9D 8H 2C 6S 7H", "2D 6D 9D TH 7D", "TC 8C 2S JH 6C", "JH 8S TH AH QH", "TS KS 5S 9S AC", "KD 6S 9D TH AD", "KS 8D 4D 9S 4S", # pair "8C 4S KH JS 4D", # pair "QH 8H KD JH 8S", # pair "KC 4H KS 2H 8D", # pair "KD 4S KC 3H 8S", # pair "AH 8S AS KC JH", # pair "3H 4C 4H 3S 2H", # 2 pairs "5S 5D 2C KH KH", # 2 pairs "3C KH 5D 5S KH", # 2 pairs "AS 3C KH AD KH", # 2 pairs "7C 7S 3S 7H 5S", # 3 of a kind "7C 7S KH 2H 7H", # 3 of a kind "AC KH QH AH AS", # 3 of a kind "2H 4D 3C AS 5S", # straight (low ace) "3C 5C 4C 2C 6H", # straight "6S 8S 7S 5H 9H", # straight "JS QS 9H TS KH", # straight "QC KH TS JS AH", # straight (high ace) "8C 9C 5C 3C TC", # flush "3S 8S 9S 5S KS", # flush "4C 5C 9C 8C KC", # flush "JH 8H AH KH QH", # flush "3D 2H 3H 2C 2D", # full house "2H 2C 3S 3H 3D", # full house "KH KC 3S 3H 3D", # full house "JC 6H JS JD JH", # 4 of a kind "JC 7H JS JD JH", # 4 of a kind "JC KH JS JD JH", # 4 of a kind "2S AS 4S 5S 3S", # straight flush (low ace) "2D 6D 3D 4D 5D", # straight flush "5C 6C 3C 7C 4C", # straight flush "JH 9H TH KH QH", # straight flush "JH AH TH KH QH", # royal flush (high ace straight flush) ) _lowerCAmelCase : List[Any] = ( ("2H 3H 4H 5H 6H", "KS AS TS QS JS", "Loss"), ("2H 3H 4H 5H 6H", "AS AD AC AH JD", "Win"), ("AS AH 2H AD AC", "JS JD JC JH 3D", "Win"), ("2S AH 2H AS AC", "JS JD JC JH AD", "Loss"), ("2S AH 2H AS AC", "2H 3H 5H 6H 7H", "Win"), ("AS 3S 4S 8S 2S", "2H 3H 5H 6H 7H", "Win"), ("2H 3H 5H 6H 7H", "2S 3H 4H 5S 6C", "Win"), ("2S 3H 4H 5S 6C", "3D 4C 5H 6H 2S", "Tie"), ("2S 3H 4H 5S 6C", "AH AC 5H 6H AS", "Win"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H AS", "Loss"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H 7S", "Win"), ("6S AD 7H 4S AS", "AH AC 5H 6H 7S", "Loss"), ("2S AH 4H 5S KC", "AH AC 5H 6H 7S", "Loss"), ("2S 3H 6H 7S 9C", "7H 3C TH 6H 9S", "Loss"), ("4S 5H 6H TS AC", "3S 5H 6H TS AC", "Win"), ("2S AH 4H 5S 6C", "AD 4C 5H 6H 2C", "Tie"), ("AS AH 3H AD AC", "AS AH 2H AD AC", "Win"), ("AH AC 5H 5C QS", "AH AC 5H 5C KS", "Loss"), ("AH AC 5H 5C QS", "KH KC 5H 5C QS", "Win"), ("7C 7S KH 2H 7H", "3C 3S AH 2H 3H", "Win"), ("3C 3S AH 2H 3H", "7C 7S KH 2H 7H", "Loss"), ("6H 5H 4H 3H 2H", "5H 4H 3H 2H AH", "Win"), ("5H 4H 3H 2H AH", "5H 4H 3H 2H AH", "Tie"), ("5H 4H 3H 2H AH", "6H 5H 4H 3H 2H", "Loss"), ("AH AD KS KC AC", "AH KD KH AC KC", "Win"), ("2H 4D 3C AS 5S", "2H 4D 3C 6S 5S", "Loss"), ("2H 3S 3C 3H 2S", "3S 3C 2S 2H 2D", "Win"), ("4D 6D 5D 2D JH", "3S 8S 3H TC KH", "Loss"), ("4S 6C 8S 3S 7S", "AD KS 2D 7D 7C", "Loss"), ("6S 4C 7H 8C 3H", "5H JC AH 9D 9C", "Loss"), ("9D 9H JH TC QH", "3C 2S JS 5C 7H", "Win"), ("2H TC 8S AD 9S", "4H TS 7H 2C 5C", "Win"), ("9D 3S 2C 7S 7C", "JC TD 3C TC 9H", "Loss"), ) _lowerCAmelCase : int = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", True), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", False), ("AS 3S 4S 8S 2S", True), ) _lowerCAmelCase : List[Any] = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", False), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", True), ) _lowerCAmelCase : str = ( ("2H 4D 3C AS 5S", True, [5, 4, 3, 2, 1_4]), ("2H 5D 3C AS 5S", False, [1_4, 5, 5, 3, 2]), ("JH QD KC AS TS", False, [1_4, 1_3, 1_2, 1_1, 1_0]), ("9D 3S 2C 7S 7C", False, [9, 7, 7, 3, 2]), ) _lowerCAmelCase : Any = ( ("JH AH TH KH QH", 0), ("JH 9H TH KH QH", 0), ("JC KH JS JD JH", 7), ("KH KC 3S 3H 3D", 6), ("8C 9C 5C 3C TC", 0), ("JS QS 9H TS KH", 0), ("7C 7S KH 2H 7H", 3), ("3C KH 5D 5S KH", 2), ("QH 8H KD JH 8S", 1), ("2D 6D 9D TH 7D", 0), ) _lowerCAmelCase : List[str] = ( ("JH AH TH KH QH", 2_3), ("JH 9H TH KH QH", 2_2), ("JC KH JS JD JH", 2_1), ("KH KC 3S 3H 3D", 2_0), ("8C 9C 5C 3C TC", 1_9), ("JS QS 9H TS KH", 1_8), ("7C 7S KH 2H 7H", 1_7), ("3C KH 5D 5S KH", 1_6), ("QH 8H KD JH 8S", 1_5), ("2D 6D 9D TH 7D", 1_4), ) def lowerCAmelCase ( ): """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = randrange(len(_lowerCAmelCase ) ), randrange(len(_lowerCAmelCase ) ) UpperCAmelCase__ = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] UpperCAmelCase__ , UpperCAmelCase__ = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def lowerCAmelCase ( _lowerCAmelCase : int = 100 ): """simple docstring""" return (generate_random_hand() for _ in range(_lowerCAmelCase )) @pytest.mark.parametrize("hand, expected" , _lowerCAmelCase ) def lowerCAmelCase ( _lowerCAmelCase : Any , _lowerCAmelCase : Dict ): """simple docstring""" assert PokerHand(_lowerCAmelCase )._is_flush() == expected @pytest.mark.parametrize("hand, expected" , _lowerCAmelCase ) def lowerCAmelCase ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : List[Any] ): """simple docstring""" assert PokerHand(_lowerCAmelCase )._is_straight() == expected @pytest.mark.parametrize("hand, expected, card_values" , _lowerCAmelCase ) def lowerCAmelCase ( _lowerCAmelCase : str , _lowerCAmelCase : Any , _lowerCAmelCase : Any ): """simple docstring""" UpperCAmelCase__ = PokerHand(_lowerCAmelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("hand, expected" , _lowerCAmelCase ) def lowerCAmelCase ( _lowerCAmelCase : Dict , _lowerCAmelCase : Optional[int] ): """simple docstring""" assert PokerHand(_lowerCAmelCase )._is_same_kind() == expected @pytest.mark.parametrize("hand, expected" , _lowerCAmelCase ) def lowerCAmelCase ( _lowerCAmelCase : str , _lowerCAmelCase : Dict ): """simple docstring""" assert PokerHand(_lowerCAmelCase )._hand_type == expected @pytest.mark.parametrize("hand, other, expected" , _lowerCAmelCase ) def lowerCAmelCase ( _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Union[str, Any] ): """simple docstring""" assert PokerHand(_lowerCAmelCase ).compare_with(PokerHand(_lowerCAmelCase ) ) == expected @pytest.mark.parametrize("hand, other, expected" , generate_random_hands() ) def lowerCAmelCase ( _lowerCAmelCase : int , _lowerCAmelCase : str , _lowerCAmelCase : str ): """simple docstring""" assert PokerHand(_lowerCAmelCase ).compare_with(PokerHand(_lowerCAmelCase ) ) == expected def lowerCAmelCase ( ): """simple docstring""" UpperCAmelCase__ = [PokerHand(_lowerCAmelCase ) for hand in SORTED_HANDS] UpperCAmelCase__ = poker_hands.copy() shuffle(_lowerCAmelCase ) UpperCAmelCase__ = chain(sorted(_lowerCAmelCase ) ) for index, hand in enumerate(_lowerCAmelCase ): assert hand == poker_hands[index] def lowerCAmelCase ( ): """simple docstring""" UpperCAmelCase__ = [PokerHand("2D AC 3H 4H 5S" ), PokerHand("2S 3H 4H 5S 6C" )] pokerhands.sort(reverse=_lowerCAmelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def lowerCAmelCase ( ): """simple docstring""" UpperCAmelCase__ = PokerHand("2C 4S AS 3D 5C" ) UpperCAmelCase__ = True UpperCAmelCase__ = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def lowerCAmelCase ( ): """simple docstring""" UpperCAmelCase__ = 0 UpperCAmelCase__ = os.path.abspath(os.path.dirname(_lowerCAmelCase ) ) UpperCAmelCase__ = os.path.join(_lowerCAmelCase , "poker_hands.txt" ) with open(_lowerCAmelCase ) as file_hand: for line in file_hand: UpperCAmelCase__ = line[:14].strip() UpperCAmelCase__ = line[15:].strip() UpperCAmelCase__ , UpperCAmelCase__ = PokerHand(_lowerCAmelCase ), PokerHand(_lowerCAmelCase ) UpperCAmelCase__ = player.compare_with(_lowerCAmelCase ) if output == "Win": answer += 1 assert answer == 376
364
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 _lowerCAmelCase : Tuple = logging.get_logger(__name__) _lowerCAmelCase : Union[str, Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} _lowerCAmelCase : 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", }, } _lowerCAmelCase : List[Any] = { "allenai/led-base-16384": 1_6_3_8_4, } class _UpperCamelCase ( lowerCAmelCase ): UpperCAmelCase_ = VOCAB_FILES_NAMES UpperCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ = LEDTokenizer UpperCAmelCase_ = ["""input_ids""", """attention_mask"""] def __init__( self :Dict , lowerCamelCase :Any=None , lowerCamelCase :Dict=None , lowerCamelCase :Dict=None , lowerCamelCase :int="replace" , lowerCamelCase :List[Any]="<s>" , lowerCamelCase :Optional[Any]="</s>" , lowerCamelCase :Optional[Any]="</s>" , lowerCamelCase :int="<s>" , lowerCamelCase :Optional[Any]="<unk>" , lowerCamelCase :Dict="<pad>" , lowerCamelCase :Tuple="<mask>" , lowerCamelCase :str=False , lowerCamelCase :Union[str, Any]=True , **lowerCamelCase :List[str] , ) -> Tuple: super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , errors=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , sep_token=lowerCamelCase , cls_token=lowerCamelCase , unk_token=lowerCamelCase , pad_token=lowerCamelCase , mask_token=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase , **lowerCamelCase , ) UpperCAmelCase__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: UpperCAmelCase__ = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) UpperCAmelCase__ = add_prefix_space UpperCAmelCase__ = pre_tok_class(**lowerCamelCase ) UpperCAmelCase__ = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` UpperCAmelCase__ = "post_processor" UpperCAmelCase__ = getattr(self.backend_tokenizer , lowerCamelCase , lowerCamelCase ) 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" , lowerCamelCase ) != add_prefix_space: UpperCAmelCase__ = add_prefix_space UpperCAmelCase__ = True if state.get("trim_offsets" , lowerCamelCase ) != trim_offsets: UpperCAmelCase__ = trim_offsets UpperCAmelCase__ = True if changes_to_apply: UpperCAmelCase__ = getattr(lowerCamelCase , state.pop("type" ) ) UpperCAmelCase__ = component_class(**lowerCamelCase ) setattr(self.backend_tokenizer , lowerCamelCase , lowerCamelCase ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def UpperCAmelCase_ ( self :List[str] ) -> str: 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 UpperCAmelCase_ ( self :Union[str, Any] , lowerCamelCase :List[str] ) -> Dict: UpperCAmelCase__ = AddedToken(lowerCamelCase , lstrip=lowerCamelCase , rstrip=lowerCamelCase ) if isinstance(lowerCamelCase , lowerCamelCase ) else value UpperCAmelCase__ = value def UpperCAmelCase_ ( self :Optional[Any] , *lowerCamelCase :Any , **lowerCamelCase :int ) -> BatchEncoding: UpperCAmelCase__ = kwargs.get("is_split_into_words" , lowerCamelCase ) 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(*lowerCamelCase , **lowerCamelCase ) def UpperCAmelCase_ ( self :int , *lowerCamelCase :Optional[Any] , **lowerCamelCase :Optional[int] ) -> BatchEncoding: UpperCAmelCase__ = kwargs.get("is_split_into_words" , lowerCamelCase ) 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(*lowerCamelCase , **lowerCamelCase ) def UpperCAmelCase_ ( self :Any , lowerCamelCase :str , lowerCamelCase :Optional[str] = None ) -> Tuple[str]: UpperCAmelCase__ = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def UpperCAmelCase_ ( self :Optional[Any] , lowerCamelCase :Optional[int] , lowerCamelCase :Optional[Any]=None ) -> Dict: 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 UpperCAmelCase_ ( self :Optional[int] , lowerCamelCase :List[int] , lowerCamelCase :Optional[List[int]] = 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 UpperCAmelCase_ ( self :List[str] , lowerCamelCase :Union[Dict[str, EncodedInput], BatchEncoding] , lowerCamelCase :Optional[int] = None , lowerCamelCase :PaddingStrategy = PaddingStrategy.DO_NOT_PAD , lowerCamelCase :Optional[int] = None , lowerCamelCase :Optional[bool] = 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
364
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def lowerCAmelCase_ ( __a , __a=False ) -> Union[str, Any]: """simple docstring""" lowerCamelCase__: Dict =[] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""module.blocks.{i}.norm1.weight""", F"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""module.blocks.{i}.norm1.bias""", F"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (F"""module.blocks.{i}.attn.proj.weight""", F"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.attn.proj.bias""", F"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""module.blocks.{i}.norm2.weight""", F"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""module.blocks.{i}.norm2.bias""", F"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc1.weight""", F"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc1.bias""", F"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc2.weight""", F"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc2.bias""", F"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("module.cls_token", "vit.embeddings.cls_token"), ("module.patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"), ("module.patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"), ("module.pos_embed", "vit.embeddings.position_embeddings"), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("module.norm.weight", "layernorm.weight"), ("module.norm.bias", "layernorm.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" lowerCamelCase__: int =[(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) return rename_keys def lowerCAmelCase_ ( __a , __a , __a=False ) -> Any: """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: lowerCamelCase__: List[Any] ="" else: lowerCamelCase__: Dict ="vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowerCamelCase__: Tuple =state_dict.pop(F"""module.blocks.{i}.attn.qkv.weight""" ) lowerCamelCase__: int =state_dict.pop(F"""module.blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict lowerCamelCase__: int =in_proj_weight[ : config.hidden_size, : ] lowerCamelCase__: Optional[int] =in_proj_bias[: config.hidden_size] lowerCamelCase__: Union[str, Any] =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCamelCase__: str =in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowerCamelCase__: Dict =in_proj_weight[ -config.hidden_size :, : ] lowerCamelCase__: str =in_proj_bias[-config.hidden_size :] def lowerCAmelCase_ ( __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(__a , __a ) def lowerCAmelCase_ ( __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: Any =[ "module.fc.fc1.weight", "module.fc.fc1.bias", "module.fc.bn1.weight", "module.fc.bn1.bias", "module.fc.bn1.running_mean", "module.fc.bn1.running_var", "module.fc.bn1.num_batches_tracked", "module.fc.fc2.weight", "module.fc.fc2.bias", "module.fc.bn2.weight", "module.fc.bn2.bias", "module.fc.bn2.running_mean", "module.fc.bn2.running_var", "module.fc.bn2.num_batches_tracked", "module.fc.fc3.weight", "module.fc.fc3.bias", ] for k in ignore_keys: state_dict.pop(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" lowerCamelCase__: int =dct.pop(__a ) lowerCamelCase__: Tuple =val def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" lowerCamelCase__: List[str] =ViTMSNConfig() lowerCamelCase__: Optional[Any] =1000 lowerCamelCase__: Dict ="datasets/huggingface/label-files" lowerCamelCase__: List[str] ="imagenet-1k-id2label.json" lowerCamelCase__: List[str] =json.load(open(hf_hub_download(__a , __a ) , "r" ) ) lowerCamelCase__: int ={int(__a ): v for k, v in idalabel.items()} lowerCamelCase__: List[str] =idalabel lowerCamelCase__: Union[str, Any] ={v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: lowerCamelCase__: Dict =384 lowerCamelCase__: Union[str, Any] =1536 lowerCamelCase__: Dict =6 elif "l16" in checkpoint_url: lowerCamelCase__: str =1024 lowerCamelCase__: List[Any] =4096 lowerCamelCase__: List[str] =24 lowerCamelCase__: List[Any] =16 lowerCamelCase__: Any =0.1 elif "b4" in checkpoint_url: lowerCamelCase__: List[str] =4 elif "l7" in checkpoint_url: lowerCamelCase__: Optional[Any] =7 lowerCamelCase__: int =1024 lowerCamelCase__: int =4096 lowerCamelCase__: Tuple =24 lowerCamelCase__: List[Any] =16 lowerCamelCase__: Tuple =0.1 lowerCamelCase__: Union[str, Any] =ViTMSNModel(__a ) lowerCamelCase__: Tuple =torch.hub.load_state_dict_from_url(__a , map_location="cpu" )["target_encoder"] lowerCamelCase__: Union[str, Any] =ViTImageProcessor(size=config.image_size ) remove_projection_head(__a ) lowerCamelCase__: Optional[Any] =create_rename_keys(__a , base_model=__a ) for src, dest in rename_keys: rename_key(__a , __a , __a ) read_in_q_k_v(__a , __a , base_model=__a ) model.load_state_dict(__a ) model.eval() lowerCamelCase__: Dict ="http://images.cocodataset.org/val2017/000000039769.jpg" lowerCamelCase__: Any =Image.open(requests.get(__a , stream=__a ).raw ) lowerCamelCase__: Union[str, Any] =ViTImageProcessor( size=config.image_size , image_mean=__a , image_std=__a ) lowerCamelCase__: List[str] =image_processor(images=__a , return_tensors="pt" ) # forward pass torch.manual_seed(2 ) lowerCamelCase__: Union[str, Any] =model(**__a ) lowerCamelCase__: List[str] =outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: lowerCamelCase__: str =torch.tensor([[-1.0_9_1_5, -1.4_8_7_6, -1.1_8_0_9]] ) elif "b16" in checkpoint_url: lowerCamelCase__: Tuple =torch.tensor([[1_4.2_8_8_9, -1_8.9_0_4_5, 1_1.7_2_8_1]] ) elif "l16" in checkpoint_url: lowerCamelCase__: List[Any] =torch.tensor([[4_1.5_0_2_8, -2_2.8_6_8_1, 4_5.6_4_7_5]] ) elif "b4" in checkpoint_url: lowerCamelCase__: Union[str, Any] =torch.tensor([[-4.3_8_6_8, 5.2_9_3_2, -0.4_1_3_7]] ) else: lowerCamelCase__: Dict =torch.tensor([[-0.1_7_9_2, -0.6_4_6_5, 2.4_2_6_3]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , __a , atol=1e-4 ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(__a ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__a ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar", type=str, help="URL of the checkpoint 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 = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
59
import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig 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 torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCAmelCase_ : """simple docstring""" def __init__( self , _a , _a=1_3 , _a=3 , _a=True , _a=True , _a=0.1 , _a=0.1 , _a=2_2_4 , _a=1_0_0_0 , _a=[3, 3, 6, 4] , _a=[4_8, 5_6, 1_1_2, 2_2_0] , ) -> Tuple: _a : Dict = parent _a : Optional[int] = batch_size _a : Optional[Any] = num_channels _a : Union[str, Any] = is_training _a : Tuple = use_labels _a : Dict = hidden_dropout_prob _a : List[Any] = attention_probs_dropout_prob _a : Dict = num_labels _a : List[str] = image_size _a : Dict = layer_depths _a : str = embed_dims def __lowercase ( self ) -> Optional[Any]: _a : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : int = None if self.use_labels: _a : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) _a : Dict = self.get_config() return config, pixel_values, labels def __lowercase ( self ) -> int: return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act='''gelu''' , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=_a , layer_scale_init_value=1e-5 , ) def __lowercase ( self , _a , _a , _a ) -> str: _a : List[Any] = SwiftFormerModel(config=_a ) model.to(_a ) model.eval() _a : Optional[int] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def __lowercase ( self , _a , _a , _a ) -> Optional[Any]: _a : List[str] = self.num_labels _a : Optional[int] = SwiftFormerForImageClassification(_a ) model.to(_a ) model.eval() _a : List[str] = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) _a : Union[str, Any] = SwiftFormerForImageClassification(_a ) model.to(_a ) model.eval() _a : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Optional[Any] = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase ( self ) -> Tuple: ((_a) , (_a) , (_a)) : Optional[int] = self.prepare_config_and_inputs() _a : List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( __lowercase , __lowercase , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[str] = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () UpperCAmelCase__ : Optional[int] = ( {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification} if is_torch_available() else {} ) UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : str = False UpperCAmelCase__ : Tuple = False UpperCAmelCase__ : Tuple = False UpperCAmelCase__ : str = False def __lowercase ( self ) -> Optional[int]: _a : Union[str, Any] = SwiftFormerModelTester(self ) _a : int = ConfigTester( self , config_class=_a , has_text_modality=_a , hidden_size=3_7 , num_attention_heads=1_2 , num_hidden_layers=1_2 , ) def __lowercase ( self ) -> int: self.config_tester.run_common_tests() @unittest.skip(reason='''SwiftFormer does not use inputs_embeds''' ) def __lowercase ( self ) -> Union[str, Any]: pass def __lowercase ( self ) -> Dict: _a , _a : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Any = model_class(_a ) _a : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def __lowercase ( self ) -> str: _a , _a : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Optional[int] = model_class(_a ) _a : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Tuple = [*signature.parameters.keys()] _a : List[str] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _a ) def __lowercase ( self ) -> int: _a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __lowercase ( self ) -> Optional[int]: _a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def __lowercase ( self ) -> Optional[Any]: for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Any = SwiftFormerModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip(reason='''SwiftFormer does not output attentions''' ) def __lowercase ( self ) -> List[Any]: pass def __lowercase ( self ) -> int: def check_hidden_states_output(_a , _a , _a ): _a : Optional[int] = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): _a : Union[str, Any] = model(**self._prepare_for_class(_a , _a ) ) _a : Optional[Any] = outputs.hidden_states _a : Union[str, Any] = 8 self.assertEqual(len(_a ) , _a ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(_a ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) _a , _a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : str = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : List[str] = True check_hidden_states_output(_a , _a , _a ) def __lowercase ( self ) -> str: def _config_zero_init(_a ): _a : List[Any] = copy.deepcopy(_a ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(_a , _a , 1e-1_0 ) if isinstance(getattr(_a , _a , _a ) , _a ): _a : int = _config_zero_init(getattr(_a , _a ) ) setattr(_a , _a , _a ) return configs_no_init _a , _a : Any = self.model_tester.prepare_config_and_inputs_for_common() _a : Dict = _config_zero_init(_a ) for model_class in self.all_model_classes: _a : Dict = model_class(config=_a ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9) / 1e9).round().item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __lowercase ( self ) -> Optional[Any]: pass def __UpperCAmelCase ( ) -> Optional[Any]: """simple docstring""" _a : Optional[int] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self ) -> str: return ViTImageProcessor.from_pretrained('''MBZUAI/swiftformer-xs''' ) if is_vision_available() else None @slow def __lowercase ( self ) -> Dict: _a : Any = SwiftFormerForImageClassification.from_pretrained('''MBZUAI/swiftformer-xs''' ).to(_a ) _a : Any = self.default_image_processor _a : Any = prepare_img() _a : Any = image_processor(images=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): _a : Optional[Any] = model(**_a ) # verify the logits _a : List[str] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _a ) _a : int = torch.tensor([[-2.1_7_0_3e0_0, 2.1_1_0_7e0_0, -2.0_8_1_1e0_0]] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) )
14
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowerCamelCase_ : Optional[Any] = { '''configuration_encodec''': [ '''ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''EncodecConfig''', ], '''feature_extraction_encodec''': ['''EncodecFeatureExtractor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Tuple = [ '''ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST''', '''EncodecModel''', '''EncodecPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys lowerCamelCase_ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
265
'''simple docstring''' from __future__ import annotations from typing import Any class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] , lowercase : int ) -> None: '''simple docstring''' UpperCamelCase__ = num_of_nodes UpperCamelCase__ = [] UpperCamelCase__ = {} def A ( self : Optional[Any] , lowercase : int , lowercase : int , lowercase : int ) -> None: '''simple docstring''' self.m_edges.append([u_node, v_node, weight] ) def A ( self : str , lowercase : int ) -> int: '''simple docstring''' if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def A ( self : Union[str, Any] , lowercase : int ) -> None: '''simple docstring''' if self.m_component[u_node] != u_node: for k in self.m_component: UpperCamelCase__ = self.find_component(lowercase ) def A ( self : Tuple , lowercase : list[int] , lowercase : int , lowercase : int ) -> None: '''simple docstring''' if component_size[u_node] <= component_size[v_node]: UpperCamelCase__ = v_node component_size[v_node] += component_size[u_node] self.set_component(lowercase ) elif component_size[u_node] >= component_size[v_node]: UpperCamelCase__ = self.find_component(lowercase ) component_size[u_node] += component_size[v_node] self.set_component(lowercase ) def A ( self : int ) -> None: '''simple docstring''' UpperCamelCase__ = [] UpperCamelCase__ = 0 UpperCamelCase__ = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) UpperCamelCase__ = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = edge UpperCamelCase__ = self.m_component[u] UpperCamelCase__ = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): UpperCamelCase__ = [u, v, w] for edge in minimum_weight_edge: if isinstance(lowercase , lowercase ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = edge UpperCamelCase__ = self.m_component[u] UpperCamelCase__ = self.m_component[v] if u_component != v_component: mst_weight += w self.union(lowercase , lowercase , lowercase ) print(f"Added edge [{u} - {v}]\nAdded weight: {w}\n" ) num_of_components -= 1 UpperCamelCase__ = [-1] * self.m_num_of_nodes print(f"The total weight of the minimal spanning tree is: {mst_weight}" ) def __magic_name__( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
265
1
"""simple docstring""" import fire from utils import calculate_rouge, save_json def _UpperCAmelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any]=None , **__lowerCamelCase : Tuple ) -> Optional[int]: _snake_case = [x.strip() for x in open(__lowerCamelCase ).readlines()] _snake_case = [x.strip() for x in open(__lowerCamelCase ).readlines()][: len(__lowerCamelCase )] _snake_case = calculate_rouge(__lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) if save_path is not None: save_json(__lowerCamelCase , __lowerCamelCase , indent=__lowerCamelCase ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
224
"""simple docstring""" from collections import deque from .hash_table import HashTable class lowerCAmelCase__ ( A_ ): def __init__( self : Tuple , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ): super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def lowercase ( self : Tuple , _lowerCamelCase : Any , _lowerCamelCase : List[Any] ): _snake_case = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(_lowerCamelCase ) _snake_case = self.values[key] def lowercase ( self : int ): return ( sum(self.charge_factor - len(_lowerCamelCase ) for slot in self.values ) / self.size_table * self.charge_factor ) def lowercase ( self : Dict , _lowerCamelCase : List[str] , _lowerCamelCase : List[str]=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(_lowerCamelCase ) == 0 ): return key return super()._collision_resolution(_lowerCamelCase , _lowerCamelCase )
224
1
import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class UpperCamelCase_ ( a__ ): '''simple docstring''' a :Optional[int] = """MCTCTFeatureExtractor""" a :str = """AutoTokenizer""" def __init__( self , _UpperCAmelCase , _UpperCAmelCase): super().__init__(lowercase__ , lowercase__) lowerCAmelCase_ = self.feature_extractor lowerCAmelCase_ = False def __call__( self , *_UpperCAmelCase , **_UpperCAmelCase): if self._in_target_context_manager: return self.current_processor(*lowercase__ , **lowercase__) if "raw_speech" in kwargs: warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''') lowerCAmelCase_ = kwargs.pop('''raw_speech''') else: lowerCAmelCase_ = kwargs.pop('''audio''' , lowercase__) lowerCAmelCase_ = kwargs.pop('''sampling_rate''' , lowercase__) lowerCAmelCase_ = kwargs.pop('''text''' , lowercase__) if len(lowercase__) > 0: lowerCAmelCase_ = args[0] lowerCAmelCase_ = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''') if audio is not None: lowerCAmelCase_ = self.feature_extractor(lowercase__ , *lowercase__ , sampling_rate=lowercase__ , **lowercase__) if text is not None: lowerCAmelCase_ = self.tokenizer(lowercase__ , **lowercase__) if text is None: return inputs elif audio is None: return encodings else: lowerCAmelCase_ = encodings['''input_ids'''] return inputs def lowercase__ ( self , *_UpperCAmelCase , **_UpperCAmelCase): return self.tokenizer.batch_decode(*lowercase__ , **lowercase__) def lowercase__ ( self , *_UpperCAmelCase , **_UpperCAmelCase): if self._in_target_context_manager: return self.current_processor.pad(*lowercase__ , **lowercase__) lowerCAmelCase_ = kwargs.pop('''input_features''' , lowercase__) lowerCAmelCase_ = kwargs.pop('''labels''' , lowercase__) if len(lowercase__) > 0: lowerCAmelCase_ = args[0] lowerCAmelCase_ = args[1:] if input_features is not None: lowerCAmelCase_ = self.feature_extractor.pad(lowercase__ , *lowercase__ , **lowercase__) if labels is not None: lowerCAmelCase_ = self.tokenizer.pad(lowercase__ , **lowercase__) if labels is None: return input_features elif input_features is None: return labels else: lowerCAmelCase_ = labels['''input_ids'''] return input_features def lowercase__ ( self , *_UpperCAmelCase , **_UpperCAmelCase): return self.tokenizer.decode(*lowercase__ , **lowercase__) @contextmanager def lowercase__ ( self): warnings.warn( '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ''' '''labels by using the argument `text` of the regular `__call__` method (either in the same call as ''' '''your audio inputs, or in a separate call.''') lowerCAmelCase_ = True lowerCAmelCase_ = self.tokenizer yield lowerCAmelCase_ = self.feature_extractor lowerCAmelCase_ = False
703
from math import pi def lowerCamelCase_ ( A : int , A : int ): """simple docstring""" return 2 * pi * radius * (angle / 3_60) if __name__ == "__main__": print(arc_length(90, 10))
413
0
import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class A( UpperCamelCase ): '''simple docstring''' UpperCamelCase = (EulerDiscreteScheduler,) UpperCamelCase = 10 def a__ ( self : Dict , **A_ : int ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ = { 'num_train_timesteps': 1100, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', } config.update(**A_ ) return config def a__ ( self : Tuple ) -> Dict: """simple docstring""" for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=A_ ) def a__ ( self : Optional[int] ) -> Dict: """simple docstring""" for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=A_ , beta_end=A_ ) def a__ ( self : Tuple ) -> Optional[int]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=A_ ) def a__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A_ ) def a__ ( self : List[Any] ) -> List[str]: """simple docstring""" lowerCamelCase_ = self.scheduler_classes[0] lowerCamelCase_ = self.get_scheduler_config() lowerCamelCase_ = scheduler_class(**A_ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCamelCase_ = torch.manual_seed(0 ) lowerCamelCase_ = self.dummy_model() lowerCamelCase_ = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCamelCase_ = sample.to(A_ ) for i, t in enumerate(scheduler.timesteps ): lowerCamelCase_ = scheduler.scale_model_input(A_ , A_ ) lowerCamelCase_ = model(A_ , A_ ) lowerCamelCase_ = scheduler.step(A_ , A_ , A_ , generator=A_ ) lowerCamelCase_ = output.prev_sample lowerCamelCase_ = torch.sum(torch.abs(A_ ) ) lowerCamelCase_ = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 10.0807 ) < 1E-2 assert abs(result_mean.item() - 0.0131 ) < 1E-3 def a__ ( self : Dict ) -> Dict: """simple docstring""" lowerCamelCase_ = self.scheduler_classes[0] lowerCamelCase_ = self.get_scheduler_config(prediction_type='v_prediction' ) lowerCamelCase_ = scheduler_class(**A_ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCamelCase_ = torch.manual_seed(0 ) lowerCamelCase_ = self.dummy_model() lowerCamelCase_ = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCamelCase_ = sample.to(A_ ) for i, t in enumerate(scheduler.timesteps ): lowerCamelCase_ = scheduler.scale_model_input(A_ , A_ ) lowerCamelCase_ = model(A_ , A_ ) lowerCamelCase_ = scheduler.step(A_ , A_ , A_ , generator=A_ ) lowerCamelCase_ = output.prev_sample lowerCamelCase_ = torch.sum(torch.abs(A_ ) ) lowerCamelCase_ = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 0.0002 ) < 1E-2 assert abs(result_mean.item() - 2.2_676E-06 ) < 1E-3 def a__ ( self : Any ) -> Any: """simple docstring""" lowerCamelCase_ = self.scheduler_classes[0] lowerCamelCase_ = self.get_scheduler_config() lowerCamelCase_ = scheduler_class(**A_ ) scheduler.set_timesteps(self.num_inference_steps , device=A_ ) lowerCamelCase_ = torch.manual_seed(0 ) lowerCamelCase_ = self.dummy_model() lowerCamelCase_ = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() lowerCamelCase_ = sample.to(A_ ) for t in scheduler.timesteps: lowerCamelCase_ = scheduler.scale_model_input(A_ , A_ ) lowerCamelCase_ = model(A_ , A_ ) lowerCamelCase_ = scheduler.step(A_ , A_ , A_ , generator=A_ ) lowerCamelCase_ = output.prev_sample lowerCamelCase_ = torch.sum(torch.abs(A_ ) ) lowerCamelCase_ = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 10.0807 ) < 1E-2 assert abs(result_mean.item() - 0.0131 ) < 1E-3 def a__ ( self : Optional[Any] ) -> Tuple: """simple docstring""" lowerCamelCase_ = self.scheduler_classes[0] lowerCamelCase_ = self.get_scheduler_config() lowerCamelCase_ = scheduler_class(**A_ , use_karras_sigmas=A_ ) scheduler.set_timesteps(self.num_inference_steps , device=A_ ) lowerCamelCase_ = torch.manual_seed(0 ) lowerCamelCase_ = self.dummy_model() lowerCamelCase_ = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() lowerCamelCase_ = sample.to(A_ ) for t in scheduler.timesteps: lowerCamelCase_ = scheduler.scale_model_input(A_ , A_ ) lowerCamelCase_ = model(A_ , A_ ) lowerCamelCase_ = scheduler.step(A_ , A_ , A_ , generator=A_ ) lowerCamelCase_ = output.prev_sample lowerCamelCase_ = torch.sum(torch.abs(A_ ) ) lowerCamelCase_ = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 124.52299499511719 ) < 1E-2 assert abs(result_mean.item() - 0.16213932633399963 ) < 1E-3
70
from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
70
1
UpperCAmelCase_ =0 # The first color of the flag. UpperCAmelCase_ =1 # The second color of the flag. UpperCAmelCase_ =2 # The third color of the flag. UpperCAmelCase_ =(red, white, blue) def UpperCAmelCase ( _snake_case ): if not sequence: return [] if len(lowerCAmelCase__ ) == 1: return list(lowerCAmelCase__ ) lowerCAmelCase = 0 lowerCAmelCase = len(lowerCAmelCase__ ) - 1 lowerCAmelCase = 0 while mid <= high: if sequence[mid] == colors[0]: lowerCAmelCase = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: lowerCAmelCase = sequence[high], sequence[mid] high -= 1 else: lowerCAmelCase = F"""The elements inside the sequence must contains only {colors} values""" raise ValueError(lowerCAmelCase__ ) return sequence if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase_ =input("""Enter numbers separated by commas:\n""").strip() UpperCAmelCase_ =[int(item.strip()) for item in user_input.split(""",""")] print(F'''{dutch_national_flag_sort(unsorted)}''')
708
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def UpperCAmelCase ( _snake_case ): lowerCAmelCase , lowerCAmelCase = analyze_text(_snake_case ) lowerCAmelCase = list(''' ''' + ascii_lowercase ) # what is our total sum of probabilities. lowerCAmelCase = sum(single_char_strings.values() ) # one length string lowerCAmelCase = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: lowerCAmelCase = single_char_strings[ch] lowerCAmelCase = my_str / all_sum my_fir_sum += prob * math.loga(_snake_case ) # entropy formula. # print entropy print(F"""{round(-1 * my_fir_sum ):.1f}""" ) # two len string lowerCAmelCase = sum(two_char_strings.values() ) lowerCAmelCase = 0 # for each alpha (two in size) calculate entropy. for cha in my_alphas: for cha in my_alphas: lowerCAmelCase = cha + cha if sequence in two_char_strings: lowerCAmelCase = two_char_strings[sequence] lowerCAmelCase = int(_snake_case ) / all_sum my_sec_sum += prob * math.loga(_snake_case ) # print second entropy print(F"""{round(-1 * my_sec_sum ):.1f}""" ) # print the difference between them print(F"""{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}""" ) def UpperCAmelCase ( _snake_case ): lowerCAmelCase = Counter() # type: ignore lowerCAmelCase = Counter() # type: ignore single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(0 , len(_snake_case ) - 1 ): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def UpperCAmelCase ( ): import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
33
0
"""simple docstring""" from collections.abc import Callable def lowercase (SCREAMING_SNAKE_CASE_ : Callable[[float], float] , SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ) -> float: SCREAMING_SNAKE_CASE = a SCREAMING_SNAKE_CASE = b if function(SCREAMING_SNAKE_CASE_ ) == 0: # one of the a or b is a root for the function return a elif function(SCREAMING_SNAKE_CASE_ ) == 0: return b elif ( function(SCREAMING_SNAKE_CASE_ ) * function(SCREAMING_SNAKE_CASE_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError('could not find root in given interval.' ) else: SCREAMING_SNAKE_CASE = start + (end - start) / 2.0 while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7 if function(SCREAMING_SNAKE_CASE_ ) == 0: return mid elif function(SCREAMING_SNAKE_CASE_ ) * function(SCREAMING_SNAKE_CASE_ ) < 0: SCREAMING_SNAKE_CASE = mid else: SCREAMING_SNAKE_CASE = mid SCREAMING_SNAKE_CASE = start + (end - start) / 2.0 return mid def lowercase (SCREAMING_SNAKE_CASE_ : float ) -> float: return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
247
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_pegasus import PegasusTokenizer else: __UpperCamelCase = None __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = '''▁''' __UpperCamelCase = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} __UpperCamelCase = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''}, '''tokenizer_file''': { '''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/tokenizer.json''' }, } __UpperCamelCase = { '''google/pegasus-xsum''': 512, } class lowerCAmelCase ( lowerCamelCase_ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ : List[Any] = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ : Any = PegasusTokenizer SCREAMING_SNAKE_CASE_ : Optional[int] = ["""input_ids""", """attention_mask"""] def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__="<pad>" , lowerCAmelCase__="</s>" , lowerCAmelCase__="<unk>" , lowerCAmelCase__="<mask_2>" , lowerCAmelCase__="<mask_1>" , lowerCAmelCase__=None , lowerCAmelCase__=103 , **lowerCAmelCase__ , ) -> Dict: SCREAMING_SNAKE_CASE = offset if additional_special_tokens is not None: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError( F'additional_special_tokens should be of type {type(lowerCAmelCase__ )}, but is' F' {type(lowerCAmelCase__ )}' ) SCREAMING_SNAKE_CASE = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ F'<unk_{i}>' for i in range(len(lowerCAmelCase__ ) , self.offset - 1 ) ] if len(set(lowerCAmelCase__ ) ) != len(lowerCAmelCase__ ): raise ValueError( 'Please make sure that the provided additional_special_tokens do not contain an incorrectly' F' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.' ) SCREAMING_SNAKE_CASE = additional_special_tokens_extended else: SCREAMING_SNAKE_CASE = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F'<unk_{i}>' for i in range(2 , self.offset )] super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , mask_token_sent=lowerCAmelCase__ , offset=lowerCAmelCase__ , additional_special_tokens=lowerCAmelCase__ , **lowerCAmelCase__ , ) SCREAMING_SNAKE_CASE = vocab_file SCREAMING_SNAKE_CASE = False if not self.vocab_file else True def __A ( self , lowerCAmelCase__ ) -> Optional[Any]: SCREAMING_SNAKE_CASE = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special if all_special_ids != set(range(len(self.additional_special_tokens ) + 3 ) ): raise ValueError( 'There should be 3 special tokens: mask_token, pad_token, and eos_token +' F' {len(self.additional_special_tokens )} additional_special_tokens, but got {all_special_ids}' ) return [1 if x in all_special_ids else 0 for x in seq] def __A ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = False ) -> List[int]: if already_has_special_tokens: return self._special_token_mask(lowerCAmelCase__ ) elif token_ids_a is None: return self._special_token_mask(lowerCAmelCase__ ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def __A ( self , lowerCAmelCase__ , lowerCAmelCase__=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def __A ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(lowerCAmelCase__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return SCREAMING_SNAKE_CASE = os.path.join( lowerCAmelCase__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase__ ): copyfile(self.vocab_file , lowerCAmelCase__ ) return (out_vocab_file,)
247
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class a_ ( unittest.TestCase ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=3 , _lowerCamelCase=224 , _lowerCamelCase=30 , _lowerCamelCase=400 , _lowerCamelCase=True , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase=[0.5, 0.5, 0.5] , _lowerCamelCase=[0.5, 0.5, 0.5] , ) ->Dict: SCREAMING_SNAKE_CASE : Any = size if size is not None else {'''height''': 18, '''width''': 18} SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : Tuple = num_channels SCREAMING_SNAKE_CASE : Optional[int] = image_size SCREAMING_SNAKE_CASE : Optional[Any] = min_resolution SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution SCREAMING_SNAKE_CASE : Tuple = do_resize SCREAMING_SNAKE_CASE : int = size SCREAMING_SNAKE_CASE : str = do_normalize SCREAMING_SNAKE_CASE : Any = image_mean SCREAMING_SNAKE_CASE : Any = image_std def __lowerCAmelCase ( self ) ->Tuple: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = ViTImageProcessor if is_vision_available() else None def __lowerCAmelCase ( self ) ->str: SCREAMING_SNAKE_CASE : Dict = EfficientFormerImageProcessorTester(self ) @property def __lowerCAmelCase ( self ) ->List[Any]: return self.image_proc_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self ) ->List[str]: SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def __lowerCAmelCase ( self ) ->Tuple: pass def __lowerCAmelCase ( self ) ->Union[str, Any]: # Initialize image_processor SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : str = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : str = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE : Tuple = image_processor(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __lowerCAmelCase ( self ) ->Tuple: # Initialize image_processor SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : Optional[Any] = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : Dict = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE : List[str] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __lowerCAmelCase ( self ) ->Optional[Any]: # Initialize image_processor SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Dict = prepare_image_inputs(self.image_proc_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched SCREAMING_SNAKE_CASE : List[str] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
721
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore a__ : Optional[int] = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" a__ : int = [file for file in filepaths if file != file.lower()] if upper_files: print(F"{len(upper_files)} files contain uppercase characters:") print('''\n'''.join(upper_files) + '''\n''') a__ : str = [file for file in filepaths if ''' ''' in file] if space_files: print(F"{len(space_files)} files contain space characters:") print('''\n'''.join(space_files) + '''\n''') a__ : Optional[Any] = [file for file in filepaths if '''-''' in file] if hyphen_files: print(F"{len(hyphen_files)} files contain hyphen characters:") print('''\n'''.join(hyphen_files) + '''\n''') a__ : List[str] = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"{len(nodir_files)} files are not in a directory:") print('''\n'''.join(nodir_files) + '''\n''') a__ : Optional[int] = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
333
0
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand __SCREAMING_SNAKE_CASE : int =( "4S 3H 2C 7S 5H", "9D 8H 2C 6S 7H", "2D 6D 9D TH 7D", "TC 8C 2S JH 6C", "JH 8S TH AH QH", "TS KS 5S 9S AC", "KD 6S 9D TH AD", "KS 8D 4D 9S 4S", # pair "8C 4S KH JS 4D", # pair "QH 8H KD JH 8S", # pair "KC 4H KS 2H 8D", # pair "KD 4S KC 3H 8S", # pair "AH 8S AS KC JH", # pair "3H 4C 4H 3S 2H", # 2 pairs "5S 5D 2C KH KH", # 2 pairs "3C KH 5D 5S KH", # 2 pairs "AS 3C KH AD KH", # 2 pairs "7C 7S 3S 7H 5S", # 3 of a kind "7C 7S KH 2H 7H", # 3 of a kind "AC KH QH AH AS", # 3 of a kind "2H 4D 3C AS 5S", # straight (low ace) "3C 5C 4C 2C 6H", # straight "6S 8S 7S 5H 9H", # straight "JS QS 9H TS KH", # straight "QC KH TS JS AH", # straight (high ace) "8C 9C 5C 3C TC", # flush "3S 8S 9S 5S KS", # flush "4C 5C 9C 8C KC", # flush "JH 8H AH KH QH", # flush "3D 2H 3H 2C 2D", # full house "2H 2C 3S 3H 3D", # full house "KH KC 3S 3H 3D", # full house "JC 6H JS JD JH", # 4 of a kind "JC 7H JS JD JH", # 4 of a kind "JC KH JS JD JH", # 4 of a kind "2S AS 4S 5S 3S", # straight flush (low ace) "2D 6D 3D 4D 5D", # straight flush "5C 6C 3C 7C 4C", # straight flush "JH 9H TH KH QH", # straight flush "JH AH TH KH QH", # royal flush (high ace straight flush) ) __SCREAMING_SNAKE_CASE : Any =( ("2H 3H 4H 5H 6H", "KS AS TS QS JS", "Loss"), ("2H 3H 4H 5H 6H", "AS AD AC AH JD", "Win"), ("AS AH 2H AD AC", "JS JD JC JH 3D", "Win"), ("2S AH 2H AS AC", "JS JD JC JH AD", "Loss"), ("2S AH 2H AS AC", "2H 3H 5H 6H 7H", "Win"), ("AS 3S 4S 8S 2S", "2H 3H 5H 6H 7H", "Win"), ("2H 3H 5H 6H 7H", "2S 3H 4H 5S 6C", "Win"), ("2S 3H 4H 5S 6C", "3D 4C 5H 6H 2S", "Tie"), ("2S 3H 4H 5S 6C", "AH AC 5H 6H AS", "Win"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H AS", "Loss"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H 7S", "Win"), ("6S AD 7H 4S AS", "AH AC 5H 6H 7S", "Loss"), ("2S AH 4H 5S KC", "AH AC 5H 6H 7S", "Loss"), ("2S 3H 6H 7S 9C", "7H 3C TH 6H 9S", "Loss"), ("4S 5H 6H TS AC", "3S 5H 6H TS AC", "Win"), ("2S AH 4H 5S 6C", "AD 4C 5H 6H 2C", "Tie"), ("AS AH 3H AD AC", "AS AH 2H AD AC", "Win"), ("AH AC 5H 5C QS", "AH AC 5H 5C KS", "Loss"), ("AH AC 5H 5C QS", "KH KC 5H 5C QS", "Win"), ("7C 7S KH 2H 7H", "3C 3S AH 2H 3H", "Win"), ("3C 3S AH 2H 3H", "7C 7S KH 2H 7H", "Loss"), ("6H 5H 4H 3H 2H", "5H 4H 3H 2H AH", "Win"), ("5H 4H 3H 2H AH", "5H 4H 3H 2H AH", "Tie"), ("5H 4H 3H 2H AH", "6H 5H 4H 3H 2H", "Loss"), ("AH AD KS KC AC", "AH KD KH AC KC", "Win"), ("2H 4D 3C AS 5S", "2H 4D 3C 6S 5S", "Loss"), ("2H 3S 3C 3H 2S", "3S 3C 2S 2H 2D", "Win"), ("4D 6D 5D 2D JH", "3S 8S 3H TC KH", "Loss"), ("4S 6C 8S 3S 7S", "AD KS 2D 7D 7C", "Loss"), ("6S 4C 7H 8C 3H", "5H JC AH 9D 9C", "Loss"), ("9D 9H JH TC QH", "3C 2S JS 5C 7H", "Win"), ("2H TC 8S AD 9S", "4H TS 7H 2C 5C", "Win"), ("9D 3S 2C 7S 7C", "JC TD 3C TC 9H", "Loss"), ) __SCREAMING_SNAKE_CASE : Optional[int] =( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", True), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", False), ("AS 3S 4S 8S 2S", True), ) __SCREAMING_SNAKE_CASE : Dict =( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", False), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", True), ) __SCREAMING_SNAKE_CASE : Dict =( ("2H 4D 3C AS 5S", True, [5, 4, 3, 2, 14]), ("2H 5D 3C AS 5S", False, [14, 5, 5, 3, 2]), ("JH QD KC AS TS", False, [14, 13, 12, 11, 10]), ("9D 3S 2C 7S 7C", False, [9, 7, 7, 3, 2]), ) __SCREAMING_SNAKE_CASE : int =( ("JH AH TH KH QH", 0), ("JH 9H TH KH QH", 0), ("JC KH JS JD JH", 7), ("KH KC 3S 3H 3D", 6), ("8C 9C 5C 3C TC", 0), ("JS QS 9H TS KH", 0), ("7C 7S KH 2H 7H", 3), ("3C KH 5D 5S KH", 2), ("QH 8H KD JH 8S", 1), ("2D 6D 9D TH 7D", 0), ) __SCREAMING_SNAKE_CASE : List[Any] =( ("JH AH TH KH QH", 23), ("JH 9H TH KH QH", 22), ("JC KH JS JD JH", 21), ("KH KC 3S 3H 3D", 20), ("8C 9C 5C 3C TC", 19), ("JS QS 9H TS KH", 18), ("7C 7S KH 2H 7H", 17), ("3C KH 5D 5S KH", 16), ("QH 8H KD JH 8S", 15), ("2D 6D 9D TH 7D", 14), ) def UpperCamelCase__ ( ): lowercase , lowercase = randrange(len(_UpperCamelCase ) ), randrange(len(_UpperCamelCase ) ) lowercase = ["""Loss""", """Tie""", """Win"""][(play >= oppo) + (play > oppo)] lowercase , lowercase = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def UpperCamelCase__ ( lowerCAmelCase__ = 100 ): return (generate_random_hand() for _ in range(_UpperCamelCase )) @pytest.mark.parametrize("""hand, expected""" ,_UpperCamelCase ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): assert PokerHand(_UpperCamelCase )._is_flush() == expected @pytest.mark.parametrize("""hand, expected""" ,_UpperCamelCase ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): assert PokerHand(_UpperCamelCase )._is_straight() == expected @pytest.mark.parametrize("""hand, expected, card_values""" ,_UpperCamelCase ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): lowercase = PokerHand(_UpperCamelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("""hand, expected""" ,_UpperCamelCase ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): assert PokerHand(_UpperCamelCase )._is_same_kind() == expected @pytest.mark.parametrize("""hand, expected""" ,_UpperCamelCase ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ): assert PokerHand(_UpperCamelCase )._hand_type == expected @pytest.mark.parametrize("""hand, other, expected""" ,_UpperCamelCase ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected @pytest.mark.parametrize("""hand, other, expected""" ,generate_random_hands() ) def UpperCamelCase__ ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ): assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected def UpperCamelCase__ ( ): lowercase = [PokerHand(_UpperCamelCase ) for hand in SORTED_HANDS] lowercase = poker_hands.copy() shuffle(_UpperCamelCase ) lowercase = chain(sorted(_UpperCamelCase ) ) for index, hand in enumerate(_UpperCamelCase ): assert hand == poker_hands[index] def UpperCamelCase__ ( ): lowercase = [PokerHand("""2D AC 3H 4H 5S""" ), PokerHand("""2S 3H 4H 5S 6C""" )] pokerhands.sort(reverse=_UpperCamelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def UpperCamelCase__ ( ): lowercase = PokerHand("""2C 4S AS 3D 5C""" ) lowercase = True lowercase = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def UpperCamelCase__ ( ): lowercase = 0 lowercase = os.path.abspath(os.path.dirname(_UpperCamelCase ) ) lowercase = os.path.join(_UpperCamelCase ,"""poker_hands.txt""" ) with open(_UpperCamelCase ) as file_hand: for line in file_hand: lowercase = line[:14].strip() lowercase = line[15:].strip() lowercase , lowercase = PokerHand(_UpperCamelCase ), PokerHand(_UpperCamelCase ) lowercase = player.compare_with(_UpperCamelCase ) if output == "Win": answer += 1 assert answer == 376
428
'''simple docstring''' import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelWithLMHead, AutoTokenizer, PretrainedConfig, PreTrainedTokenizer, ) from transformers.optimization import ( Adafactor, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.utils.versions import require_version lowerCamelCase : Optional[int] = logging.getLogger(__name__) require_version("pytorch_lightning>=1.0.4") lowerCamelCase : Union[str, Any] = { "base": AutoModel, "sequence-classification": AutoModelForSequenceClassification, "question-answering": AutoModelForQuestionAnswering, "pretraining": AutoModelForPreTraining, "token-classification": AutoModelForTokenClassification, "language-modeling": AutoModelWithLMHead, "summarization": AutoModelForSeqaSeqLM, "translation": AutoModelForSeqaSeqLM, } # update this and the import above to support new schedulers from transformers.optimization lowerCamelCase : str = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, # '': get_constant_schedule, # not supported for now # '': get_constant_schedule_with_warmup, # not supported for now } lowerCamelCase : Optional[Any] = sorted(arg_to_scheduler.keys()) lowerCamelCase : int = "{" + ", ".join(arg_to_scheduler_choices) + "}" class A__ ( pl.LightningModule ): def __init__( self : Optional[Any] , _a : argparse.Namespace , _a : Any=None , _a : int="base" , _a : Dict=None , _a : Tuple=None , _a : Any=None , **_a : List[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__() # TODO: move to self.save_hyperparameters() # self.save_hyperparameters() # can also expand arguments into trainer signature for easier reading self.save_hyperparameters(_a ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =Path(self.hparams.output_dir ) _SCREAMING_SNAKE_CASE =self.hparams.cache_dir if self.hparams.cache_dir else None if config is None: _SCREAMING_SNAKE_CASE =AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path , **({'num_labels': num_labels} if num_labels is not None else {}) , cache_dir=_a , **_a , ) else: _SCREAMING_SNAKE_CASE =config _SCREAMING_SNAKE_CASE =('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout') for p in extra_model_params: if getattr(self.hparams , _a , _a ): assert hasattr(self.config , _a ), f"model config doesn't have a `{p}` attribute" setattr(self.config , _a , getattr(self.hparams , _a ) ) if tokenizer is None: _SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path , cache_dir=_a , ) else: _SCREAMING_SNAKE_CASE =tokenizer _SCREAMING_SNAKE_CASE =MODEL_MODES[mode] if model is None: _SCREAMING_SNAKE_CASE =self.model_type.from_pretrained( self.hparams.model_name_or_path , from_tf=bool('.ckpt' in self.hparams.model_name_or_path ) , config=self.config , cache_dir=_a , ) else: _SCREAMING_SNAKE_CASE =model def A ( self : List[Any] , *_a : Optional[int] , **_a : int ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_type.from_pretrained(*_a , **_a ) def A ( self : List[Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =arg_to_scheduler[self.hparams.lr_scheduler] _SCREAMING_SNAKE_CASE =get_schedule_func( self.opt , num_warmup_steps=self.hparams.warmup_steps , num_training_steps=self.total_steps() ) _SCREAMING_SNAKE_CASE ={'scheduler': scheduler, 'interval': 'step', 'frequency': 1} return scheduler def A ( self : str ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model _SCREAMING_SNAKE_CASE =['bias', 'LayerNorm.weight'] _SCREAMING_SNAKE_CASE =[ { 'params': [ p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay ) ], # check this named paramters 'weight_decay': self.hparams.weight_decay, }, { 'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] if self.hparams.adafactor: _SCREAMING_SNAKE_CASE =Adafactor( _a , lr=self.hparams.learning_rate , scale_parameter=_a , relative_step=_a ) else: _SCREAMING_SNAKE_CASE =AdamW( _a , lr=self.hparams.learning_rate , eps=self.hparams.adam_epsilon ) _SCREAMING_SNAKE_CASE =optimizer _SCREAMING_SNAKE_CASE =self.get_lr_scheduler() return [optimizer], [scheduler] def A ( self : Tuple , _a : Dict , _a : List[str] ) -> str: '''simple docstring''' return self.validation_step(_a , _a ) def A ( self : Dict , _a : str ) -> Dict: '''simple docstring''' return self.validation_end(_a ) def A ( self : Union[str, Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =max(1 , self.hparams.gpus ) # TODO: consider num_tpu_cores _SCREAMING_SNAKE_CASE =self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs def A ( self : int , _a : Any ) -> Union[str, Any]: '''simple docstring''' if stage == "test": _SCREAMING_SNAKE_CASE =len(self.test_dataloader().dataset ) else: _SCREAMING_SNAKE_CASE =self.get_dataloader('train' , self.hparams.train_batch_size , shuffle=_a ) _SCREAMING_SNAKE_CASE =len(self.train_dataloader().dataset ) def A ( self : Union[str, Any] , _a : str , _a : int , _a : bool = False ) -> Optional[int]: '''simple docstring''' raise NotImplementedError('You must implement this for your task' ) def A ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' return self.train_loader def A ( self : str ) -> str: '''simple docstring''' return self.get_dataloader('dev' , self.hparams.eval_batch_size , shuffle=_a ) def A ( self : Tuple ) -> Any: '''simple docstring''' return self.get_dataloader('test' , self.hparams.eval_batch_size , shuffle=_a ) def A ( self : int , _a : Dict ) -> Optional[Any]: '''simple docstring''' return os.path.join( self.hparams.data_dir , 'cached_{}_{}_{}'.format( _a , list(filter(_a , self.hparams.model_name_or_path.split('/' ) ) ).pop() , str(self.hparams.max_seq_length ) , ) , ) @pl.utilities.rank_zero_only def A ( self : Optional[Any] , _a : Dict[str, Any] ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.output_dir.joinpath('best_tfmr' ) _SCREAMING_SNAKE_CASE =self.step_count self.model.save_pretrained(_a ) self.tokenizer.save_pretrained(_a ) @staticmethod def A ( _a : Any , _a : Any ) -> List[str]: '''simple docstring''' parser.add_argument( '--model_name_or_path' , default=_a , type=_a , required=_a , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--config_name' , default='' , type=_a , help='Pretrained config name or path if not the same as model_name' ) parser.add_argument( '--tokenizer_name' , default=_a , type=_a , help='Pretrained tokenizer name or path if not the same as model_name' , ) parser.add_argument( '--cache_dir' , default=str(Path(_a ).parent / 'test_run' / 'cache' ) , type=_a , help='Where do you want to store the pre-trained models downloaded from huggingface.co' , ) parser.add_argument( '--encoder_layerdrop' , type=_a , help='Encoder layer dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--decoder_layerdrop' , type=_a , help='Decoder layer dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--dropout' , type=_a , help='Dropout probability (Optional). Goes into model.config' , ) parser.add_argument( '--attention_dropout' , type=_a , help='Attention dropout probability (Optional). Goes into model.config' , ) parser.add_argument('--learning_rate' , default=5e-5 , type=_a , help='The initial learning rate for Adam.' ) parser.add_argument( '--lr_scheduler' , default='linear' , choices=_a , metavar=_a , type=_a , help='Learning rate scheduler' , ) parser.add_argument('--weight_decay' , default=0.0 , type=_a , help='Weight decay if we apply some.' ) parser.add_argument('--adam_epsilon' , default=1e-8 , type=_a , help='Epsilon for Adam optimizer.' ) parser.add_argument('--warmup_steps' , default=0 , type=_a , help='Linear warmup over warmup_steps.' ) parser.add_argument('--num_workers' , default=4 , type=_a , help='kwarg passed to DataLoader' ) parser.add_argument('--num_train_epochs' , dest='max_epochs' , default=3 , type=_a ) parser.add_argument('--train_batch_size' , default=32 , type=_a ) parser.add_argument('--eval_batch_size' , default=32 , type=_a ) parser.add_argument('--adafactor' , action='store_true' ) class A__ ( pl.Callback ): def A ( self : Tuple , _a : str , _a : int ) -> Dict: '''simple docstring''' if ( trainer.is_global_zero and trainer.global_rank == 0 ): # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed. pl_module.model.rag.retriever.init_retrieval() # better to use hook functions. class A__ ( pl.Callback ): def A ( self : Tuple , _a : str , _a : Tuple ) -> Tuple: '''simple docstring''' for name, param in pl_module.model.rag.named_parameters(): if param.grad is None: print(_a ) class A__ ( pl.Callback ): def A ( self : List[str] , _a : Tuple , _a : Optional[int] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =trainer.lr_schedulers[0]['scheduler'] _SCREAMING_SNAKE_CASE ={f"lr_group_{i}": lr for i, lr in enumerate(lr_scheduler.get_lr() )} pl_module.logger.log_metrics(_a ) def A ( self : List[Any] , _a : pl.Trainer , _a : pl.LightningModule ) -> Optional[int]: '''simple docstring''' rank_zero_info('***** Validation results *****' ) _SCREAMING_SNAKE_CASE =trainer.callback_metrics # Log results for key in sorted(_a ): if key not in ["log", "progress_bar"]: rank_zero_info('{} = {}\n'.format(_a , str(metrics[key] ) ) ) def A ( self : Optional[Any] , _a : pl.Trainer , _a : pl.LightningModule ) -> List[str]: '''simple docstring''' rank_zero_info('***** Test results *****' ) _SCREAMING_SNAKE_CASE =trainer.callback_metrics # Log and save results to file _SCREAMING_SNAKE_CASE =os.path.join(pl_module.hparams.output_dir , 'test_results.txt' ) with open(_a , 'w' ) as writer: for key in sorted(_a ): if key not in ["log", "progress_bar"]: rank_zero_info('{} = {}\n'.format(_a , str(metrics[key] ) ) ) writer.write('{} = {}\n'.format(_a , str(metrics[key] ) ) ) def _lowerCAmelCase ( _UpperCamelCase : Optional[int] , _UpperCamelCase : Union[str, Any] ) -> None: """simple docstring""" parser.add_argument( '--output_dir' , default=str(Path(_UpperCamelCase ).parent / 'test_run' / 'model_checkpoints' ) , type=_UpperCamelCase , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument( '--fp16' , action='store_true' , help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit' , ) parser.add_argument( '--fp16_opt_level' , type=_UpperCamelCase , default='O2' , help=( 'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].' 'See details at https://nvidia.github.io/apex/amp.html' ) , ) parser.add_argument('--n_tpu_cores' , dest='tpu_cores' , type=_UpperCamelCase ) parser.add_argument('--max_grad_norm' , dest='gradient_clip_val' , default=1.0 , type=_UpperCamelCase , help='Max gradient norm' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_predict' , action='store_true' , help='Whether to run predictions on the test set.' ) parser.add_argument( '--gradient_accumulation_steps' , dest='accumulate_grad_batches' , type=_UpperCamelCase , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--seed' , type=_UpperCamelCase , default=42 , help='random seed for initialization' ) parser.add_argument( '--data_dir' , default=str(Path(_UpperCamelCase ).parent / 'test_run' / 'dummy-train-data' ) , type=_UpperCamelCase , help='The input data dir. Should contain the training files for the CoNLL-2003 NER task.' , ) def _lowerCAmelCase ( _UpperCamelCase : BaseTransformer , _UpperCamelCase : argparse.Namespace , _UpperCamelCase : Any=None , _UpperCamelCase : str=True , _UpperCamelCase : Any=[] , _UpperCamelCase : Union[str, Any]=None , _UpperCamelCase : str=None , **_UpperCamelCase : Optional[int] , ) -> Tuple: """simple docstring""" pl.seed_everything(args.seed ) # init model _SCREAMING_SNAKE_CASE =Path(model.hparams.output_dir ) odir.mkdir(exist_ok=_UpperCamelCase ) # add custom checkpoints if checkpoint_callback is None: _SCREAMING_SNAKE_CASE =pl.callbacks.ModelCheckpoint( filepath=args.output_dir , prefix='checkpoint' , monitor='val_loss' , mode='min' , save_top_k=1 ) if early_stopping_callback: extra_callbacks.append(_UpperCamelCase ) if logging_callback is None: _SCREAMING_SNAKE_CASE =LoggingCallback() _SCREAMING_SNAKE_CASE ={} if args.fpaa: _SCREAMING_SNAKE_CASE =16 if args.gpus > 1: _SCREAMING_SNAKE_CASE ='auto' _SCREAMING_SNAKE_CASE ='ddp' _SCREAMING_SNAKE_CASE =args.accumulate_grad_batches _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE ='auto' _SCREAMING_SNAKE_CASE =pl.Trainer.from_argparse_args( _UpperCamelCase , weights_summary=_UpperCamelCase , callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] , logger=_UpperCamelCase , val_check_interval=1 , num_sanity_val_steps=2 , **_UpperCamelCase , ) if args.do_train: trainer.fit(_UpperCamelCase ) else: print('RAG modeling tests with new set functions successfuly executed!' ) return trainer
405
0
"""simple docstring""" import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def A ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = AlbertConfig.from_json_file(snake_case__ ) print(f"""Building PyTorch model from configuration: {config}""" ) SCREAMING_SNAKE_CASE__ = AlbertForPreTraining(snake_case__ ) # Load weights from tf checkpoint load_tf_weights_in_albert(snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , snake_case__ ) if __name__ == "__main__": A_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--albert_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained ALBERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) A_ : List[str] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
700
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : List[Any] = logging.get_logger(__name__) A_ : Dict = { "microsoft/unispeech-large-1500h-cv": ( "https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json" ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class lowerCamelCase (A__ ): lowerCamelCase__ : int = 'unispeech' def __init__( self : Union[str, Any] , __UpperCAmelCase : List[Any]=3_2 , __UpperCAmelCase : Union[str, Any]=7_6_8 , __UpperCAmelCase : Tuple=1_2 , __UpperCAmelCase : Dict=1_2 , __UpperCAmelCase : Optional[Any]=3_0_7_2 , __UpperCAmelCase : Optional[Any]="gelu" , __UpperCAmelCase : Union[str, Any]=0.1 , __UpperCAmelCase : List[Any]=0.1 , __UpperCAmelCase : List[str]=0.1 , __UpperCAmelCase : List[str]=0.0 , __UpperCAmelCase : Tuple=0.0 , __UpperCAmelCase : List[Any]=0.1 , __UpperCAmelCase : Union[str, Any]=0.1 , __UpperCAmelCase : Union[str, Any]=0.02 , __UpperCAmelCase : Union[str, Any]=1e-5 , __UpperCAmelCase : List[Any]="group" , __UpperCAmelCase : Union[str, Any]="gelu" , __UpperCAmelCase : Any=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , __UpperCAmelCase : List[str]=(5, 2, 2, 2, 2, 2, 2) , __UpperCAmelCase : int=(1_0, 3, 3, 3, 3, 2, 2) , __UpperCAmelCase : str=False , __UpperCAmelCase : Any=1_2_8 , __UpperCAmelCase : str=1_6 , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Union[str, Any]=0.05 , __UpperCAmelCase : str=1_0 , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : List[Any]=0.0 , __UpperCAmelCase : Tuple=1_0 , __UpperCAmelCase : Tuple=0 , __UpperCAmelCase : Tuple=3_2_0 , __UpperCAmelCase : Any=2 , __UpperCAmelCase : Optional[int]=0.1 , __UpperCAmelCase : Any=1_0_0 , __UpperCAmelCase : str=2_5_6 , __UpperCAmelCase : Dict=2_5_6 , __UpperCAmelCase : Dict=0.1 , __UpperCAmelCase : List[str]="mean" , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : List[Any]=False , __UpperCAmelCase : str=2_5_6 , __UpperCAmelCase : Dict=8_0 , __UpperCAmelCase : List[Any]=0 , __UpperCAmelCase : int=1 , __UpperCAmelCase : Optional[int]=2 , __UpperCAmelCase : Any=0.5 , **__UpperCAmelCase : List[str] , ) -> Tuple: super().__init__(**__UpperCAmelCase , pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = feat_extract_norm SCREAMING_SNAKE_CASE__ = feat_extract_activation SCREAMING_SNAKE_CASE__ = list(__UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = list(__UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = list(__UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = conv_bias SCREAMING_SNAKE_CASE__ = num_conv_pos_embeddings SCREAMING_SNAKE_CASE__ = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE__ = len(self.conv_dim ) SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_dropout SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = activation_dropout SCREAMING_SNAKE_CASE__ = feat_proj_dropout SCREAMING_SNAKE_CASE__ = final_dropout SCREAMING_SNAKE_CASE__ = layerdrop SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_ctc_classes SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = do_stable_layer_norm SCREAMING_SNAKE_CASE__ = use_weighted_layer_sum SCREAMING_SNAKE_CASE__ = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" F""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE__ = apply_spec_augment SCREAMING_SNAKE_CASE__ = mask_time_prob SCREAMING_SNAKE_CASE__ = mask_time_length SCREAMING_SNAKE_CASE__ = mask_time_min_masks SCREAMING_SNAKE_CASE__ = mask_feature_prob SCREAMING_SNAKE_CASE__ = mask_feature_length SCREAMING_SNAKE_CASE__ = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE__ = num_codevectors_per_group SCREAMING_SNAKE_CASE__ = num_codevector_groups SCREAMING_SNAKE_CASE__ = contrastive_logits_temperature SCREAMING_SNAKE_CASE__ = feat_quantizer_dropout SCREAMING_SNAKE_CASE__ = num_negatives SCREAMING_SNAKE_CASE__ = codevector_dim SCREAMING_SNAKE_CASE__ = proj_codevector_dim SCREAMING_SNAKE_CASE__ = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE__ = ctc_loss_reduction SCREAMING_SNAKE_CASE__ = ctc_zero_infinity # pretraining loss SCREAMING_SNAKE_CASE__ = replace_prob @property def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: return functools.reduce(operator.mul , self.conv_stride , 1 )
616
0
'''simple docstring''' import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class _A ( unittest.TestCase ): def lowercase__ ( self : List[str] ) -> Dict: """simple docstring""" super().tearDown() gc.collect() def lowercase__ ( self : Any ) -> Tuple: """simple docstring""" __snake_case , __snake_case : Dict = FlaxControlNetModel.from_pretrained( """lllyasviel/sd-controlnet-canny""" , from_pt=__magic_name__ , dtype=jnp.bfloataa ) __snake_case , __snake_case : Tuple = FlaxStableDiffusionControlNetPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , controlnet=__magic_name__ , from_pt=__magic_name__ , dtype=jnp.bfloataa ) __snake_case : Tuple = controlnet_params __snake_case : Tuple = """bird""" __snake_case : Dict = jax.device_count() __snake_case : Any = pipe.prepare_text_inputs([prompts] * num_samples ) __snake_case : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ) __snake_case : int = pipe.prepare_image_inputs([canny_image] * num_samples ) __snake_case : int = jax.random.PRNGKey(0 ) __snake_case : Dict = jax.random.split(__magic_name__ , jax.device_count() ) __snake_case : Any = replicate(__magic_name__ ) __snake_case : str = shard(__magic_name__ ) __snake_case : Optional[Any] = shard(__magic_name__ ) __snake_case : List[str] = pipe( prompt_ids=__magic_name__ , image=__magic_name__ , params=__magic_name__ , prng_seed=__magic_name__ , num_inference_steps=50 , jit=__magic_name__ , ).images assert images.shape == (jax.device_count(), 1, 7_68, 5_12, 3) __snake_case : Tuple = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __snake_case : Optional[Any] = images[0, 2_53:2_56, 2_53:2_56, -1] __snake_case : str = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __snake_case : Optional[int] = jnp.array( [0.167969, 0.116699, 0.081543, 0.154297, 0.132812, 0.108887, 0.169922, 0.169922, 0.205078] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2 def lowercase__ ( self : Any ) -> List[str]: """simple docstring""" __snake_case , __snake_case : Any = FlaxControlNetModel.from_pretrained( """lllyasviel/sd-controlnet-openpose""" , from_pt=__magic_name__ , dtype=jnp.bfloataa ) __snake_case , __snake_case : Tuple = FlaxStableDiffusionControlNetPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , controlnet=__magic_name__ , from_pt=__magic_name__ , dtype=jnp.bfloataa ) __snake_case : List[Any] = controlnet_params __snake_case : Dict = """Chef in the kitchen""" __snake_case : Dict = jax.device_count() __snake_case : str = pipe.prepare_text_inputs([prompts] * num_samples ) __snake_case : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png""" ) __snake_case : Any = pipe.prepare_image_inputs([pose_image] * num_samples ) __snake_case : Any = jax.random.PRNGKey(0 ) __snake_case : Optional[Any] = jax.random.split(__magic_name__ , jax.device_count() ) __snake_case : List[Any] = replicate(__magic_name__ ) __snake_case : Optional[Any] = shard(__magic_name__ ) __snake_case : Optional[Any] = shard(__magic_name__ ) __snake_case : Optional[int] = pipe( prompt_ids=__magic_name__ , image=__magic_name__ , params=__magic_name__ , prng_seed=__magic_name__ , num_inference_steps=50 , jit=__magic_name__ , ).images assert images.shape == (jax.device_count(), 1, 7_68, 5_12, 3) __snake_case : str = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) __snake_case : Union[str, Any] = images[0, 2_53:2_56, 2_53:2_56, -1] __snake_case : Any = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __snake_case : Optional[int] = jnp.array( [[0.271484, 0.261719, 0.275391, 0.277344, 0.279297, 0.291016, 0.294922, 0.302734, 0.302734]] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
26
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys lowerCamelCase = subprocess.check_output("""git merge-base main HEAD""".split()).decode("""utf-8""") lowerCamelCase = subprocess.check_output(F'git diff --name-only {fork_point_sha}'.split()).decode("""utf-8""").split() lowerCamelCase = """|""".join(sys.argv[1:]) lowerCamelCase = re.compile(RF'^({joined_dirs}).*?\.py$') lowerCamelCase = [x for x in modified_files if regex.match(x)] print(""" """.join(relevant_modified_files), end="""""")
191
0
def _lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' A_ = 0 for ch in input_str: A_ = ord(SCREAMING_SNAKE_CASE ) A_ = pow(2 , SCREAMING_SNAKE_CASE ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
563
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer __lowercase = logging.get_logger(__name__) __lowercase = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} __lowercase = { """vocab_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json""" ), }, } __lowercase = { """yjernite/retribert-base-uncased""": 512, } __lowercase = { """yjernite/retribert-base-uncased""": {"""do_lower_case""": True}, } class _lowercase ( __lowerCamelCase ): _lowercase : Union[str, Any] = VOCAB_FILES_NAMES _lowercase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _lowercase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Tuple = PRETRAINED_INIT_CONFIGURATION _lowercase : List[Any] = RetriBertTokenizer _lowercase : Optional[int] = ['input_ids', 'attention_mask'] def __init__( self : Optional[Any] , lowerCamelCase__ : int=None , lowerCamelCase__ : Tuple=None , lowerCamelCase__ : Dict=True , lowerCamelCase__ : Union[str, Any]="[UNK]" , lowerCamelCase__ : Optional[Any]="[SEP]" , lowerCamelCase__ : List[Any]="[PAD]" , lowerCamelCase__ : Tuple="[CLS]" , lowerCamelCase__ : List[Any]="[MASK]" , lowerCamelCase__ : Dict=True , lowerCamelCase__ : str=None , **lowerCamelCase__ : List[Any] , ) -> Dict: """simple docstring""" super().__init__( lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , do_lower_case=lowerCamelCase__ , unk_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , cls_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , tokenize_chinese_chars=lowerCamelCase__ , strip_accents=lowerCamelCase__ , **lowerCamelCase__ , ) A_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , lowerCamelCase__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , lowerCamelCase__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , lowerCamelCase__ ) != tokenize_chinese_chars ): A_ = getattr(lowerCamelCase__ , normalizer_state.pop('''type''' ) ) A_ = do_lower_case A_ = strip_accents A_ = tokenize_chinese_chars A_ = normalizer_class(**lowerCamelCase__ ) A_ = do_lower_case def UpperCamelCase ( self : Optional[Any] , lowerCamelCase__ : int , lowerCamelCase__ : List[str]=None ) -> Union[str, Any]: """simple docstring""" A_ = [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 UpperCamelCase ( self : Any , lowerCamelCase__ : List[int] , lowerCamelCase__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" A_ = [self.sep_token_id] A_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase ( self : Union[str, Any] , lowerCamelCase__ : str , lowerCamelCase__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" A_ = self._tokenizer.model.save(lowerCamelCase__ , name=lowerCamelCase__ ) return tuple(lowerCamelCase__ )
563
1
import os from pathlib import Path def SCREAMING_SNAKE_CASE__ ( ) -> List[Any]: from torch.utils.cpp_extension import load snake_case : Optional[int] = Path(lowercase ).resolve().parent.parent.parent / """kernels""" / """deformable_detr""" snake_case : Any = [ root / filename for filename in [ """vision.cpp""", os.path.join("""cpu""" ,"""ms_deform_attn_cpu.cpp""" ), os.path.join("""cuda""" ,"""ms_deform_attn_cuda.cu""" ), ] ] load( """MultiScaleDeformableAttention""" ,lowercase ,with_cuda=lowercase ,extra_include_paths=[str(lowercase )] ,extra_cflags=["""-DWITH_CUDA=1"""] ,extra_cuda_cflags=[ """-DCUDA_HAS_FP16=1""", """-D__CUDA_NO_HALF_OPERATORS__""", """-D__CUDA_NO_HALF_CONVERSIONS__""", """-D__CUDA_NO_HALF2_OPERATORS__""", ] ,) import MultiScaleDeformableAttention as MSDA return MSDA
587
def SCREAMING_SNAKE_CASE__ ( lowercase ) -> bool: snake_case : set[int] = set() # To detect a back edge, keep track of vertices currently in the recursion stack snake_case : set[int] = set() return any( node not in visited and depth_first_search(lowercase ,lowercase ,lowercase ,lowercase ) for node in graph ) def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase ) -> bool: visited.add(lowercase ) rec_stk.add(lowercase ) for node in graph[vertex]: if node not in visited: if depth_first_search(lowercase ,lowercase ,lowercase ,lowercase ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(lowercase ) return False if __name__ == "__main__": from doctest import testmod testmod()
587
1
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _a : List[Any] = logging.getLogger(__name__) @dataclass class __A : snake_case :str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case :Optional[str] = field( default=__magic_name__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case :Optional[str] = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case :Optional[str] = field( default=__magic_name__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case :bool = field(default=__magic_name__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case :Optional[str] = field( default=__magic_name__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __A : snake_case :str = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case :Optional[str] = field( default=__magic_name__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case :int = field( default=128 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case :bool = field( default=__magic_name__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _lowercase ( ) -> str: """simple docstring""" __UpperCAmelCase : int = 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 : str = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __UpperCAmelCase : List[Any] = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" " --overwrite_output_dir to overcome." ) __UpperCAmelCase : List[str] = import_module("tasks" ) try: __UpperCAmelCase : Optional[int] = getattr(lowerCamelCase__ , model_args.task_type ) __UpperCAmelCase : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( f"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ f"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""" ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCamelCase__ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task __UpperCAmelCase : Any = token_classification_task.get_labels(data_args.labels ) __UpperCAmelCase : Dict[int, str] = dict(enumerate(lowerCamelCase__ ) ) __UpperCAmelCase : Any = len(lowerCamelCase__ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __UpperCAmelCase : List[str] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCamelCase__ , idalabel=lowerCamelCase__ , labelaid={label: i for i, label in enumerate(lowerCamelCase__ )} , cache_dir=model_args.cache_dir , ) __UpperCAmelCase : List[Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) __UpperCAmelCase : Union[str, Any] = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCamelCase__ , cache_dir=model_args.cache_dir , ) # Get datasets __UpperCAmelCase : Tuple = ( TokenClassificationDataset( token_classification_task=lowerCamelCase__ , data_dir=data_args.data_dir , tokenizer=lowerCamelCase__ , labels=lowerCamelCase__ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) __UpperCAmelCase : int = ( TokenClassificationDataset( token_classification_task=lowerCamelCase__ , data_dir=data_args.data_dir , tokenizer=lowerCamelCase__ , labels=lowerCamelCase__ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCamelCase__ , lowerCamelCase__ ) -> Tuple[List[int], List[int]]: __UpperCAmelCase : Tuple = np.argmax(lowerCamelCase__ , axis=2 ) __UpperCAmelCase : str = preds.shape __UpperCAmelCase : List[Any] = [[] for _ in range(lowerCamelCase__ )] __UpperCAmelCase : Union[str, Any] = [[] for _ in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ ): for j in range(lowerCamelCase__ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCamelCase__ ) -> Dict: __UpperCAmelCase : Any = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCamelCase__ , lowerCamelCase__ ), "precision": precision_score(lowerCamelCase__ , lowerCamelCase__ ), "recall": recall_score(lowerCamelCase__ , lowerCamelCase__ ), "f1": fa_score(lowerCamelCase__ , lowerCamelCase__ ), } # Data collator __UpperCAmelCase : Dict = DataCollatorWithPadding(lowerCamelCase__ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer __UpperCAmelCase : List[str] = Trainer( model=lowerCamelCase__ , args=lowerCamelCase__ , train_dataset=lowerCamelCase__ , eval_dataset=lowerCamelCase__ , compute_metrics=lowerCamelCase__ , data_collator=lowerCamelCase__ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __UpperCAmelCase : List[str] = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) __UpperCAmelCase : Tuple = trainer.evaluate() __UpperCAmelCase : List[str] = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCamelCase__ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCamelCase__ , lowerCamelCase__ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCamelCase__ ) # Predict if training_args.do_predict: __UpperCAmelCase : List[Any] = TokenClassificationDataset( token_classification_task=lowerCamelCase__ , data_dir=data_args.data_dir , tokenizer=lowerCamelCase__ , labels=lowerCamelCase__ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) __UpperCAmelCase : List[Any] = trainer.predict(lowerCamelCase__ ) __UpperCAmelCase : int = align_predictions(lowerCamelCase__ , lowerCamelCase__ ) __UpperCAmelCase : str = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCamelCase__ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCamelCase__ , lowerCamelCase__ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions __UpperCAmelCase : Any = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCamelCase__ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) return results def _lowercase ( lowerCamelCase__ ) -> Optional[int]: """simple docstring""" main() if __name__ == "__main__": main()
707
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _a : Optional[Any] = logging.get_logger(__name__) _a : int = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all BART models at https://huggingface.co/models?filter=bart _a : Tuple = { "vocab_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json", }, "merges_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt", }, } _a : List[Any] = { "facebook/bart-base": 1024, "facebook/bart-large": 1024, "facebook/bart-large-mnli": 1024, "facebook/bart-large-cnn": 1024, "facebook/bart-large-xsum": 1024, "yjernite/bart_eli5": 1024, } @lru_cache() def _lowercase ( ) -> List[Any]: """simple docstring""" __UpperCAmelCase : Dict = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) __UpperCAmelCase : Optional[Any] = bs[:] __UpperCAmelCase : Optional[int] = 0 for b in range(2**8 ): if b not in bs: bs.append(lowerCamelCase__ ) cs.append(2**8 + n ) n += 1 __UpperCAmelCase : Dict = [chr(lowerCamelCase__ ) for n in cs] return dict(zip(lowerCamelCase__ , lowerCamelCase__ ) ) def _lowercase ( lowerCamelCase__ ) -> str: """simple docstring""" __UpperCAmelCase : Dict = set() __UpperCAmelCase : Union[str, Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __UpperCAmelCase : Optional[Any] = char return pairs class __A (__magic_name__ ): snake_case :Optional[int] = VOCAB_FILES_NAMES snake_case :List[Any] = PRETRAINED_VOCAB_FILES_MAP snake_case :Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case :Optional[int] = ["input_ids", "attention_mask"] def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_="replace" , UpperCamelCase_="<s>" , UpperCamelCase_="</s>" , UpperCamelCase_="</s>" , UpperCamelCase_="<s>" , UpperCamelCase_="<unk>" , UpperCamelCase_="<pad>" , UpperCamelCase_="<mask>" , UpperCamelCase_=False , **UpperCamelCase_ , ): __UpperCAmelCase : str = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else bos_token __UpperCAmelCase : List[str] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else eos_token __UpperCAmelCase : Optional[int] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else sep_token __UpperCAmelCase : int = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else cls_token __UpperCAmelCase : Optional[int] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else unk_token __UpperCAmelCase : Dict = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __UpperCAmelCase : Union[str, Any] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else mask_token super().__init__( errors=UpperCamelCase_ , bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , add_prefix_space=UpperCamelCase_ , **UpperCamelCase_ , ) with open(UpperCamelCase_ , encoding="utf-8" ) as vocab_handle: __UpperCAmelCase : int = json.load(UpperCamelCase_ ) __UpperCAmelCase : Any = {v: k for k, v in self.encoder.items()} __UpperCAmelCase : Any = errors # how to handle errors in decoding __UpperCAmelCase : str = bytes_to_unicode() __UpperCAmelCase : List[str] = {v: k for k, v in self.byte_encoder.items()} with open(UpperCamelCase_ , encoding="utf-8" ) as merges_handle: __UpperCAmelCase : str = merges_handle.read().split("\n" )[1:-1] __UpperCAmelCase : List[str] = [tuple(merge.split() ) for merge in bpe_merges] __UpperCAmelCase : Union[str, Any] = dict(zip(UpperCamelCase_ , range(len(UpperCamelCase_ ) ) ) ) __UpperCAmelCase : Optional[int] = {} __UpperCAmelCase : Optional[int] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __UpperCAmelCase : Dict = re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property def _snake_case ( self ): return len(self.encoder ) def _snake_case ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def _snake_case ( self , UpperCamelCase_ ): if token in self.cache: return self.cache[token] __UpperCAmelCase : List[str] = tuple(UpperCamelCase_ ) __UpperCAmelCase : str = get_pairs(UpperCamelCase_ ) if not pairs: return token while True: __UpperCAmelCase : str = min(UpperCamelCase_ , key=lambda UpperCamelCase_ : self.bpe_ranks.get(UpperCamelCase_ , float("inf" ) ) ) if bigram not in self.bpe_ranks: break __UpperCAmelCase , __UpperCAmelCase : List[Any] = bigram __UpperCAmelCase : Any = [] __UpperCAmelCase : List[str] = 0 while i < len(UpperCamelCase_ ): try: __UpperCAmelCase : Union[str, Any] = word.index(UpperCamelCase_ , UpperCamelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __UpperCAmelCase : str = j if word[i] == first and i < len(UpperCamelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __UpperCAmelCase : Dict = tuple(UpperCamelCase_ ) __UpperCAmelCase : str = new_word if len(UpperCamelCase_ ) == 1: break else: __UpperCAmelCase : int = get_pairs(UpperCamelCase_ ) __UpperCAmelCase : Optional[int] = " ".join(UpperCamelCase_ ) __UpperCAmelCase : Dict = word return word def _snake_case ( self , UpperCamelCase_ ): __UpperCAmelCase : Optional[Any] = [] for token in re.findall(self.pat , UpperCamelCase_ ): __UpperCAmelCase : Any = "".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(UpperCamelCase_ ).split(" " ) ) return bpe_tokens def _snake_case ( self , UpperCamelCase_ ): return self.encoder.get(UpperCamelCase_ , self.encoder.get(self.unk_token ) ) def _snake_case ( self , UpperCamelCase_ ): return self.decoder.get(UpperCamelCase_ ) def _snake_case ( self , UpperCamelCase_ ): __UpperCAmelCase : List[str] = "".join(UpperCamelCase_ ) __UpperCAmelCase : Union[str, Any] = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): if not os.path.isdir(UpperCamelCase_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __UpperCAmelCase : Any = os.path.join( UpperCamelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) __UpperCAmelCase : Optional[int] = os.path.join( UpperCamelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(UpperCamelCase_ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=UpperCamelCase_ , ensure_ascii=UpperCamelCase_ ) + "\n" ) __UpperCAmelCase : str = 0 with open(UpperCamelCase_ , "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 UpperCamelCase_ : 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 : str = token_index writer.write(" ".join(UpperCamelCase_ ) + "\n" ) index += 1 return vocab_file, merge_file def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCAmelCase : List[Any] = [self.cls_token_id] __UpperCAmelCase : Tuple = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase_ , token_ids_a=UpperCamelCase_ , already_has_special_tokens=UpperCamelCase_ ) if token_ids_a is None: return [1] + ([0] * len(UpperCamelCase_ )) + [1] return [1] + ([0] * len(UpperCamelCase_ )) + [1, 1] + ([0] * len(UpperCamelCase_ )) + [1] def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): __UpperCAmelCase : int = [self.sep_token_id] __UpperCAmelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_=False , **UpperCamelCase_ ): __UpperCAmelCase : List[str] = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(UpperCamelCase_ ) > 0 and not text[0].isspace()): __UpperCAmelCase : Tuple = " " + text return (text, kwargs)
10
0