code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
def _a ( a :int ) -> int: assert isinstance(a , a ), F"""The input value of [n={number}] is not an integer""" if number == 1: return 2 elif number < 1: a = F"""The input value of [n={number}] has to be > 0""" raise ValueError(a ) else: a = sylvester(number - 1 ) a = num - 1 a = num return lower * upper + 1 if __name__ == "__main__": print(f"""The 8th number in Sylvester's sequence: {sylvester(8)}""")
0
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> str: """simple docstring""" a_ : Tuple = [] for line in lines: a_ : Any = re.sub(R'#.*' , '' , __A ) # remove comments if line: filtered_lines.append(__A ) a_ : Tuple = '\n'.join(__A ) # Make a hash from all this code a_ : Tuple = full_str.encode('utf-8' ) return shaaaa(__A ).hexdigest() # get importable module names and hash for caching UpperCAmelCase_ : List[Any] = { 'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), 'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), 'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), 'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), 'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), 'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), 'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), 'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions UpperCAmelCase_ : Dict = { '.csv': ('csv', {}), '.tsv': ('csv', {'sep': '\t'}), '.json': ('json', {}), '.jsonl': ('json', {}), '.parquet': ('parquet', {}), '.arrow': ('arrow', {}), '.txt': ('text', {}), } _EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) UpperCAmelCase_ : Optional[int] = {'imagefolder', 'audiofolder'} # Used to filter data files based on extensions given a module name UpperCAmelCase_ : Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('.zip') _MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')
32
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available SCREAMING_SNAKE_CASE_: int ={ 'configuration_ernie': ['ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ErnieConfig', 'ErnieOnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: List[str] =[ 'ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ErnieForCausalLM', 'ErnieForMaskedLM', 'ErnieForMultipleChoice', 'ErnieForNextSentencePrediction', 'ErnieForPreTraining', 'ErnieForQuestionAnswering', 'ErnieForSequenceClassification', 'ErnieForTokenClassification', 'ErnieModel', 'ErniePreTrainedModel', ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: Union[str, Any] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Optional[int] = '''convbert''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=3_0_5_2_2 , SCREAMING_SNAKE_CASE__ : Dict=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[int]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : Any=1E-12 , SCREAMING_SNAKE_CASE__ : int=1 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=9 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : Dict=None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> Any: super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) a_ : Tuple = vocab_size a_ : List[str] = hidden_size a_ : List[str] = num_hidden_layers a_ : Dict = num_attention_heads a_ : Optional[int] = intermediate_size a_ : int = hidden_act a_ : Dict = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : str = max_position_embeddings a_ : List[str] = type_vocab_size a_ : List[str] = initializer_range a_ : Tuple = layer_norm_eps a_ : Optional[int] = embedding_size a_ : List[Any] = head_ratio a_ : List[Any] = conv_kernel_size a_ : Tuple = num_groups a_ : Tuple = classifier_dropout class SCREAMING_SNAKE_CASE__ ( lowercase__ ): @property def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": a_ : Tuple = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a_ : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
32
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings lowerCamelCase : Tuple = R'\n [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and\n can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.\n\n Args:\n title_sep (`str`, *optional*, defaults to `" / "`):\n Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].\n doc_sep (`str`, *optional*, defaults to `" // "`):\n Separator inserted between the text of the retrieved document and the original input when calling\n [`RagRetriever`].\n n_docs (`int`, *optional*, defaults to 5):\n Number of documents to retrieve.\n max_combined_length (`int`, *optional*, defaults to 300):\n Max length of contextualized input returned by [`~RagRetriever.__call__`].\n retrieval_vector_size (`int`, *optional*, defaults to 768):\n Dimensionality of the document embeddings indexed by [`RagRetriever`].\n retrieval_batch_size (`int`, *optional*, defaults to 8):\n Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated\n [`RagRetriever`].\n dataset (`str`, *optional*, defaults to `"wiki_dpr"`):\n A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids\n using `datasets.list_datasets()`).\n dataset_split (`str`, *optional*, defaults to `"train"`)\n Which split of the `dataset` to load.\n index_name (`str`, *optional*, defaults to `"compressed"`)\n The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and\n `"compressed"`.\n index_path (`str`, *optional*)\n The path to the serialized faiss index on disk.\n passages_path (`str`, *optional*):\n A path to text passages compatible with the faiss index. Required if using\n [`~models.rag.retrieval_rag.LegacyIndex`]\n use_dummy_dataset (`bool`, *optional*, defaults to `False`)\n Whether to load a "dummy" variant of the dataset specified by `dataset`.\n label_smoothing (`float`, *optional*, defaults to 0.0):\n Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing\n in the loss calculation. If set to 0, no label smoothing is performed.\n do_marginalize (`bool`, *optional*, defaults to `False`):\n If `True`, the logits are marginalized over all documents by making use of\n `torch.nn.functional.log_softmax`.\n reduce_loss (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.\n do_deduplication (`bool`, *optional*, defaults to `True`):\n Whether or not to deduplicate the generations from different context documents for a given input. Has to be\n set to `False` if used while training with distributed backend.\n exclude_bos_score (`bool`, *optional*, defaults to `False`):\n Whether or not to disregard the BOS token when computing the loss.\n output_retrieved(`bool`, *optional*, defaults to `False`):\n If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and\n `context_attention_mask` are returned. See returned tensors for more detail.\n use_cache (`bool`, *optional*, defaults to `True`):\n Whether or not the model should return the last key/values attentions (not used by all models).\n forced_eos_token_id (`int`, *optional*):\n The id of the token to force as the last generated token when `max_length` is reached. Usually set to\n `eos_token_id`.\n' @add_start_docstrings(lowercase_ ) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Any = """rag""" lowerCAmelCase__ : List[Any] = True def __init__(self : Dict , UpperCamelCase : List[Any]=None , UpperCamelCase : str=True , UpperCamelCase : List[Any]=None , UpperCamelCase : List[str]=None , UpperCamelCase : List[Any]=None , UpperCamelCase : str=None , UpperCamelCase : List[Any]=None , UpperCamelCase : str=" / " , UpperCamelCase : Union[str, Any]=" // " , UpperCamelCase : List[str]=5 , UpperCamelCase : Tuple=300 , UpperCamelCase : Optional[int]=768 , UpperCamelCase : int=8 , UpperCamelCase : str="wiki_dpr" , UpperCamelCase : Optional[Any]="train" , UpperCamelCase : Any="compressed" , UpperCamelCase : Dict=None , UpperCamelCase : List[Any]=None , UpperCamelCase : List[Any]=False , UpperCamelCase : str=False , UpperCamelCase : Optional[int]=0.0 , UpperCamelCase : str=True , UpperCamelCase : int=False , UpperCamelCase : Any=False , UpperCamelCase : Any=False , UpperCamelCase : List[str]=True , UpperCamelCase : Optional[int]=None , **UpperCamelCase : List[Any] , ): '''simple docstring''' super().__init__( bos_token_id=UpperCamelCase , pad_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , decoder_start_token_id=UpperCamelCase , forced_eos_token_id=UpperCamelCase , is_encoder_decoder=UpperCamelCase , prefix=UpperCamelCase , vocab_size=UpperCamelCase , **UpperCamelCase , ) assert ( "question_encoder" in kwargs and "generator" in kwargs ), "Config has to be initialized with question_encoder and generator config" lowercase__ = kwargs.pop('''question_encoder''' ) lowercase__ = question_encoder_config.pop('''model_type''' ) lowercase__ = kwargs.pop('''generator''' ) lowercase__ = decoder_config.pop('''model_type''' ) from ..auto.configuration_auto import AutoConfig lowercase__ = AutoConfig.for_model(UpperCamelCase , **UpperCamelCase ) lowercase__ = AutoConfig.for_model(UpperCamelCase , **UpperCamelCase ) lowercase__ = reduce_loss lowercase__ = label_smoothing lowercase__ = exclude_bos_score lowercase__ = do_marginalize lowercase__ = title_sep lowercase__ = doc_sep lowercase__ = n_docs lowercase__ = max_combined_length lowercase__ = dataset lowercase__ = dataset_split lowercase__ = index_name lowercase__ = retrieval_vector_size lowercase__ = retrieval_batch_size lowercase__ = passages_path lowercase__ = index_path lowercase__ = use_dummy_dataset lowercase__ = output_retrieved lowercase__ = do_deduplication lowercase__ = use_cache if self.forced_eos_token_id is None: lowercase__ = getattr(self.generator , '''forced_eos_token_id''' , UpperCamelCase ) @classmethod def UpperCamelCase__ (cls : Optional[int] , UpperCamelCase : PretrainedConfig , UpperCamelCase : PretrainedConfig , **UpperCamelCase : int ): '''simple docstring''' return cls(question_encoder=question_encoder_config.to_dict() , generator=generator_config.to_dict() , **UpperCamelCase ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = copy.deepcopy(self.__dict__ ) lowercase__ = self.question_encoder.to_dict() lowercase__ = self.generator.to_dict() lowercase__ = self.__class__.model_type return output
2
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE__ : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str=1_3 , SCREAMING_SNAKE_CASE__ : Optional[int]=7 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=9_9 , SCREAMING_SNAKE_CASE__ : str=2_4 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6 , SCREAMING_SNAKE_CASE__ : Optional[int]=3_7 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 , SCREAMING_SNAKE_CASE__ : List[str]=1_6 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Tuple=1_0_0_0 , ) -> str: a_ : Optional[Any] = parent a_ : List[str] = batch_size a_ : List[str] = seq_length a_ : str = is_training a_ : str = use_input_mask a_ : int = use_token_type_ids a_ : List[str] = use_labels a_ : Optional[int] = vocab_size a_ : Any = hidden_size a_ : int = num_hidden_layers a_ : List[str] = num_attention_heads a_ : str = intermediate_size a_ : Union[str, Any] = hidden_act a_ : List[str] = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : int = max_position_embeddings a_ : Tuple = type_vocab_size a_ : Optional[Any] = type_sequence_label_size a_ : Tuple = initializer_range a_ : Dict = num_labels a_ : str = scope a_ : Optional[int] = range_bbox def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a_ : int = bbox[i, j, 3] a_ : str = bbox[i, j, 1] a_ : List[str] = t if bbox[i, j, 2] < bbox[i, j, 0]: a_ : Tuple = bbox[i, j, 2] a_ : List[str] = bbox[i, j, 0] a_ : Union[str, Any] = t a_ : List[Any] = None if self.use_input_mask: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) a_ : List[Any] = None if self.use_token_type_ids: a_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : int = None a_ : Tuple = None if self.use_labels: a_ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : Optional[int] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> str: a_ : Any = LiltModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Any = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> int: a_ : Any = self.num_labels a_ : str = LiltForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> str: a_ : Union[str, Any] = LiltForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : List[str] = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , start_positions=SCREAMING_SNAKE_CASE__ , end_positions=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: a_ : int = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : List[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'bbox': bbox, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Union[str, Any] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) snake_case__ : str = ( { '''feature-extraction''': LiltModel, '''question-answering''': LiltForQuestionAnswering, '''text-classification''': LiltForSequenceClassification, '''token-classification''': LiltForTokenClassification, '''zero-shot''': LiltForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ) -> int: return True def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: a_ : str = LiltModelTester(self ) a_ : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: a_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a_ : List[str] = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: a_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: a_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : List[Any] = LiltModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: a_ : List[str] = LiltModel.from_pretrained('SCUT-DLVCLab/lilt-roberta-en-base' ).to(SCREAMING_SNAKE_CASE__ ) a_ : str = torch.tensor([[1, 2]] , device=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): a_ : str = model(input_ids=SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = torch.Size([1, 2, 7_6_8] ) a_ : int = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=SCREAMING_SNAKE_CASE__ , ) self.assertTrue(outputs.last_hidden_state.shape , SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) )
32
0
'''simple docstring''' from __future__ import annotations import math from collections.abc import Callable def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = 100 , ): '''simple docstring''' A : str = x_start A : Optional[Any] = fnc(snake_case__ ) A : List[str] = 0.0 for _ in range(snake_case__ ): # Approximates curve as a sequence of linear lines and sums their length A : Any = (x_end - x_start) / steps + xa A : Dict = fnc(snake_case__ ) length += math.hypot(xa - xa , fxa - fxa ) # Increment step A : Optional[Any] = xa A : Tuple = fxa return length if __name__ == "__main__": def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return math.sin(10 * x ) print('f(x) = sin(10 * x)') print('The length of the curve from x = -10 to x = 10 is:') lowercase : int = 10 while i <= 10_00_00: print(f'''With {i} steps: {line_length(f, -10, 10, i)}''') i *= 10
3
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple=1_3 , SCREAMING_SNAKE_CASE__ : str=7 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=9_9 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_2 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Tuple=3_7 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=5_1_2 , SCREAMING_SNAKE_CASE__ : int=1_6 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> Any: a_ : Tuple = parent a_ : int = batch_size a_ : Tuple = seq_length a_ : List[Any] = is_training a_ : List[str] = use_token_type_ids a_ : Dict = use_labels a_ : Any = vocab_size a_ : List[str] = hidden_size a_ : Tuple = num_hidden_layers a_ : List[Any] = num_attention_heads a_ : Dict = intermediate_size a_ : Any = hidden_act a_ : List[str] = hidden_dropout_prob a_ : Tuple = attention_probs_dropout_prob a_ : Optional[Any] = max_position_embeddings a_ : List[Any] = type_vocab_size a_ : int = type_sequence_label_size a_ : List[Any] = initializer_range a_ : List[str] = num_labels a_ : Union[str, Any] = num_choices a_ : str = scope a_ : Tuple = self.vocab_size - 1 def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: a_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = None if self.use_token_type_ids: a_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : List[Any] = None a_ : Union[str, Any] = None a_ : List[Any] = None if self.use_labels: a_ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) a_ : Union[str, Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) a_ : List[str] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: a_ : Dict = OpenAIGPTModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , head_mask=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: a_ : str = OpenAIGPTLMHeadModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: a_ : int = OpenAIGPTDoubleHeadsModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Any = self.num_labels a_ : Dict = OpenAIGPTForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : Optional[Any] = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : Optional[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Tuple = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) snake_case__ : List[str] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly snake_case__ : Dict = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any=False ) -> List[str]: a_ : str = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": a_ : Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : str = inputs_dict['labels'] a_ : Optional[int] = inputs_dict['labels'] a_ : Optional[int] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: a_ : str = OpenAIGPTModelTester(self ) a_ : int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , n_embd=3_7 ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: a_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: a_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: a_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : str = OpenAIGPTModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: a_ : Dict = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt' ) model.to(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) # the president is a_ : Tuple = [ 4_8_1, 4_7_3_5, 5_4_4, 2_4_6, 9_6_3, 8_7_0, 7_6_2, 2_3_9, 2_4_4, 4_0_4_7_7, 2_4_4, 2_4_9, 7_1_9, 8_8_1, 4_8_7, 5_4_4, 2_4_0, 2_4_4, 6_0_3, 4_8_1, ] # the president is a very good man. " \n " i\'m sure he is, " said the a_ : Dict = model.generate(SCREAMING_SNAKE_CASE__ , do_sample=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(output_ids[0].tolist() , SCREAMING_SNAKE_CASE__ )
32
0
'''simple docstring''' from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class UpperCAmelCase_ ( __lowercase ): def __lt__( self : Optional[int] , UpperCAmelCase__ : List[str] ) -> List[Any]: return self[-1] < other[-1] def __eq__( self : str , UpperCAmelCase__ : List[str] ) -> Tuple: return self[-1] == other[-1] def a_ ( lowerCamelCase : list ): lowerCAmelCase = [] # sort into stacks for element in collection: lowerCAmelCase = Stack([element] ) lowerCAmelCase = bisect_left(lowerCamelCase , lowerCamelCase ) if i != len(lowerCamelCase ): stacks[i].append(lowerCamelCase ) else: stacks.append(lowerCamelCase ) # use a heap-based merge to merge stack efficiently lowerCAmelCase = merge(*(reversed(lowerCamelCase ) for stack in stacks) ) return collection if __name__ == "__main__": __snake_case =input("""Enter numbers separated by a comma:\n""").strip() __snake_case =[int(item) for item in user_input.split(""",""")] print(patience_sort(unsorted))
4
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase_ : Optional[int] = { 'facebook/mask2former-swin-small-coco-instance': ( 'https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase_ : List[str] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = '''mask2former''' snake_case__ : Any = ['''swin'''] snake_case__ : str = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 1_0 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_5_5 , SCREAMING_SNAKE_CASE__ : int = 1_0_0 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : int , ) -> List[Any]: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) a_ : Dict = CONFIG_MAPPING['swin']( image_size=2_2_4 , in_channels=3 , patch_size=4 , embed_dim=9_6 , depths=[2, 2, 1_8, 2] , num_heads=[3, 6, 1_2, 2_4] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): a_ : Any = backbone_config.pop('model_type' ) a_ : Optional[Any] = CONFIG_MAPPING[backbone_model_type] a_ : List[str] = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # 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 Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) a_ : Dict = backbone_config a_ : List[str] = feature_size a_ : List[str] = mask_feature_size a_ : int = hidden_dim a_ : Dict = encoder_feedforward_dim a_ : str = activation_function a_ : List[str] = encoder_layers a_ : List[str] = decoder_layers a_ : Dict = num_attention_heads a_ : str = dropout a_ : Tuple = dim_feedforward a_ : List[str] = pre_norm a_ : Optional[int] = enforce_input_projection a_ : Any = common_stride a_ : Optional[int] = ignore_value a_ : int = num_queries a_ : Tuple = no_object_weight a_ : Dict = class_weight a_ : Optional[int] = mask_weight a_ : Optional[int] = dice_weight a_ : str = train_num_points a_ : List[str] = oversample_ratio a_ : List[Any] = importance_sample_ratio a_ : Any = init_std a_ : Union[str, Any] = init_xavier_std a_ : Union[str, Any] = use_auxiliary_loss a_ : Dict = feature_strides a_ : List[str] = output_auxiliary_logits a_ : Dict = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def SCREAMING_SNAKE_CASE ( cls : str , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict[str, any]: a_ : Optional[int] = copy.deepcopy(self.__dict__ ) a_ : List[Any] = self.backbone_config.to_dict() a_ : Optional[Any] = self.__class__.model_type return output
32
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class lowerCamelCase__ ( lowerCAmelCase): SCREAMING_SNAKE_CASE__ = '''vivit''' def __init__(self , UpperCAmelCase=2_2_4 , UpperCAmelCase=3_2 , UpperCAmelCase=[2, 1_6, 1_6] , UpperCAmelCase=3 , UpperCAmelCase=7_6_8 , UpperCAmelCase=1_2 , UpperCAmelCase=1_2 , UpperCAmelCase=3_0_7_2 , UpperCAmelCase="gelu_fast" , UpperCAmelCase=0.0 , UpperCAmelCase=0.0 , UpperCAmelCase=0.02 , UpperCAmelCase=1e-06 , UpperCAmelCase=True , **UpperCAmelCase , ) -> List[str]: _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 =image_size _lowercase =num_frames _lowercase =tubelet_size _lowercase =num_channels _lowercase =qkv_bias super().__init__(**UpperCAmelCase )
5
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Union[str, Any] = { 'google/switch-base-8': 'https://huggingface.co/google/switch-base-8/blob/main/config.json', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : List[str] = '''switch_transformers''' snake_case__ : Optional[int] = ['''past_key_values'''] snake_case__ : Optional[Any] = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int]=3_2_1_2_8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6_4 , SCREAMING_SNAKE_CASE__ : List[str]=2_0_4_8 , SCREAMING_SNAKE_CASE__ : Dict=6_4 , SCREAMING_SNAKE_CASE__ : List[Any]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3 , SCREAMING_SNAKE_CASE__ : Tuple=1_2 , SCREAMING_SNAKE_CASE__ : Tuple=8 , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.01 , SCREAMING_SNAKE_CASE__ : str="float32" , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_2 , SCREAMING_SNAKE_CASE__ : Dict=1_2_8 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=1E-6 , SCREAMING_SNAKE_CASE__ : Dict=0.001 , SCREAMING_SNAKE_CASE__ : Any=0.001 , SCREAMING_SNAKE_CASE__ : Optional[int]=1.0 , SCREAMING_SNAKE_CASE__ : Any="relu" , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : Optional[int]=1 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: a_ : Optional[int] = vocab_size a_ : List[str] = d_model a_ : Tuple = d_kv a_ : Optional[Any] = d_ff a_ : List[Any] = num_sparse_encoder_layers a_ : Any = num_layers a_ : str = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a_ : List[Any] = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: a_ : Optional[int] = self.num_layers // self.num_sparse_encoder_layers else: a_ : List[Any] = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: a_ : Union[str, Any] = self.num_decoder_layers // self.num_sparse_decoder_layers else: a_ : List[str] = self.num_decoder_layers # HACK: this will create 0 sparse layers a_ : Dict = num_heads a_ : str = num_experts a_ : Any = expert_capacity a_ : List[Any] = router_bias a_ : str = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""" ) a_ : Optional[int] = router_dtype a_ : int = router_ignore_padding_tokens a_ : Any = relative_attention_num_buckets a_ : List[str] = relative_attention_max_distance a_ : Optional[Any] = dropout_rate a_ : Tuple = layer_norm_epsilon a_ : Dict = initializer_factor a_ : Any = feed_forward_proj a_ : Tuple = use_cache a_ : str = add_router_probs a_ : Optional[int] = router_z_loss_coef a_ : List[str] = router_aux_loss_coef a_ : int = self.feed_forward_proj.split('-' ) a_ : int = act_info[-1] a_ : Optional[int] = act_info[0] == 'gated' if len(SCREAMING_SNAKE_CASE__ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE__ ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a_ : Any = 'gelu_new' super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
32
0
from binascii import hexlify from hashlib import shaaaa from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 A : Any = { # 1536-bit 5: { 'prime': int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF', base=1_6, ), 'generator': 2, }, # 2048-bit 1_4: { 'prime': int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AACAA68FFFFFFFFFFFFFFFF', base=1_6, ), 'generator': 2, }, # 3072-bit 1_5: { 'prime': int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF', base=1_6, ), 'generator': 2, }, # 4096-bit 1_6: { 'prime': int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7' + '88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA' + '2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6' + '287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED' + '1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9' + '93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199' + 'FFFFFFFFFFFFFFFF', base=1_6, ), 'generator': 2, }, # 6144-bit 1_7: { 'prime': int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08' + '8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B' + '302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9' + 'A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6' + '49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8' + 'FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C' + '180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718' + '3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D' + '04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D' + 'B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226' + '1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC' + 'E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26' + '99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB' + '04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2' + '233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127' + 'D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492' + '36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406' + 'AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918' + 'DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151' + '2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03' + 'F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F' + 'BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA' + 'CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B' + 'B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632' + '387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E' + '6DCC4024FFFFFFFFFFFFFFFF', base=1_6, ), 'generator': 2, }, # 8192-bit 1_8: { 'prime': int( 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7' + '88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA' + '2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6' + '287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED' + '1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9' + '93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492' + '36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD' + 'F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831' + '179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B' + 'DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF' + '5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6' + 'D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3' + '23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA' + 'CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328' + '06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C' + 'DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE' + '12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4' + '38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300' + '741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568' + '3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9' + '22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B' + '4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A' + '062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36' + '4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1' + 'B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92' + '4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47' + '9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71' + '60C980DD98EDD3DFFFFFFFFFFFFFFFFF', base=1_6, ), 'generator': 2, }, } class __A: def __init__( self , _snake_case = 14 ) -> None: '''simple docstring''' if group not in primes: raise ValueError('''Unsupported Group''' ) __a = primes[group]['''prime'''] __a = primes[group]['''generator'''] __a = int(hexlify(urandom(32 ) ) , base=16 ) def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' return hex(self.__private_key )[2:] def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' __a = pow(self.generator , self.__private_key , self.prime ) return hex(_snake_case )[2:] def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> bool: '''simple docstring''' return ( 2 <= key <= self.prime - 2 and pow(_snake_case , (self.prime - 1) // 2 , self.prime ) == 1 ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> str: '''simple docstring''' __a = int(_snake_case , base=16 ) if not self.is_valid_public_key(_snake_case ): raise ValueError('''Invalid public key''' ) __a = pow(_snake_case , self.__private_key , self.prime ) return shaaaa(str(_snake_case ).encode() ).hexdigest() @staticmethod def SCREAMING_SNAKE_CASE_ ( _snake_case , _snake_case ) -> bool: '''simple docstring''' return ( 2 <= remote_public_key_str <= prime - 2 and pow(_snake_case , (prime - 1) // 2 , _snake_case ) == 1 ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _snake_case , _snake_case , _snake_case = 14 ) -> str: '''simple docstring''' __a = int(_snake_case , base=16 ) __a = int(_snake_case , base=16 ) __a = primes[group]['''prime'''] if not DiffieHellman.is_valid_public_key_static(_snake_case , _snake_case ): raise ValueError('''Invalid public key''' ) __a = pow(_snake_case , _snake_case , _snake_case ) return shaaaa(str(_snake_case ).encode() ).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()
6
# 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. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase_ : Tuple = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyรจ': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmรฅl': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''facebook/nllb-200-distilled-600M''' snake_case__ : Union[str, Any] = ( '''This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ''' '''be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ''' '''which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ''' '''plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.''' ) snake_case__ : Optional[Any] = '''translator''' snake_case__ : Tuple = AutoTokenizer snake_case__ : Union[str, Any] = AutoModelForSeqaSeqLM snake_case__ : Dict = LANGUAGE_CODES snake_case__ : str = ['''text''', '''text''', '''text'''] snake_case__ : Tuple = ['''text'''] def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: if src_lang not in self.lang_to_code: raise ValueError(F"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(F"""{tgt_lang} is not a supported language.""" ) a_ : str = self.lang_to_code[src_lang] a_ : Any = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors='pt' , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Tuple ) -> Any: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
32
0
from manim import * class A ( _UpperCAmelCase ): """simple docstring""" def snake_case__ ( self : Any )-> Optional[int]: '''simple docstring''' A__ = Rectangle(height=0.5,width=0.5 ) A__ = Rectangle(height=0.25,width=0.25 ) A__ = Rectangle(height=0.46,width=0.46 ).set_stroke(width=0 ) A__ = [mem.copy() for i in range(6 )] A__ = [mem.copy() for i in range(6 )] A__ = VGroup(*lowercase_ ).arrange(lowercase_,buff=0 ) A__ = VGroup(*lowercase_ ).arrange(lowercase_,buff=0 ) A__ = VGroup(lowercase_,lowercase_ ).arrange(lowercase_,buff=0 ) A__ = Text('CPU',font_size=2_4 ) A__ = Group(lowercase_,lowercase_ ).arrange(lowercase_,buff=0.5,aligned_edge=lowercase_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(lowercase_ ) A__ = [mem.copy() for i in range(4 )] A__ = VGroup(*lowercase_ ).arrange(lowercase_,buff=0 ) A__ = Text('GPU',font_size=2_4 ) A__ = Group(lowercase_,lowercase_ ).arrange(lowercase_,buff=0.5,aligned_edge=lowercase_ ) gpu.move_to([-1, -1, 0] ) self.add(lowercase_ ) A__ = [mem.copy() for i in range(6 )] A__ = VGroup(*lowercase_ ).arrange(lowercase_,buff=0 ) A__ = Text('Model',font_size=2_4 ) A__ = Group(lowercase_,lowercase_ ).arrange(lowercase_,buff=0.5,aligned_edge=lowercase_ ) model.move_to([3, -1.0, 0] ) self.add(lowercase_ ) A__ = [] A__ = [] A__ = [] for i, rect in enumerate(lowercase_ ): rect.set_stroke(lowercase_ ) A__ = Rectangle(height=0.46 / 4,width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(lowercase_,opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ),buff=0.02,direction=lowercase_ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0],direction=lowercase_,buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1],direction=lowercase_,buff=0.0 ) self.add(lowercase_ ) model_cpu_arr.append(lowercase_ ) self.add(*lowercase_,*lowercase_,*lowercase_ ) A__ = [mem.copy() for i in range(6 )] A__ = VGroup(*lowercase_ ).arrange(lowercase_,buff=0 ) A__ = Text('Loaded Checkpoint',font_size=2_4 ) A__ = Group(lowercase_,lowercase_ ).arrange(lowercase_,buff=0.5,aligned_edge=lowercase_ ) checkpoint.move_to([3, 0.5, 0] ) self.add(lowercase_ ) A__ = [] A__ = [] for i, rect in enumerate(lowercase_ ): A__ = fill.copy().set_fill(lowercase_,opacity=0.7 ) target.move_to(lowercase_ ) ckpt_arr.append(lowercase_ ) A__ = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(lowercase_ ) self.add(*lowercase_,*lowercase_ ) A__ = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) A__ = MarkupText( F'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>โ—</span> Empty Model',font_size=1_8,) key_text.move_to([-5, 2.4, 0] ) self.add(lowercase_,lowercase_ ) A__ = MarkupText( F'<span fgcolor=\'{BLUE}\'>โ—</span> Checkpoint',font_size=1_8,) blue_text.next_to(lowercase_,DOWN * 2.4,aligned_edge=key_text.get_left() ) self.add(lowercase_ ) A__ = MarkupText( F'Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.',font_size=2_4,) step_a.move_to([2, 2, 0] ) A__ = [meta_mem.copy() for i in range(6 )] A__ = [meta_mem.copy() for i in range(6 )] A__ = VGroup(*lowercase_ ).arrange(lowercase_,buff=0 ) A__ = VGroup(*lowercase_ ).arrange(lowercase_,buff=0 ) A__ = VGroup(lowercase_,lowercase_ ).arrange(lowercase_,buff=0 ) A__ = Text('Disk',font_size=2_4 ) A__ = Group(lowercase_,lowercase_ ).arrange(lowercase_,buff=0.5,aligned_edge=lowercase_ ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(lowercase_,run_time=3 ),Write(lowercase_,run_time=1 ),Create(lowercase_,run_time=1 ) ) A__ = [] for i, rect in enumerate(lowercase_ ): A__ = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(lowercase_,run_time=1.5 ) ) self.play(*lowercase_ ) self.play(FadeOut(lowercase_ ) ) A__ = MarkupText(F'Then, the checkpoint is removed from memory\nthrough garbage collection.',font_size=2_4 ) step_a.move_to([2, 2, 0] ) self.play(Write(lowercase_,run_time=3 ) ) self.play( FadeOut(lowercase_,lowercase_,*lowercase_,*lowercase_ ),) self.wait()
7
UpperCAmelCase_ : Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def SCREAMING_SNAKE_CASE_ ( __A : int , __A : int , __A : int ) -> str: """simple docstring""" assert len(str(__A ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: a_ : List[str] = year // 1_00 a_ : Optional[int] = (5 * (century % 4) + 2) % 7 a_ : List[str] = year % 1_00 a_ : str = centurian % 12 a_ : List[str] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 a_ : Any = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) a_ : Any = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
32
0
import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # Initialise PyTorch model snake_case_ = FunnelConfig.from_json_file(SCREAMING_SNAKE_CASE__ ) print(F'''Building PyTorch model from configuration: {config}''' ) snake_case_ = FunnelBaseModel(SCREAMING_SNAKE_CASE__ ) if base_model else FunnelModel(SCREAMING_SNAKE_CASE__ ) # Load weights from tf checkpoint load_tf_weights_in_funnel(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowerCAmelCase_ = 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( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained 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( '''--base_model''', action='''store_true''', help='''Whether you want just the base model (no decoder) or not.''' ) lowerCAmelCase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
8
import math import flax.linen as nn import jax.numpy as jnp def SCREAMING_SNAKE_CASE_ ( __A : jnp.ndarray , __A : int , __A : float = 1 , __A : float = 1 , __A : float = 1.0e4 , __A : bool = False , __A : float = 1.0 , ) -> jnp.ndarray: """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F"""Embedding dimension {embedding_dim} should be even""" a_ : int = float(embedding_dim // 2 ) a_ : str = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) a_ : Optional[int] = min_timescale * jnp.exp(jnp.arange(__A , dtype=jnp.floataa ) * -log_timescale_increment ) a_ : Optional[int] = jnp.expand_dims(__A , 1 ) * jnp.expand_dims(__A , 0 ) # scale embeddings a_ : str = scale * emb if flip_sin_to_cos: a_ : str = jnp.concatenate([jnp.cos(__A ), jnp.sin(__A )] , axis=1 ) else: a_ : Any = jnp.concatenate([jnp.sin(__A ), jnp.cos(__A )] , axis=1 ) a_ : Optional[int] = jnp.reshape(__A , [jnp.shape(__A )[0], embedding_dim] ) return signal class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Optional[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_1' )(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = nn.silu(SCREAMING_SNAKE_CASE__ ) a_ : str = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_2' )(SCREAMING_SNAKE_CASE__ ) return temb class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : bool = False snake_case__ : float = 1 @nn.compact def __call__( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Tuple: return get_sinusoidal_embeddings( SCREAMING_SNAKE_CASE__ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
32
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCAmelCase : Dict ={ 'configuration_albert': ['ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AlbertConfig', 'AlbertOnnxConfig'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : List[str] =['AlbertTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Any =['AlbertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Optional[Any] =[ 'ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'AlbertForMaskedLM', 'AlbertForMultipleChoice', 'AlbertForPreTraining', 'AlbertForQuestionAnswering', 'AlbertForSequenceClassification', 'AlbertForTokenClassification', 'AlbertModel', 'AlbertPreTrainedModel', 'load_tf_weights_in_albert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Any =[ 'TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFAlbertForMaskedLM', 'TFAlbertForMultipleChoice', 'TFAlbertForPreTraining', 'TFAlbertForQuestionAnswering', 'TFAlbertForSequenceClassification', 'TFAlbertForTokenClassification', 'TFAlbertMainLayer', 'TFAlbertModel', 'TFAlbertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Optional[int] =[ 'FlaxAlbertForMaskedLM', 'FlaxAlbertForMultipleChoice', 'FlaxAlbertForPreTraining', 'FlaxAlbertForQuestionAnswering', 'FlaxAlbertForSequenceClassification', 'FlaxAlbertForTokenClassification', 'FlaxAlbertModel', 'FlaxAlbertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert import AlbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert_fast import AlbertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_albert import ( ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, AlbertPreTrainedModel, load_tf_weights_in_albert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_albert import ( TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFAlbertForMaskedLM, TFAlbertForMultipleChoice, TFAlbertForPreTraining, TFAlbertForQuestionAnswering, TFAlbertForSequenceClassification, TFAlbertForTokenClassification, TFAlbertMainLayer, TFAlbertModel, TFAlbertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, FlaxAlbertPreTrainedModel, ) else: import sys __lowerCAmelCase : Tuple =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
9
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) UpperCAmelCase_ : str = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCAmelCase_ : Optional[Any] = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) UpperCAmelCase_ : int = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) UpperCAmelCase_ : Union[str, Any] = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) UpperCAmelCase_ : Union[str, Any] = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) UpperCAmelCase_ : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase_ : Dict = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase_ : Dict = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase_ : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase_ : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase_ : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[Any] = FLAX_MODEL_MAPPING UpperCAmelCase_ : Tuple = auto_class_update(FlaxAutoModel) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Any = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[Any] = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase_ : Union[str, Any] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase_ : Optional[int] = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase_ : str = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[str] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase_ : Tuple = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Dict = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase_ : int = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[int] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase_ : Dict = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase_ : str = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[Any] = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase_ : Tuple = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[int] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase_ : Union[str, Any] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
32
0
from __future__ import annotations from typing import TypedDict class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = 42 def lowerCAmelCase_ ( __a ) -> list[str]: """simple docstring""" if not isinstance(__a , __a ): raise TypeError("The parameter s type must be str." ) return [s[i:] + s[:i] for i in range(len(__a ) )] def lowerCAmelCase_ ( __a ) -> BWTTransformDict: """simple docstring""" if not isinstance(__a , __a ): raise TypeError("The parameter s type must be str." ) if not s: raise ValueError("The parameter s must not be empty." ) lowerCamelCase__: int =all_rotations(__a ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation lowerCamelCase__: BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(__a ), } return response def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" if not isinstance(__a , __a ): raise TypeError("The parameter bwt_string type must be str." ) if not bwt_string: raise ValueError("The parameter bwt_string must not be empty." ) try: lowerCamelCase__: Tuple =int(__a ) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0." ) if idx_original_string >= len(__a ): raise ValueError( "The parameter idx_original_string must be lower than" " len(bwt_string)." ) lowerCamelCase__: List[str] =[""] * len(__a ) for _ in range(len(__a ) ): for i in range(len(__a ) ): lowerCamelCase__: List[str] =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": __A = "Provide a string that I will generate its BWT transform: " __A = input(entry_msg).strip() __A = bwt_transform(s) print( f'Burrows Wheeler transform for string \'{s}\' results ' f'in \'{result["bwt_string"]}\'' ) __A = reverse_bwt(result["bwt_string"], result["idx_original_string"]) print( f'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ' f'we get original string \'{original_string}\'' )
10
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): snake_case__ : Any = GPTSanJapaneseTokenizer snake_case__ : Tuple = False snake_case__ : str = {'''do_clean_text''': False, '''add_prefix_space''': False} def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: super().setUp() # fmt: off a_ : Union[str, Any] = ['ใ“ใ‚“', 'ใ“ใ‚“ใซ', 'ใซใกใฏ', 'ใฐใ‚“ใฏ', 'ไธ–็•Œ,ใ”บ็•Œ', 'ใ€', 'ใ€‚', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on a_ : int = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # ๐Ÿ˜€ a_ : List[Any] = {'unk_token': '<unk>'} a_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) a_ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE__ ) ) def SCREAMING_SNAKE_CASE ( self : List[str] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> int: kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> int: a_ : Optional[int] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : List[str] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Dict: a_ , a_ : Union[str, Any] = self.get_input_output_texts(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) a_ : Dict = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) return text, ids def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: a_ : List[str] = self.get_tokenizer() # Testing tokenization a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ€€ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚' a_ : Optional[int] = ['ใ“ใ‚“', 'ใซใกใฏ', 'ใ€', 'ไธ–็•Œ', 'ใ€‚', '<SP>', 'ใ“ใ‚“', 'ใฐใ‚“ใฏ', 'ใ€', 'ใ”บ็•Œ', 'ใ€‚'] a_ : Dict = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids without special tokens a_ : Tuple = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] a_ : List[Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids with special tokens a_ : int = tokens + [tokenizer.unk_token] a_ : int = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9] a_ : Tuple = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: a_ : Union[str, Any] = self.get_tokenizer() # Testing tokenization a_ : Dict = 'ใ“ใ‚“ใซใกใฏใ€<|bagoftoken|>ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€<|bagoftoken|>ใ”บ็•Œใ€‚' a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚' a_ : Any = tokenizer.encode(SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : str ) -> Dict: a_ : Tuple = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' a_ : int = 'ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : Dict = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' a_ : Optional[int] = tokenizer.encode(prefix_text + input_text ) a_ : Any = tokenizer.encode('' , prefix_text=prefix_text + input_text ) a_ : Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) a_ : str = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: a_ : Tuple = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization a_ : str = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' a_ : List[str] = 'ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : str = len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 a_ : Tuple = len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 a_ : Optional[Any] = [1] + [0] * (len_prefix + len_text + 1) a_ : Optional[Any] = [1] * (len_prefix + len_text + 1) + [0] a_ : Tuple = [1] + [1] * (len_prefix) + [0] * (len_text + 1) a_ : List[str] = tokenizer(prefix_text + input_text ).token_type_ids a_ : Union[str, Any] = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids a_ : Any = tokenizer(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: a_ : str = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) a_ : Optional[int] = tokenizer.encode('ใ‚ใƒณใ„ใƒฏ' ) a_ : Dict = tokenizer.encode('' , prefix_text='ใ‚ใƒณใ„ใƒฏ' ) a_ : Dict = tokenizer.encode('ใ„ใƒฏ' , prefix_text='ใ‚ใƒณ' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: a_ : List[str] = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) a_ : Optional[Any] = [['ๆญฆ็”ฐไฟก็Ž„', 'ใฏใ€'], ['็น”็”ฐไฟก้•ท', 'ใฎ้…ไธ‹ใฎใ€']] a_ : List[str] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) a_ : Dict = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) # fmt: off a_ : List[Any] = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]] a_ : Any = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] a_ : List[Any] = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: # tokenizer has no padding token pass
32
0
from math import factorial def _UpperCAmelCase (UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : float ): if successes > trials: raise ValueError("successes must be lower or equal to trials" ) if trials < 0 or successes < 0: raise ValueError("the function is defined for non-negative integers" ) if not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError("the function is defined for non-negative integers" ) if not 0 < prob < 1: raise ValueError("prob has to be in range of 1 - 0" ) _A : Optional[Any] = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! _A : Dict = float(factorial(UpperCamelCase__ ) ) coefficient /= factorial(UpperCamelCase__ ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
11
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, logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Union[str, Any] = ['''pixel_values'''] def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, int]] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 2_5_5 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) a_ : str = size if size is not None else {'shortest_edge': 2_5_6} a_ : Any = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) a_ : Dict = crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4} a_ : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE__ ) a_ : List[str] = do_resize a_ : Dict = size a_ : Optional[Any] = resample a_ : Optional[int] = do_center_crop a_ : Dict = crop_size a_ : int = do_rescale a_ : int = rescale_factor a_ : Tuple = do_normalize a_ : int = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN a_ : Tuple = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> np.ndarray: a_ : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) a_ : Tuple = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=size['shortest_edge'] , default_to_square=SCREAMING_SNAKE_CASE__ ) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> np.ndarray: a_ : str = get_size_dict(SCREAMING_SNAKE_CASE__ ) return center_crop(SCREAMING_SNAKE_CASE__ , size=(size['height'], size['width']) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> np.ndarray: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[float] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> Union[str, Any]: a_ : List[str] = do_resize if do_resize is not None else self.do_resize a_ : Dict = size if size is not None else self.size a_ : Dict = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = resample if resample is not None else self.resample a_ : List[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop a_ : int = crop_size if crop_size is not None else self.crop_size a_ : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE__ ) a_ : Dict = do_rescale if do_rescale is not None else self.do_rescale a_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor a_ : Any = do_normalize if do_normalize is not None else self.do_normalize a_ : str = image_mean if image_mean is not None else self.image_mean a_ : Dict = image_std if image_std is not None else self.image_std a_ : Optional[int] = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. a_ : Any = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: a_ : str = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_center_crop: a_ : int = [self.center_crop(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: a_ : Optional[Any] = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: a_ : List[Any] = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] a_ : Dict = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] a_ : Tuple = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
32
0
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient UpperCAmelCase_ = WebClient(token=os.environ['CI_SLACK_BOT_TOKEN']) def lowerCamelCase__ ( A__ : Union[str, Any] ): '''simple docstring''' __lowerCamelCase = test_results.split(""" """ ) __lowerCamelCase = 0 __lowerCamelCase = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. __lowerCamelCase = expressions[-2] if """=""" in expressions[-1] else expressions[-1] for i, expression in enumerate(A__ ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def lowerCamelCase__ ( A__ : Optional[int] ): '''simple docstring''' __lowerCamelCase = {} __lowerCamelCase = None __lowerCamelCase = False for line in failures_short_lines.split("""\n""" ): if re.search(R"""_ \[doctest\]""" , A__ ): __lowerCamelCase = True __lowerCamelCase = line.split(""" """ )[2] elif in_error and not line.split(""" """ )[0].isdigit(): __lowerCamelCase = line __lowerCamelCase = False return failures class lowerCamelCase__: def __init__( self: int , UpperCamelCase_: str , UpperCamelCase_: Dict ): __lowerCamelCase = title __lowerCamelCase = doc_test_results["""time_spent"""].split(""",""" )[0] __lowerCamelCase = doc_test_results["""success"""] __lowerCamelCase = doc_test_results["""failures"""] __lowerCamelCase = self.n_success + self.n_failures # Failures and success of the modeling tests __lowerCamelCase = doc_test_results @property def lowerCAmelCase__ ( self: List[str] ): __lowerCamelCase = [self._time_spent] __lowerCamelCase = 0 for time in time_spent: __lowerCamelCase = time.split(""":""" ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(UpperCamelCase_ ) == 1: __lowerCamelCase = [0, 0, time_parts[0]] __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return F'{int(UpperCamelCase_ )}h{int(UpperCamelCase_ )}m{int(UpperCamelCase_ )}s' @property def lowerCAmelCase__ ( self: List[str] ): return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def lowerCAmelCase__ ( self: Union[str, Any] ): return { "type": "section", "text": { "type": "plain_text", "text": F'๐ŸŒž There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def lowerCAmelCase__ ( self: Optional[int] ): return { "type": "section", "text": { "type": "plain_text", "text": ( F'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' F' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": F'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def lowerCAmelCase__ ( self: str ): __lowerCamelCase = 40 __lowerCamelCase = {k: v["""failed"""] for k, v in doc_test_results.items() if isinstance(UpperCamelCase_ , UpperCamelCase_ )} __lowerCamelCase = """""" for category, failures in category_failures.items(): if len(UpperCamelCase_ ) == 0: continue if report != "": report += "\n\n" report += F'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(UpperCamelCase_ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": F'The following examples had failures:\n\n\n{report}\n', }, } @property def lowerCAmelCase__ ( self: List[str] ): __lowerCamelCase = [self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(UpperCamelCase_ ) @staticmethod def lowerCAmelCase__ ( ): __lowerCamelCase = [ { """type""": """section""", """text""": { """type""": """plain_text""", """text""": """There was an issue running the tests.""", }, """accessory""": { """type""": """button""", """text""": {"""type""": """plain_text""", """text""": """Check Action results""", """emoji""": True}, """url""": F'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print("""Sending the following payload""" ) print(json.dumps({"""blocks""": json.loads(UpperCamelCase_ )} ) ) client.chat_postMessage( channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""] , text="""There was an issue running the tests.""" , blocks=UpperCamelCase_ , ) def lowerCAmelCase__ ( self: int ): print("""Sending the following payload""" ) print(json.dumps({"""blocks""": json.loads(self.payload )} ) ) __lowerCamelCase = F'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else """All tests passed.""" __lowerCamelCase = client.chat_postMessage( channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""] , blocks=self.payload , text=UpperCamelCase_ , ) def lowerCAmelCase__ ( self: List[Any] , UpperCamelCase_: List[str] , UpperCamelCase_: Tuple , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Tuple ): __lowerCamelCase = """""" for key, value in failures.items(): __lowerCamelCase = value[:2_00] + """ [Truncated]""" if len(UpperCamelCase_ ) > 2_50 else value failures_text += F'*{key}*\n_{value}_\n\n' __lowerCamelCase = job_name __lowerCamelCase = {"""type""": """section""", """text""": {"""type""": """mrkdwn""", """text""": text}} if job_link is not None: __lowerCamelCase = { """type""": """button""", """text""": {"""type""": """plain_text""", """text""": """GitHub Action job""", """emoji""": True}, """url""": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def lowerCAmelCase__ ( self: List[Any] ): if self.thread_ts is None: raise ValueError("""Can only post reply if a post has been made.""" ) __lowerCamelCase = self.doc_test_results.pop("""job_link""" ) self.doc_test_results.pop("""failures""" ) self.doc_test_results.pop("""success""" ) self.doc_test_results.pop("""time_spent""" ) __lowerCamelCase = sorted(self.doc_test_results.items() , key=lambda UpperCamelCase_ : t[0] ) for job, job_result in sorted_dict: if len(job_result["""failures"""] ): __lowerCamelCase = F'*Num failures* :{len(job_result["failed"] )} \n' __lowerCamelCase = job_result["""failures"""] __lowerCamelCase = self.get_reply_blocks(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , text=UpperCamelCase_ ) print("""Sending the following reply""" ) print(json.dumps({"""blocks""": blocks} ) ) client.chat_postMessage( channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""] , text=F'Results for {job}' , blocks=UpperCamelCase_ , thread_ts=self.thread_ts["""ts"""] , ) time.sleep(1 ) def lowerCamelCase__ ( ): '''simple docstring''' __lowerCamelCase = os.environ["""GITHUB_RUN_ID"""] __lowerCamelCase = f'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' __lowerCamelCase = requests.get(A__ ).json() __lowerCamelCase = {} try: jobs.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) __lowerCamelCase = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(A__ ): __lowerCamelCase = requests.get(url + f'&page={i + 2}' ).json() jobs.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return jobs except Exception as e: print("""Unknown error, could not fetch links.""" , A__ ) return {} def lowerCamelCase__ ( A__ : str ): '''simple docstring''' __lowerCamelCase = {} if os.path.exists(A__ ): __lowerCamelCase = os.listdir(A__ ) for file in files: try: with open(os.path.join(A__ , A__ ) , encoding="""utf-8""" ) as f: __lowerCamelCase = f.read() except UnicodeDecodeError as e: raise ValueError(f'Could not open {os.path.join(A__ , A__ )}.' ) from e return _artifact def lowerCamelCase__ ( ): '''simple docstring''' class lowerCamelCase__: def __init__( self: Optional[Any] , UpperCamelCase_: str ): __lowerCamelCase = name __lowerCamelCase = [] def __str__( self: List[str] ): return self.name def lowerCAmelCase__ ( self: List[str] , UpperCamelCase_: str ): self.paths.append({"""name""": self.name, """path""": path} ) __lowerCamelCase = {} __lowerCamelCase = filter(os.path.isdir , os.listdir() ) for directory in directories: __lowerCamelCase = directory if artifact_name not in _available_artifacts: __lowerCamelCase = Artifact(A__ ) _available_artifacts[artifact_name].add_path(A__ ) return _available_artifacts if __name__ == "__main__": UpperCAmelCase_ = get_job_links() UpperCAmelCase_ = retrieve_available_artifacts() UpperCAmelCase_ = collections.OrderedDict( [ ('*.py', 'API Examples'), ('*.md', 'MD Examples'), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' UpperCAmelCase_ = { v: { 'failed': [], 'failures': {}, } for v in docs.values() } # Link to the GitHub Action job UpperCAmelCase_ = github_actions_job_links.get('run_doctests') UpperCAmelCase_ = available_artifacts['doc_tests_gpu_test_reports'].paths[0] UpperCAmelCase_ = retrieve_artifact(artifact_path['name']) if "stats" in artifact: UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = handle_test_results(artifact['stats']) UpperCAmelCase_ = failed UpperCAmelCase_ = success UpperCAmelCase_ = time_spent[1:-1] + ', ' UpperCAmelCase_ = extract_first_line_failure(artifact['failures_short']) for line in artifact["summary_short"].split('\n'): if re.search('FAILED', line): UpperCAmelCase_ = line.replace('FAILED ', '') UpperCAmelCase_ = line.split()[0].replace('\n', '') if "::" in line: UpperCAmelCase_ , UpperCAmelCase_ = line.split('::') else: UpperCAmelCase_ , UpperCAmelCase_ = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): UpperCAmelCase_ = docs[file_regex] doc_test_results[category]["failed"].append(test) UpperCAmelCase_ = all_failures[test] if test in all_failures else 'N/A' UpperCAmelCase_ = failure break UpperCAmelCase_ = Message('๐Ÿค— Results of the doc tests.', doc_test_results) message.post() message.post_reply()
12
def SCREAMING_SNAKE_CASE_ ( __A : list[int] , __A : str ) -> list[int]: """simple docstring""" a_ : Any = int(__A ) # Initialize Result a_ : Tuple = [] # Traverse through all denomination for denomination in reversed(__A ): # Find denominations while int(__A ) >= int(__A ): total_value -= int(__A ) answer.append(__A ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = [] UpperCAmelCase_ : Union[str, Any] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase_ : List[Any] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(F'Denomination {i}: ').strip())) UpperCAmelCase_ : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase_ : List[Any] = [1, 2, 5, 10, 20, 50, 100, 500, 2000] UpperCAmelCase_ : str = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(F'Following is minimal change for {value}: ') UpperCAmelCase_ : Optional[Any] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
32
0
import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): # Initialise PyTorch model SCREAMING_SNAKE_CASE_: Tuple = FunnelConfig.from_json_file(_UpperCAmelCase ) print(f"Building PyTorch model from configuration: {config}" ) SCREAMING_SNAKE_CASE_: Optional[Any] = FunnelBaseModel(_UpperCAmelCase ) if base_model else FunnelModel(_UpperCAmelCase ) # Load weights from tf checkpoint load_tf_weights_in_funnel(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , _UpperCAmelCase ) if __name__ == "__main__": lowerCAmelCase : Union[str, 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( """--config_file""", default=None, type=str, required=True, help="""The config json file corresponding to the pre-trained 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( """--base_model""", action="""store_true""", help="""Whether you want just the base model (no decoder) or not.""" ) lowerCAmelCase : Optional[int] = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
13
import flax.linen as nn import jax import jax.numpy as jnp class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : str ) -> int: a_ : Dict = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: a_ , a_ , a_ , a_ : Union[str, Any] = hidden_states.shape a_ : List[str] = jax.image.resize( SCREAMING_SNAKE_CASE__ , shape=(batch, height * 2, width * 2, channels) , method='nearest' , ) a_ : Any = self.conv(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: a_ : Optional[int] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]: # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim # hidden_states = jnp.pad(hidden_states, pad_width=pad) a_ : str = self.conv(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : int = None snake_case__ : float = 0.0 snake_case__ : bool = None snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: a_ : List[str] = self.in_channels if self.out_channels is None else self.out_channels a_ : Optional[int] = nn.GroupNorm(num_groups=3_2 , epsilon=1E-5 ) a_ : Any = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) a_ : Optional[int] = nn.Dense(SCREAMING_SNAKE_CASE__ , dtype=self.dtype ) a_ : Union[str, Any] = nn.GroupNorm(num_groups=3_2 , epsilon=1E-5 ) a_ : int = nn.Dropout(self.dropout_prob ) a_ : Optional[Any] = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) a_ : List[str] = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut a_ : List[Any] = None if use_nin_shortcut: a_ : Union[str, Any] = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(1, 1) , strides=(1, 1) , padding='VALID' , dtype=self.dtype , ) def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any]=True ) -> int: a_ : List[Any] = hidden_states a_ : Any = self.norma(SCREAMING_SNAKE_CASE__ ) a_ : Any = nn.swish(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = self.conva(SCREAMING_SNAKE_CASE__ ) a_ : int = self.time_emb_proj(nn.swish(SCREAMING_SNAKE_CASE__ ) ) a_ : List[str] = jnp.expand_dims(jnp.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , 1 ) a_ : Optional[int] = hidden_states + temb a_ : List[str] = self.norma(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = nn.swish(SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.dropout(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = self.conva(SCREAMING_SNAKE_CASE__ ) if self.conv_shortcut is not None: a_ : List[str] = self.conv_shortcut(SCREAMING_SNAKE_CASE__ ) return hidden_states + residual
32
0
_lowerCamelCase : int = { """a""": """AAAAA""", """b""": """AAAAB""", """c""": """AAABA""", """d""": """AAABB""", """e""": """AABAA""", """f""": """AABAB""", """g""": """AABBA""", """h""": """AABBB""", """i""": """ABAAA""", """j""": """BBBAA""", """k""": """ABAAB""", """l""": """ABABA""", """m""": """ABABB""", """n""": """ABBAA""", """o""": """ABBAB""", """p""": """ABBBA""", """q""": """ABBBB""", """r""": """BAAAA""", """s""": """BAAAB""", """t""": """BAABA""", """u""": """BAABB""", """v""": """BBBAB""", """w""": """BABAA""", """x""": """BABAB""", """y""": """BABBA""", """z""": """BABBB""", """ """: """ """, } _lowerCamelCase : Union[str, Any] = {value: key for key, value in encode_dict.items()} def SCREAMING_SNAKE_CASE ( lowercase_ ) -> str: """simple docstring""" A__ = '''''' for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception('''encode() accepts only letters of the alphabet and spaces''' ) return encoded def SCREAMING_SNAKE_CASE ( lowercase_ ) -> str: """simple docstring""" if set(lowercase_ ) - {"A", "B", " "} != set(): raise Exception('''decode() accepts only \'A\', \'B\' and spaces''' ) A__ = '''''' for word in coded.split(): while len(lowercase_ ) != 0: decoded += decode_dict[word[:5]] A__ = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
14
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. UpperCAmelCase_ : Dict = {'LayoutLMv2Config', 'LayoutLMv3Config'} @is_pipeline_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): snake_case__ : List[str] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING snake_case__ : Optional[Any] = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: snake_case__ : str = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: snake_case__ : List[Any] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: a_ : List[Any] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' ) a_ : int = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) a_ : Tuple = text_classifier('This is great !' , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}] ) a_ : List[str] = text_classifier(['This is great !', 'This is bad'] , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], ] , ) a_ : Tuple = text_classifier('This is great !' , top_k=1 ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) # Legacy behavior a_ : Union[str, Any] = text_classifier('This is great !' , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) a_ : List[str] = text_classifier('This is great !' , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}]] ) a_ : int = text_classifier(['This is great !', 'Something else'] , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], ] , ) a_ : str = text_classifier(['This is great !', 'Something else'] , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ {'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_0', 'score': 0.504}, ] , ) @require_torch def SCREAMING_SNAKE_CASE ( self : int ) -> Dict: import torch a_ : List[Any] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' , device=torch.device('cpu' ) , ) a_ : Any = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) @require_tf def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: a_ : List[str] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='tf' ) a_ : Optional[int] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) @slow @require_torch def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: a_ : List[str] = pipeline('text-classification' ) a_ : Dict = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 1.0}] ) a_ : Union[str, Any] = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'NEGATIVE', 'score': 1.0}] ) a_ : Tuple = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 0.988}] ) @slow @require_tf def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: a_ : Dict = pipeline('text-classification' , framework='tf' ) a_ : Optional[Any] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 1.0}] ) a_ : int = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'NEGATIVE', 'score': 1.0}] ) a_ : Optional[int] = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 0.988}] ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: a_ : Optional[Any] = TextClassificationPipeline(model=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ ) return text_classifier, ["HuggingFace is in", "This is another test"] def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: a_ : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 a_ : Union[str, Any] = 'HuggingFace is in' a_ : int = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) a_ : Union[str, Any] = ['HuggingFace is in ', 'Paris is in France'] a_ : int = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}, {'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) self.assertTrue(outputs[1]['label'] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format a_ : List[Any] = text_classifier(SCREAMING_SNAKE_CASE__ , top_k=SCREAMING_SNAKE_CASE__ ) a_ : Dict = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [[{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] * N, [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] * N] , ) a_ : int = {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'} a_ : Optional[int] = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , {'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )} , ) self.assertTrue(outputs['label'] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. a_ : Any = [['HuggingFace is in ', 'Paris is in France']] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): text_classifier(SCREAMING_SNAKE_CASE__ ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility a_ : Tuple = text_classifier([[['HuggingFace is in ', 'Paris is in France']]] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )
32
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 UpperCAmelCase ( a_ , a_ , a_=1E-12 ) -> List[str]: """simple docstring""" __A = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(a_ , axis=1 ) , a_min=a_ ) ).T __A = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(a_ , axis=1 ) , a_min=a_ ) ).T return jnp.matmul(a_ , norm_emb_a.T ) class UpperCAmelCase ( nn.Module ): '''simple docstring''' snake_case_ = 42 snake_case_ = jnp.floataa def UpperCamelCase_ ( self : List[str] ): __A = FlaxCLIPVisionModule(self.config.vision_config ) __A = nn.Dense(self.config.projection_dim ,use_bias=A ,dtype=self.dtype ) __A = self.param("concept_embeds" ,jax.nn.initializers.ones ,(17, self.config.projection_dim) ) __A = self.param( "special_care_embeds" ,jax.nn.initializers.ones ,(3, self.config.projection_dim) ) __A = self.param("concept_embeds_weights" ,jax.nn.initializers.ones ,(17,) ) __A = self.param("special_care_embeds_weights" ,jax.nn.initializers.ones ,(3,) ) def __call__( self : Tuple ,A : Any ): __A = self.vision_model(A )[1] __A = self.visual_projection(A ) __A = jax_cosine_distance(A ,self.special_care_embeds ) __A = jax_cosine_distance(A ,self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs __A = 0.0 __A = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment __A = jnp.round(A ,3 ) __A = jnp.any(special_scores > 0 ,axis=1 ,keepdims=A ) # Use a lower threshold if an image has any special care concept __A = is_special_care * 0.01 __A = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment __A = jnp.round(A ,3 ) __A = jnp.any(concept_scores > 0 ,axis=1 ) return has_nsfw_concepts class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = CLIPConfig snake_case_ = "clip_input" snake_case_ = FlaxStableDiffusionSafetyCheckerModule def __init__( self : int ,A : CLIPConfig ,A : Optional[Tuple] = None ,A : int = 0 ,A : jnp.dtype = jnp.floataa ,A : bool = True ,**A : Tuple ,): if input_shape is None: __A = (1, 2_24, 2_24, 3) __A = self.module_class(config=A ,dtype=A ,**A ) super().__init__(A ,A ,input_shape=A ,seed=A ,dtype=A ,_do_init=_do_init ) def UpperCamelCase_ ( self : int ,A : jax.random.KeyArray ,A : Tuple ,A : FrozenDict = None ): # init input tensor __A = jax.random.normal(A ,A ) __A , __A = jax.random.split(A ) __A = {"params": params_rng, "dropout": dropout_rng} __A = self.module.init(A ,A )["params"] return random_params def __call__( self : Tuple ,A : Dict ,A : dict = None ,): __A = jnp.transpose(A ,(0, 2, 3, 1) ) return self.module.apply( {"params": params or self.params} ,jnp.array(A ,dtype=jnp.floataa ) ,rngs={} ,)
15
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : str = 'T5Config' def SCREAMING_SNAKE_CASE_ ( __A : jnp.array , __A : int , __A : int ) -> jnp.ndarray: """simple docstring""" a_ : Dict = jnp.zeros_like(__A ) a_ : Dict = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) a_ : str = shifted_input_ids.at[:, 0].set(__A ) a_ : int = jnp.where(shifted_input_ids == -1_00 , __A , __A ) return shifted_input_ids class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[Any] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[str] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = '''mt5''' snake_case__ : Union[str, Any] = MTaConfig
32
0
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = {'vocab_file': 'spiece.model'} lowerCAmelCase_ = { 'vocab_file': { 'TsinghuaAI/CPM-Generate': 'https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model', } } class __A ( A_ ): '''simple docstring''' def __init__( self : str ,_snake_case : Tuple ,_snake_case : int=False ,_snake_case : Union[str, Any]=True ,_snake_case : List[Any]=False ,_snake_case : Dict="<s>" ,_snake_case : Optional[Any]="</s>" ,_snake_case : List[str]="<unk>" ,_snake_case : int="<sep>" ,_snake_case : List[Any]="<pad>" ,_snake_case : Union[str, Any]="<cls>" ,_snake_case : str="<mask>" ,_snake_case : int=["<eop>", "<eod>"] ,_snake_case : Optional[Dict[str, Any]] = None ,**_snake_case : Optional[int] ,) -> None: """simple docstring""" lowercase__ : Union[str, Any] = AddedToken(_snake_case ,lstrip=_snake_case ,rstrip=_snake_case ) if isinstance(_snake_case ,_snake_case ) else mask_token lowercase__ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_snake_case ,remove_space=_snake_case ,keep_accents=_snake_case ,bos_token=_snake_case ,eos_token=_snake_case ,unk_token=_snake_case ,sep_token=_snake_case ,pad_token=_snake_case ,cls_token=_snake_case ,mask_token=_snake_case ,additional_special_tokens=_snake_case ,sp_model_kwargs=self.sp_model_kwargs ,**_snake_case ,) lowercase__ : Any = 3 lowercase__ : Union[str, Any] = do_lower_case lowercase__ : Optional[int] = remove_space lowercase__ : Optional[Any] = keep_accents lowercase__ : List[str] = vocab_file lowercase__ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_snake_case ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( '''You need to install jieba to use CpmTokenizer or CpmTokenizerFast. ''' '''See https://pypi.org/project/jieba/ for installation.''' ) lowercase__ : Union[str, Any] = jieba lowercase__ : Tuple = str.maketrans(''' \n''' ,'''\u2582\u2583''' ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def UpperCAmelCase ( self : Tuple ) -> Optional[Any]: """simple docstring""" return len(self.sp_model ) def UpperCAmelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" lowercase__ : List[str] = {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 : Optional[int] ) -> Tuple: """simple docstring""" lowercase__ : Any = self.__dict__.copy() lowercase__ : Optional[int] = None return state def __setstate__( self : List[str] ,_snake_case : int ) -> Union[str, Any]: """simple docstring""" lowercase__ : str = d # for backward compatibility if not hasattr(self ,'''sp_model_kwargs''' ): lowercase__ : Dict = {} lowercase__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCAmelCase ( self : List[str] ,_snake_case : Optional[Any] ) -> Optional[Any]: """simple docstring""" if self.remove_space: lowercase__ : str = ''' '''.join(inputs.strip().split() ) else: lowercase__ : List[str] = inputs lowercase__ : Tuple = outputs.replace('''``''' ,'''"''' ).replace('''\'\'''' ,'''"''' ) if not self.keep_accents: lowercase__ : Tuple = unicodedata.normalize('''NFKD''' ,_snake_case ) lowercase__ : List[str] = ''''''.join([c for c in outputs if not unicodedata.combining(_snake_case )] ) if self.do_lower_case: lowercase__ : List[str] = outputs.lower() return outputs def UpperCAmelCase ( self : int ,_snake_case : str ) -> List[str]: """simple docstring""" lowercase__ : Tuple = self.preprocess_text(_snake_case ) lowercase__ : int = self.sp_model.encode(_snake_case ,out_type=_snake_case ) lowercase__ : List[Any] = [] for piece in pieces: if len(_snake_case ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): lowercase__ : List[str] = self.sp_model.EncodeAsPieces(piece[:-1].replace(_snake_case ,'''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowercase__ : int = cur_pieces[1:] else: lowercase__ : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_snake_case ) else: new_pieces.append(_snake_case ) return new_pieces def UpperCAmelCase ( self : List[str] ,_snake_case : List[Any] ) -> Union[str, Any]: """simple docstring""" return self.sp_model.PieceToId(_snake_case ) def UpperCAmelCase ( self : List[Any] ,_snake_case : Optional[Any] ) -> Tuple: """simple docstring""" return self.sp_model.IdToPiece(_snake_case ) def UpperCAmelCase ( self : Dict ,_snake_case : int ) -> Tuple: """simple docstring""" lowercase__ : List[Any] = ''''''.join(_snake_case ).replace(_snake_case ,''' ''' ).strip() return out_string def UpperCAmelCase ( self : Tuple ,_snake_case : List[int] ,_snake_case : Optional[List[int]] = None ) -> List[int]: """simple docstring""" lowercase__ : Tuple = [self.sep_token_id] lowercase__ : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def UpperCAmelCase ( self : List[str] ,_snake_case : List[int] ,_snake_case : Optional[List[int]] = None ,_snake_case : bool = False ) -> List[int]: """simple docstring""" 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 ) if token_ids_a is not None: return ([0] * len(_snake_case )) + [1] + ([0] * len(_snake_case )) + [1, 1] return ([0] * len(_snake_case )) + [1, 1] def UpperCAmelCase ( self : List[Any] ,_snake_case : List[int] ,_snake_case : Optional[List[int]] = None ) -> List[int]: """simple docstring""" lowercase__ : Tuple = [self.sep_token_id] lowercase__ : Any = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def UpperCAmelCase ( self : Union[str, Any] ,_snake_case : str ,_snake_case : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_snake_case ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowercase__ : 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: lowercase__ : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(_snake_case ) return (out_vocab_file,) def UpperCAmelCase ( self : List[Any] ,*_snake_case : List[Any] ,**_snake_case : List[str] ) -> Dict: """simple docstring""" lowercase__ : Union[str, Any] = super()._decode(*_snake_case ,**_snake_case ) lowercase__ : Tuple = text.replace(''' ''' ,'''''' ).replace('''\u2582''' ,''' ''' ).replace('''\u2583''' ,'''\n''' ) return text
16
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent UpperCAmelCase_ : Any = {'UserAgent': UserAgent().random} def SCREAMING_SNAKE_CASE_ ( __A : Optional[int] ) -> dict: """simple docstring""" a_ : Tuple = script.contents[0] a_ : int = json.loads(data[data.find('{"config"' ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: a_ : Tuple = F"""https://www.instagram.com/{username}/""" a_ : Optional[Any] = self.get_json() def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> dict: a_ : Any = requests.get(self.url , headers=SCREAMING_SNAKE_CASE__ ).text a_ : Dict = BeautifulSoup(SCREAMING_SNAKE_CASE__ , 'html.parser' ).find_all('script' ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Union[str, Any] ) -> str: return F"""{self.__class__.__name__}('{self.username}')""" def __str__( self : Optional[int] ) -> str: return F"""{self.fullname} ({self.username}) is {self.biography}""" @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: return self.user_data["username"] @property def SCREAMING_SNAKE_CASE ( self : str ) -> str: return self.user_data["full_name"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> str: return self.user_data["biography"] @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: return self.user_data["business_email"] @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: return self.user_data["external_url"] @property def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return self.user_data["edge_followed_by"]["count"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> int: return self.user_data["edge_follow"]["count"] @property def SCREAMING_SNAKE_CASE ( self : str ) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: return self.user_data["profile_pic_url_hd"] @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> bool: return self.user_data["is_verified"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.user_data["is_private"] def SCREAMING_SNAKE_CASE_ ( __A : str = "github" ) -> None: """simple docstring""" import os if os.environ.get('CI' ): return # test failing on GitHub Actions a_ : int = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 1_50 assert instagram_user.number_of_followers > 12_00_00 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith('https://instagram.' ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase_ : Union[str, Any] = InstagramUser('github') print(instagram_user) print(F'{instagram_user.number_of_posts = }') print(F'{instagram_user.number_of_followers = }') print(F'{instagram_user.number_of_followings = }') print(F'{instagram_user.email = }') print(F'{instagram_user.website = }') print(F'{instagram_user.profile_picture_url = }') print(F'{instagram_user.is_verified = }') print(F'{instagram_user.is_private = }')
32
0
"""simple docstring""" def _A ( UpperCamelCase_ : Tuple) -> Any: '''simple docstring''' __lowercase = len(UpperCamelCase_) while cur > 1: # Find the maximum number in arr __lowercase = arr.index(max(arr[0:cur])) # Reverse from 0 to mi __lowercase = arr[mi::-1] + arr[mi + 1 : len(UpperCamelCase_)] # Reverse whole list __lowercase = arr[cur - 1 :: -1] + arr[cur : len(UpperCamelCase_)] cur -= 1 return arr if __name__ == "__main__": _a = input('Enter numbers separated by a comma:\n').strip() _a = [int(item) for item in user_input.split(',')] print(pancake_sort(unsorted))
17
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Tuple = ['''image_processor''', '''tokenizer'''] snake_case__ : Union[str, Any] = '''CLIPImageProcessor''' snake_case__ : Dict = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : int ) -> Any: a_ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , SCREAMING_SNAKE_CASE__ , ) a_ : Tuple = kwargs.pop('feature_extractor' ) a_ : Tuple = 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 : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE__ : str ) -> Optional[Any]: if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: a_ : List[str] = self.tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if images is not None: a_ : Dict = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None and images is not None: a_ : Dict = 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 SCREAMING_SNAKE_CASE ( self : Any , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[Any]: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: a_ : str = self.tokenizer.model_input_names a_ : Tuple = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def SCREAMING_SNAKE_CASE ( self : str ) -> str: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , SCREAMING_SNAKE_CASE__ , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , SCREAMING_SNAKE_CASE__ , ) return self.image_processor
32
0
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def _snake_case ( lowerCAmelCase : Optional[int] ): """simple docstring""" if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class a__ ( nn.Module ): def __init__( self : str,_A : nn.Module,_A : int ): """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE_ : str = module SCREAMING_SNAKE_CASE_ : Optional[Any] = nn.Sequential( nn.Linear(module.in_features,_A,bias=_A ),nn.Linear(_A,module.out_features,bias=_A ),) SCREAMING_SNAKE_CASE_ : str = (2.0 / (5 * min(module.in_features,module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight,std=_A ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def __UpperCamelCase ( self : Optional[Any],_A : Dict,*_A : int,**_A : Dict ): """simple docstring""" return self.module(_A,*_A,**_A ) + self.adapter(_A ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class a__ ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module A = 'bigscience/bloom-1b7' # Constant values A = 2.109_6595_5269_2574 A = 'Hello my name is' A = set() EXPECTED_OUTPUTS.add('Hello my name is John and I am a professional photographer. I' ) EXPECTED_OUTPUTS.add('Hello my name is John.\nI am a friend of your father.\n' ) EXPECTED_OUTPUTS.add('Hello my name is John Doe, I am a student at the University' ) A = 10 def __UpperCamelCase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoTokenizer.from_pretrained(self.model_name ) class a__ ( A__ ): def __UpperCamelCase ( self : Optional[int] ): """simple docstring""" super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForCausalLM.from_pretrained( self.model_name,torch_dtype=torch.floataa,device_map="auto" ) SCREAMING_SNAKE_CASE_ : Dict = AutoModelForCausalLM.from_pretrained(self.model_name,load_in_abit=_A,device_map="auto" ) def __UpperCamelCase ( self : str ): """simple docstring""" del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.model_abit.config self.assertTrue(hasattr(_A,"quantization_config" ) ) SCREAMING_SNAKE_CASE_ : Any = config.to_dict() SCREAMING_SNAKE_CASE_ : Optional[Any] = config.to_diff_dict() SCREAMING_SNAKE_CASE_ : int = config.to_json_string() def __UpperCamelCase ( self : Optional[Any] ): """simple docstring""" from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE_ : str = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit,self.EXPECTED_RELATIVE_DIFFERENCE ) SCREAMING_SNAKE_CASE_ : Optional[int] = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def __UpperCamelCase ( self : int ): """simple docstring""" from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(_A,torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def __UpperCamelCase ( self : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = self.tokenizer(self.input_text,return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : Any = self.model_abit.generate(input_ids=encoded_input["input_ids"].to(0 ),max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0],skip_special_tokens=_A ),self.EXPECTED_OUTPUTS ) def __UpperCamelCase ( self : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = BitsAndBytesConfig() SCREAMING_SNAKE_CASE_ : str = True SCREAMING_SNAKE_CASE_ : str = AutoModelForCausalLM.from_pretrained( self.model_name,quantization_config=_A,device_map="auto" ) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.tokenizer(self.input_text,return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : int = model_abit_from_config.generate( input_ids=encoded_input["input_ids"].to(0 ),max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0],skip_special_tokens=_A ),self.EXPECTED_OUTPUTS ) def __UpperCamelCase ( self : Optional[Any] ): """simple docstring""" with self.assertRaises(_A ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(_A ) def __UpperCamelCase ( self : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = BitsAndBytesConfig() with self.assertRaises(_A ): SCREAMING_SNAKE_CASE_ : List[Any] = AutoModelForCausalLM.from_pretrained( self.model_name,quantization_config=_A,load_in_abit=_A,device_map="auto",bnb_abit_quant_type="nf4",) def __UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" with self.assertRaises(_A ): # Tries with `str` self.model_abit.to("cpu" ) with self.assertRaises(_A ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(_A ): # Tries with a `device` self.model_abit.to(torch.device("cuda:0" ) ) with self.assertRaises(_A ): # Tries with a `device` self.model_abit.float() with self.assertRaises(_A ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE_ : Tuple = self.tokenizer(self.input_text,return_tensors="pt" ) SCREAMING_SNAKE_CASE_ : int = self.model_fpaa.to(torch.floataa ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_fpaa.generate(input_ids=encoded_input["input_ids"].to(0 ),max_new_tokens=10 ) # Check this does not throw an error SCREAMING_SNAKE_CASE_ : str = self.model_fpaa.to("cpu" ) # Check this does not throw an error SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE_ : int = self.model_fpaa.float() def __UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = AutoModelForSeqaSeqLM.from_pretrained("t5-small",load_in_abit=_A,device_map="auto" ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class a__ ( unittest.TestCase ): @classmethod def __UpperCamelCase ( cls : str ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = "t5-small" SCREAMING_SNAKE_CASE_ : Optional[Any] = "google/flan-t5-small" # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE_ : Dict = AutoTokenizer.from_pretrained(cls.model_name ) SCREAMING_SNAKE_CASE_ : Optional[Any] = "Translate in German: Hello, my dog is cute" def __UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self : List[Any] ): """simple docstring""" from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE_ : Any = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE_ : Dict = None # test with `t5-small` SCREAMING_SNAKE_CASE_ : List[Any] = TaForConditionalGeneration.from_pretrained(self.model_name,load_in_abit=_A,device_map="auto" ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.tokenizer(self.input_text,return_tensors="pt" ).to(0 ) SCREAMING_SNAKE_CASE_ : Optional[int] = model.generate(**_A ) # test with `flan-t5-small` SCREAMING_SNAKE_CASE_ : Union[str, Any] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name,load_in_abit=_A,device_map="auto" ) SCREAMING_SNAKE_CASE_ : Dict = self.tokenizer(self.input_text,return_tensors="pt" ).to(0 ) SCREAMING_SNAKE_CASE_ : Tuple = model.generate(**_A ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = modules def __UpperCamelCase ( self : str ): """simple docstring""" import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE_ : Tuple = TaForConditionalGeneration.from_pretrained(self.model_name,load_in_abit=_A,device_map="auto" ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q,bnb.nn.Linearabit ) ) SCREAMING_SNAKE_CASE_ : List[str] = self.tokenizer(self.input_text,return_tensors="pt" ).to(0 ) SCREAMING_SNAKE_CASE_ : Optional[int] = model.generate(**_A ) # test with `flan-t5-small` SCREAMING_SNAKE_CASE_ : List[str] = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name,load_in_abit=_A,device_map="auto" ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.tokenizer(self.input_text,return_tensors="pt" ).to(0 ) SCREAMING_SNAKE_CASE_ : List[str] = model.generate(**_A ) class a__ ( A__ ): def __UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" super().setUp() # model_name SCREAMING_SNAKE_CASE_ : str = "bigscience/bloom-560m" SCREAMING_SNAKE_CASE_ : Optional[int] = "t5-small" # Different types of model SCREAMING_SNAKE_CASE_ : List[str] = AutoModel.from_pretrained(self.model_name,load_in_abit=_A,device_map="auto" ) # Sequence classification model SCREAMING_SNAKE_CASE_ : Optional[int] = AutoModelForSequenceClassification.from_pretrained( self.model_name,load_in_abit=_A,device_map="auto" ) # CausalLM model SCREAMING_SNAKE_CASE_ : int = AutoModelForCausalLM.from_pretrained(self.model_name,load_in_abit=_A,device_map="auto" ) # Seq2seq model SCREAMING_SNAKE_CASE_ : List[str] = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name,load_in_abit=_A,device_map="auto" ) def __UpperCamelCase ( self : Dict ): """simple docstring""" del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self : Any ): """simple docstring""" from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class a__ ( A__ ): def __UpperCamelCase ( self : List[str] ): """simple docstring""" super().setUp() def __UpperCamelCase ( self : Optional[Any] ): """simple docstring""" del self.pipe gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = pipeline( "text-generation",model=self.model_name,model_kwargs={"device_map": "auto", "load_in_4bit": True, "torch_dtype": torch.floataa},max_new_tokens=self.MAX_NEW_TOKENS,) # Real second forward pass SCREAMING_SNAKE_CASE_ : List[str] = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]["generated_text"],self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class a__ ( A__ ): def __UpperCamelCase ( self : str ): """simple docstring""" super().setUp() def __UpperCamelCase ( self : Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = AutoModelForCausalLM.from_pretrained( self.model_name,load_in_abit=_A,device_map="balanced" ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ),{0, 1} ) # Check that inference pass works on the model SCREAMING_SNAKE_CASE_ : Any = self.tokenizer(self.input_text,return_tensors="pt" ) # Second real batch SCREAMING_SNAKE_CASE_ : Optional[int] = model_parallel.generate(input_ids=encoded_input["input_ids"].to(0 ),max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_parallel[0],skip_special_tokens=_A ),self.EXPECTED_OUTPUTS ) class a__ ( A__ ): def __UpperCamelCase ( self : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = "facebook/opt-350m" super().setUp() def __UpperCamelCase ( self : Any ): """simple docstring""" if version.parse(importlib.metadata.version("bitsandbytes" ) ) < version.parse("0.37.0" ): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name,load_in_abit=_A ) self.assertEqual(set(model.hf_device_map.values() ),{torch.cuda.current_device()} ) for param in model.parameters(): SCREAMING_SNAKE_CASE_ : Any = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE_ : List[Any] = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(_A ) ): SCREAMING_SNAKE_CASE_ : Dict = LoRALayer(module.q_proj,rank=16 ) SCREAMING_SNAKE_CASE_ : Optional[Any] = LoRALayer(module.k_proj,rank=16 ) SCREAMING_SNAKE_CASE_ : List[Any] = LoRALayer(module.v_proj,rank=16 ) # Step 3: dummy batch SCREAMING_SNAKE_CASE_ : int = self.tokenizer("Test batch ",return_tensors="pt" ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE_ : int = model.forward(**_A ) out.logits.norm().backward() for module in model.modules(): if isinstance(_A,_A ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(_A,nn.Embedding ): self.assertTrue(module.weight.grad is None ) class a__ ( A__ ): A = 'gpt2-xl' A = 3.3191_8548_5415_2187
18
from __future__ import annotations UpperCAmelCase_ : Tuple = [] def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] , __A : int , __A : int ) -> bool: """simple docstring""" for i in range(len(__A ) ): if board[row][i] == 1: return False for i in range(len(__A ) ): if board[i][column] == 1: return False for i, j in zip(range(__A , -1 , -1 ) , range(__A , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(__A , -1 , -1 ) , range(__A , len(__A ) ) ): if board[i][j] == 1: return False return True def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] , __A : int ) -> bool: """simple docstring""" if row >= len(__A ): solution.append(__A ) printboard(__A ) print() return True for i in range(len(__A ) ): if is_safe(__A , __A , __A ): a_ : Any = 1 solve(__A , row + 1 ) a_ : Tuple = 0 return False def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] ) -> None: """simple docstring""" for i in range(len(__A ) ): for j in range(len(__A ) ): if board[i][j] == 1: print('Q' , end=' ' ) else: print('.' , end=' ' ) print() # n=int(input("The no. of queens")) UpperCAmelCase_ : List[str] = 8 UpperCAmelCase_ : str = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
32
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer __A =logging.get_logger(__name__) __A ={'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} __A ={ '''vocab_file''': {'''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'''}, '''tokenizer_file''': { '''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json''' }, } __A ={'''mobilebert-uncased''': 5_1_2} __A ={} class _SCREAMING_SNAKE_CASE ( snake_case_ ): lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = PRETRAINED_INIT_CONFIGURATION lowerCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ = MobileBertTokenizer def __init__( self , lowercase=None , lowercase=None , lowercase=True , lowercase="[UNK]" , lowercase="[SEP]" , lowercase="[PAD]" , lowercase="[CLS]" , lowercase="[MASK]" , lowercase=True , lowercase=None , **lowercase , ) -> Union[str, Any]: super().__init__( lowercase , tokenizer_file=lowercase , do_lower_case=lowercase , unk_token=lowercase , sep_token=lowercase , pad_token=lowercase , cls_token=lowercase , mask_token=lowercase , tokenize_chinese_chars=lowercase , strip_accents=lowercase , **lowercase , ) lowerCamelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowercase ) != do_lower_case or normalizer_state.get("strip_accents" , lowercase ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowercase ) != tokenize_chinese_chars ): lowerCamelCase_ = getattr(lowercase , normalizer_state.pop("type" ) ) lowerCamelCase_ = do_lower_case lowerCamelCase_ = strip_accents lowerCamelCase_ = tokenize_chinese_chars lowerCamelCase_ = normalizer_class(**lowercase ) lowerCamelCase_ = do_lower_case def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase=None ) -> str: 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 SCREAMING_SNAKE_CASE_( self , lowercase , lowercase = 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 SCREAMING_SNAKE_CASE_( self , lowercase , lowercase = None ) -> Tuple[str]: lowerCamelCase_ = self._tokenizer.model.save(lowercase , name=lowercase ) return tuple(lowercase )
19
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def SCREAMING_SNAKE_CASE_ ( ) -> Any: """simple docstring""" a_ : Optional[Any] = HfArgumentParser(__A ) a_ : Optional[int] = parser.parse_args_into_dataclasses()[0] a_ : List[Any] = TensorFlowBenchmark(args=__A ) try: a_ : List[str] = parser.parse_args_into_dataclasses()[0] except ValueError as e: a_ : Dict = 'Arg --no_{0} is no longer used, please use --no-{0} instead.' a_ : Dict = ' '.join(str(__A ).split(' ' )[:-1] ) a_ : int = '' a_ : int = eval(str(__A ).split(' ' )[-1] ) a_ : Any = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__A ) if len(__A ) > 0: a_ : str = full_error_msg + begin_error_msg + str(__A ) raise ValueError(__A ) benchmark.run() if __name__ == "__main__": main()
32
0
import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class __snake_case : def __init__( self ,snake_case ,snake_case=13 ,snake_case=7 ,snake_case=True ,snake_case=True ,snake_case=True ,snake_case=True ,snake_case=99 ,snake_case=16 ,snake_case=36 ,snake_case=6 ,snake_case=6 ,snake_case=6 ,snake_case=37 ,snake_case="gelu" ,snake_case=0.1 ,snake_case=0.1 ,snake_case=512 ,snake_case=16 ,snake_case=2 ,snake_case=0.02 ,snake_case=3 ,snake_case=4 ,snake_case=None ,): '''simple docstring''' lowercase : Union[str, Any] = parent lowercase : Dict = batch_size lowercase : Optional[int] = seq_length lowercase : Union[str, Any] = is_training lowercase : Dict = use_input_mask lowercase : Dict = use_token_type_ids lowercase : str = use_labels lowercase : Union[str, Any] = vocab_size lowercase : int = embedding_size lowercase : List[str] = hidden_size lowercase : Dict = num_hidden_layers lowercase : Optional[Any] = num_hidden_groups lowercase : List[Any] = num_attention_heads lowercase : Union[str, Any] = intermediate_size lowercase : Any = hidden_act lowercase : Tuple = hidden_dropout_prob lowercase : Dict = attention_probs_dropout_prob lowercase : Any = max_position_embeddings lowercase : List[str] = type_vocab_size lowercase : int = type_sequence_label_size lowercase : Optional[Any] = initializer_range lowercase : int = num_labels lowercase : Optional[Any] = num_choices lowercase : Union[str, Any] = scope def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) lowercase : Union[str, Any] = None if self.use_input_mask: lowercase : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) lowercase : Optional[int] = None if self.use_token_type_ids: lowercase : Any = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) lowercase : Tuple = None lowercase : Any = None lowercase : Any = None if self.use_labels: lowercase : List[Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) lowercase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) lowercase : List[str] = ids_tensor([self.batch_size] ,self.num_choices ) lowercase : Tuple = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' return AlbertConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,initializer_range=self.initializer_range ,num_hidden_groups=self.num_hidden_groups ,) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : int = AlbertModel(config=snake_case ) model.to(snake_case ) model.eval() lowercase : List[str] = model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ) lowercase : str = model(snake_case ,token_type_ids=snake_case ) lowercase : Optional[Any] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : Tuple = AlbertForPreTraining(config=snake_case ) model.to(snake_case ) model.eval() lowercase : Union[str, Any] = model( snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ,sentence_order_label=snake_case ,) self.parent.assertEqual(result.prediction_logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape ,(self.batch_size, config.num_labels) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : int = AlbertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() lowercase : int = model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : str = AlbertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() lowercase : List[str] = model( snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,start_positions=snake_case ,end_positions=snake_case ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : str = self.num_labels lowercase : Tuple = AlbertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() lowercase : Tuple = model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : Tuple = self.num_labels lowercase : Optional[int] = AlbertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() lowercase : int = model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : Any = self.num_choices lowercase : Any = AlbertForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() lowercase : List[Any] = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() lowercase : Tuple = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() lowercase : Tuple = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() lowercase : Dict = model( snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Tuple = self.prepare_config_and_inputs() ( ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ( lowercase ) , ) : str = config_and_inputs lowercase : int = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __snake_case ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): _a : Tuple= ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) _a : List[str]= ( { "feature-extraction": AlbertModel, "fill-mask": AlbertForMaskedLM, "question-answering": AlbertForQuestionAnswering, "text-classification": AlbertForSequenceClassification, "token-classification": AlbertForTokenClassification, "zero-shot": AlbertForSequenceClassification, } if is_torch_available() else {} ) _a : Dict= True def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case=False ): '''simple docstring''' lowercase : List[str] = super()._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) if return_labels: if model_class in get_values(snake_case ): lowercase : List[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) ,dtype=torch.long ,device=snake_case ) lowercase : str = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=snake_case ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = AlbertModelTester(self ) lowercase : Optional[int] = ConfigTester(self ,config_class=snake_case ,hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowercase : Optional[Any] = type self.model_tester.create_and_check_model(*snake_case ) @slow def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase : List[Any] = AlbertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_torch class __snake_case ( unittest.TestCase ): @slow def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[int] = AlbertModel.from_pretrained("""albert-base-v2""" ) lowercase : int = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) lowercase : Optional[int] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): lowercase : List[str] = model(snake_case ,attention_mask=snake_case )[0] lowercase : Any = torch.Size((1, 11, 768) ) self.assertEqual(output.shape ,snake_case ) lowercase : int = torch.tensor( [[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] ,snake_case ,atol=1e-4 ) )
20
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): snake_case__ : Optional[Any] = TextToVideoSDPipeline snake_case__ : Optional[int] = TEXT_TO_IMAGE_PARAMS snake_case__ : str = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. snake_case__ : Optional[Any] = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: torch.manual_seed(0 ) a_ : Optional[int] = UNetaDConditionModel( block_out_channels=(3_2, 6_4, 6_4, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D') , up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D') , cross_attention_dim=3_2 , attention_head_dim=4 , ) a_ : int = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) a_ : int = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) a_ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=5_1_2 , ) a_ : Dict = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) a_ : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> List[str]: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): a_ : Dict = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: a_ : Optional[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) a_ : int = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'pt', } return inputs def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator a_ : Dict = self.get_dummy_components() a_ : str = TextToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) a_ : Dict = 'np' a_ : Dict = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames a_ : int = frames[0][-3:, -3:, -1] assert frames[0].shape == (6_4, 6_4, 3) a_ : Union[str, Any] = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=3E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def SCREAMING_SNAKE_CASE ( self : Any ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=1E-2 ) @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: pass @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: pass @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: pass def SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: return super().test_progress_bar() @slow @skip_mps class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: a_ : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy' ) a_ : Any = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) a_ : Optional[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) a_ : Optional[Any] = pipe.to('cuda' ) a_ : Any = 'Spiderman is surfing' a_ : List[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) a_ : Optional[Any] = pipe(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2_5 , output_type='pt' ).frames a_ : str = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2 def SCREAMING_SNAKE_CASE ( self : Any ) -> Any: a_ : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy' ) a_ : Tuple = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) a_ : Tuple = pipe.to('cuda' ) a_ : Any = 'Spiderman is surfing' a_ : List[str] = torch.Generator(device='cpu' ).manual_seed(0 ) a_ : List[Any] = pipe(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type='pt' ).frames a_ : List[str] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2
32
0
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 SCREAMING_SNAKE_CASE : Optional[Any] = "โ–" SCREAMING_SNAKE_CASE : Dict = {"vocab_file": "spiece.model"} SCREAMING_SNAKE_CASE : int = { "vocab_file": {"google/pegasus-xsum": "https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"} } SCREAMING_SNAKE_CASE : Optional[Any] = { "google/pegasus-xsum": 512, } SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) class _lowerCamelCase( _a ): lowercase_ : List[Any] = VOCAB_FILES_NAMES lowercase_ : Any = VOCAB_FILES_NAMES lowercase_ : List[Any] = PRETRAINED_VOCAB_FILES_MAP lowercase_ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ : int = ["""input_ids""", """attention_mask"""] def __init__( self, lowerCamelCase, lowerCamelCase="<pad>", lowerCamelCase="</s>", lowerCamelCase="<unk>", lowerCamelCase="<mask_2>", lowerCamelCase="<mask_1>", lowerCamelCase=None, lowerCamelCase=1_03, lowerCamelCase = None, **lowerCamelCase, ) -> None: """simple docstring""" _lowercase : Any = 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)}''') _lowercase : Optional[Any] = ( ([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}.''') _lowercase : int = additional_special_tokens_extended else: _lowercase : List[Any] = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F'''<unk_{i}>''' for i in range(2, self.offset)] _lowercase : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=lowerCamelCase, unk_token=lowerCamelCase, mask_token=lowerCamelCase, pad_token=lowerCamelCase, mask_token_sent=lowerCamelCase, offset=lowerCamelCase, additional_special_tokens=lowerCamelCase, sp_model_kwargs=self.sp_model_kwargs, **lowerCamelCase, ) _lowercase : Optional[int] = mask_token_sent _lowercase : Optional[int] = vocab_file _lowercase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(lowerCamelCase) # add special tokens to encoder dict _lowercase : Dict[int, str] = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, }) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1, self.offset - 1)}) _lowercase : Dict[str, int] = {v: k for k, v in self.encoder.items()} @property def UpperCamelCase ( self) -> int: """simple docstring""" return len(self.sp_model) + self.offset def UpperCamelCase ( self) -> Dict[str, int]: """simple docstring""" _lowercase : Union[str, Any] = {self.convert_ids_to_tokens(lowerCamelCase): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self) -> Union[str, Any]: """simple docstring""" _lowercase : List[Any] = self.__dict__.copy() _lowercase : List[str] = None return state def __setstate__( self, lowerCamelCase) -> Dict: """simple docstring""" _lowercase : Union[str, Any] = d # for backward compatibility if not hasattr(self, 'sp_model_kwargs'): _lowercase : Optional[Any] = {} _lowercase : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def UpperCamelCase ( self, lowerCamelCase) -> List[str]: """simple docstring""" return self.sp_model.encode(lowerCamelCase, out_type=lowerCamelCase) def UpperCamelCase ( self, lowerCamelCase) -> int: """simple docstring""" if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] _lowercase : str = self.sp_model.piece_to_id(lowerCamelCase) return sp_id + self.offset def UpperCamelCase ( self, lowerCamelCase) -> str: """simple docstring""" if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: _lowercase : Optional[int] = self.sp_model.IdToPiece(index - self.offset) return token def UpperCamelCase ( self, lowerCamelCase) -> Any: """simple docstring""" _lowercase : List[str] = [] _lowercase : Union[str, Any] = '' 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(lowerCamelCase) + token _lowercase : str = [] else: current_sub_tokens.append(lowerCamelCase) out_string += self.sp_model.decode(lowerCamelCase) return out_string.strip() def UpperCamelCase ( self, lowerCamelCase=False) -> Dict: """simple docstring""" return 1 def UpperCamelCase ( self, lowerCamelCase) -> str: """simple docstring""" _lowercase : str = 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 return [1 if x in all_special_ids else 0 for x in seq] def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None, lowerCamelCase = False) -> List[int]: """simple docstring""" 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 UpperCamelCase ( self, lowerCamelCase, lowerCamelCase=None) -> List[int]: """simple docstring""" 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, lowerCamelCase, lowerCamelCase = None) -> Tuple[str]: """simple docstring""" if not os.path.isdir(lowerCamelCase): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''') return _lowercase : Any = 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) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file, lowerCamelCase) elif not os.path.isfile(self.vocab_file): with open(lowerCamelCase, 'wb') as fi: _lowercase : int = self.sp_model.serialized_model_proto() fi.write(lowerCamelCase) return (out_vocab_file,)
21
import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): # TODO: is there an appropriate internal test set? snake_case__ : Any = '''ssube/stable-diffusion-x4-upscaler-onnx''' def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : int=0 ) -> Tuple: a_ : Union[str, Any] = floats_tensor((1, 3, 1_2_8, 1_2_8) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ) a_ : Dict = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: a_ : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.get_dummy_inputs() a_ : int = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : Tuple = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : List[Any] = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: a_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : int = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : List[str] = self.get_dummy_inputs() a_ : List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : str = np.array( [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: a_ : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : Optional[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.get_dummy_inputs() a_ : Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : Optional[Any] = np.array( [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: a_ : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : int = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = self.get_dummy_inputs() a_ : Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : int = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: a_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : Optional[int] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = self.get_dummy_inputs() a_ : List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : Union[str, Any] = np.array( [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: a_ : List[str] = ort.SessionOptions() a_ : int = False return options def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: a_ : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) a_ : int = init_image.resize((1_2_8, 1_2_8) ) # using the PNDM scheduler by default a_ : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Tuple = 'A fantasy landscape, trending on artstation' a_ : str = torch.manual_seed(0 ) a_ : List[str] = pipe( prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=1_0 , generator=SCREAMING_SNAKE_CASE__ , output_type='np' , ) a_ : Dict = output.images a_ : Any = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) a_ : str = np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: a_ : Dict = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) a_ : List[str] = init_image.resize((1_2_8, 1_2_8) ) a_ : Dict = LMSDiscreteScheduler.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , subfolder='scheduler' ) a_ : Union[str, Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , scheduler=SCREAMING_SNAKE_CASE__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Any = 'A fantasy landscape, trending on artstation' a_ : Tuple = torch.manual_seed(0 ) a_ : Optional[Any] = pipe( prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=2_0 , generator=SCREAMING_SNAKE_CASE__ , output_type='np' , ) a_ : str = output.images a_ : List[Any] = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) a_ : Tuple = np.array( [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
32
0
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE :int = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE :Optional[Any] = {'''vocab_file''': '''vocab.json'''} __SCREAMING_SNAKE_CASE :Tuple = { '''vocab_file''': { '''mgp-str''': '''https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json''', } } __SCREAMING_SNAKE_CASE :List[str] = {'''mgp-str''': 27} class A_ ( lowerCAmelCase_ ): _lowerCamelCase : Any = VOCAB_FILES_NAMES _lowerCamelCase : int = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , snake_case_ : List[str] , snake_case_ : List[Any]="[GO]" , snake_case_ : Optional[Any]="[GO]" , snake_case_ : Union[str, Any]="[s]" , snake_case_ : Any="[GO]" , **snake_case_ : Dict ): super().__init__( unk_token=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , pad_token=snake_case_ , **snake_case_ , ) with open(snake_case_ , encoding="utf-8" ) as vocab_handle: _UpperCAmelCase = json.load(snake_case_ ) _UpperCAmelCase = {v: k for k, v in self.vocab.items()} @property def lowercase ( self : str ): return len(self.vocab ) def lowercase ( self : int ): return dict(self.vocab , **self.added_tokens_encoder ) def lowercase ( self : Optional[Any] , snake_case_ : int ): _UpperCAmelCase = [] for s in text: char_tokens.extend(snake_case_ ) return char_tokens def lowercase ( self : Union[str, Any] , snake_case_ : Union[str, Any] ): return self.vocab.get(snake_case_ , self.vocab.get(self.unk_token ) ) def lowercase ( self : int , snake_case_ : int ): return self.decoder.get(snake_case_ ) def lowercase ( self : int , snake_case_ : str , snake_case_ : Optional[str] = None ): if not os.path.isdir(snake_case_ ): logger.error("Vocabulary path ({}) should be a directory".format(snake_case_ ) ) return _UpperCAmelCase = os.path.join( snake_case_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) with open(snake_case_ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=snake_case_ , ensure_ascii=snake_case_ ) + "\n" ) return (vocab_file,)
22
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> str: """simple docstring""" a_ : Tuple = [] for line in lines: a_ : Any = re.sub(R'#.*' , '' , __A ) # remove comments if line: filtered_lines.append(__A ) a_ : Tuple = '\n'.join(__A ) # Make a hash from all this code a_ : Tuple = full_str.encode('utf-8' ) return shaaaa(__A ).hexdigest() # get importable module names and hash for caching UpperCAmelCase_ : List[Any] = { 'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), 'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), 'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), 'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), 'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), 'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), 'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), 'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions UpperCAmelCase_ : Dict = { '.csv': ('csv', {}), '.tsv': ('csv', {'sep': '\t'}), '.json': ('json', {}), '.jsonl': ('json', {}), '.parquet': ('parquet', {}), '.arrow': ('arrow', {}), '.txt': ('text', {}), } _EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) UpperCAmelCase_ : Optional[int] = {'imagefolder', 'audiofolder'} # Used to filter data files based on extensions given a module name UpperCAmelCase_ : Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('.zip') _MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')
32
0
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss UpperCamelCase__: Dict = pytest.mark.integration @require_faiss class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" def A ( self : List[str] ) -> int: UpperCAmelCase : Union[str, Any] = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(__snake_case ) for x in np.arange(30 ).tolist()]} ) return dset def A ( self : List[Any] ) -> Optional[int]: import faiss UpperCAmelCase : Dataset = self._create_dummy_dataset() UpperCAmelCase : Tuple = dset.map( lambda __snake_case , __snake_case : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__snake_case , keep_in_memory=__snake_case ) UpperCAmelCase : Optional[int] = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) UpperCAmelCase , UpperCAmelCase : Optional[int] = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) dset.drop_index('''vecs''' ) def A ( self : Dict ) -> Tuple: import faiss UpperCAmelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) UpperCAmelCase , UpperCAmelCase : Optional[int] = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def A ( self : Tuple ) -> Tuple: import faiss UpperCAmelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__snake_case ) as tmp_file: dset.save_faiss_index('''vecs''' , tmp_file.name ) dset.load_faiss_index('''vecs2''' , tmp_file.name ) os.unlink(tmp_file.name ) UpperCAmelCase , UpperCAmelCase : List[str] = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def A ( self : Optional[int] ) -> Dict: UpperCAmelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' ) dset.drop_index('''vecs''' ) self.assertRaises(__snake_case , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) ) def A ( self : str ) -> str: from elasticsearch import Elasticsearch UpperCAmelCase : Dataset = self._create_dummy_dataset() with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch( '''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk: UpperCAmelCase : Dict = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) UpperCAmelCase : Dict = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} UpperCAmelCase : List[Any] = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=__snake_case ) UpperCAmelCase , UpperCAmelCase : Any = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" def A ( self : Optional[int] ) -> Union[str, Any]: import faiss UpperCAmelCase : Tuple = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query UpperCAmelCase : Optional[Any] = np.zeros(5 , dtype=np.floataa ) UpperCAmelCase : List[str] = 1 UpperCAmelCase , UpperCAmelCase : Optional[int] = index.search(__snake_case ) self.assertRaises(__snake_case , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries UpperCAmelCase : Optional[int] = np.eye(5 , dtype=np.floataa )[::-1] UpperCAmelCase , UpperCAmelCase : List[str] = index.search_batch(__snake_case ) self.assertRaises(__snake_case , index.search_batch , queries[0] ) UpperCAmelCase : List[Any] = [scores[0] for scores in total_scores] UpperCAmelCase : Optional[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__snake_case ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __snake_case ) def A ( self : str ) -> Union[str, Any]: import faiss UpperCAmelCase : Optional[Any] = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) UpperCAmelCase : int = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__snake_case ): UpperCAmelCase : List[str] = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def A ( self : int ) -> List[str]: import faiss UpperCAmelCase : Any = faiss.IndexFlat(5 ) UpperCAmelCase : Optional[int] = FaissIndex(custom_index=__snake_case ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A ( self : str ) -> List[str]: import faiss UpperCAmelCase : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__snake_case ) as tmp_file: index.save(tmp_file.name ) UpperCAmelCase : int = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) UpperCAmelCase : str = np.zeros(5 , dtype=np.floataa ) UpperCAmelCase : List[str] = 1 UpperCAmelCase , UpperCAmelCase : List[Any] = index.search(__snake_case ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def snake_case_ ( _lowerCAmelCase : Optional[int] ) -> Union[str, Any]: import faiss UpperCAmelCase : List[str] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) UpperCAmelCase : Dict = '''index.faiss''' UpperCAmelCase : Dict = f"""mock://{index_name}""" index.save(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCAmelCase : Tuple = FaissIndex.load(_lowerCAmelCase , storage_options=mockfs.storage_options ) UpperCAmelCase : Union[str, Any] = np.zeros(5 , dtype=np.floataa ) UpperCAmelCase : Any = 1 UpperCAmelCase , UpperCAmelCase : Tuple = index.search(_lowerCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" def A ( self : str ) -> Union[str, Any]: from elasticsearch import Elasticsearch with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch( '''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk: UpperCAmelCase : Any = Elasticsearch() UpperCAmelCase : List[Any] = {'''acknowledged''': True} UpperCAmelCase : Optional[Any] = ElasticSearchIndex(es_client=__snake_case ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query UpperCAmelCase : Optional[Any] = '''foo''' UpperCAmelCase : List[str] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} UpperCAmelCase , UpperCAmelCase : int = index.search(__snake_case ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout UpperCAmelCase : str = '''foo''' UpperCAmelCase : Optional[int] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} UpperCAmelCase , UpperCAmelCase : Tuple = index.search(__snake_case , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries UpperCAmelCase : Any = ['''foo''', '''bar''', '''foobar'''] UpperCAmelCase : Optional[Any] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} UpperCAmelCase , UpperCAmelCase : Optional[int] = index.search_batch(__snake_case ) UpperCAmelCase : int = [scores[0] for scores in total_scores] UpperCAmelCase : List[str] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__snake_case ) , 0 ) self.assertListEqual([1, 1, 1] , __snake_case ) # batched queries with timeout UpperCAmelCase : Optional[int] = ['''foo''', '''bar''', '''foobar'''] UpperCAmelCase : int = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} UpperCAmelCase , UpperCAmelCase : str = index.search_batch(__snake_case , request_timeout=30 ) UpperCAmelCase : Optional[Any] = [scores[0] for scores in total_scores] UpperCAmelCase : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__snake_case ) , 0 ) self.assertListEqual([1, 1, 1] , __snake_case )
23
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Optional[int] = '''convbert''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=3_0_5_2_2 , SCREAMING_SNAKE_CASE__ : Dict=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[int]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : Any=1E-12 , SCREAMING_SNAKE_CASE__ : int=1 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=9 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : Dict=None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> Any: super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) a_ : Tuple = vocab_size a_ : List[str] = hidden_size a_ : List[str] = num_hidden_layers a_ : Dict = num_attention_heads a_ : Optional[int] = intermediate_size a_ : int = hidden_act a_ : Dict = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : str = max_position_embeddings a_ : List[str] = type_vocab_size a_ : List[str] = initializer_range a_ : Tuple = layer_norm_eps a_ : Optional[int] = embedding_size a_ : List[Any] = head_ratio a_ : List[Any] = conv_kernel_size a_ : Tuple = num_groups a_ : Tuple = classifier_dropout class SCREAMING_SNAKE_CASE__ ( lowercase__ ): @property def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": a_ : Tuple = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a_ : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
32
0
import math snake_case_ = 10 snake_case_ = 7 snake_case_ = BALLS_PER_COLOUR * NUM_COLOURS def lowerCamelCase__ ( snake_case_ : int = 20 ) -> str: __snake_case = math.comb(snake_case_ , snake_case_ ) __snake_case = math.comb(NUM_BALLS - BALLS_PER_COLOUR , snake_case_ ) __snake_case = NUM_COLOURS * (1 - missing_colour / total) return f"""{result:.9f}""" if __name__ == "__main__": print(solution(20))
24
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE__ : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str=1_3 , SCREAMING_SNAKE_CASE__ : Optional[int]=7 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=9_9 , SCREAMING_SNAKE_CASE__ : str=2_4 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6 , SCREAMING_SNAKE_CASE__ : Optional[int]=3_7 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 , SCREAMING_SNAKE_CASE__ : List[str]=1_6 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Tuple=1_0_0_0 , ) -> str: a_ : Optional[Any] = parent a_ : List[str] = batch_size a_ : List[str] = seq_length a_ : str = is_training a_ : str = use_input_mask a_ : int = use_token_type_ids a_ : List[str] = use_labels a_ : Optional[int] = vocab_size a_ : Any = hidden_size a_ : int = num_hidden_layers a_ : List[str] = num_attention_heads a_ : str = intermediate_size a_ : Union[str, Any] = hidden_act a_ : List[str] = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : int = max_position_embeddings a_ : Tuple = type_vocab_size a_ : Optional[Any] = type_sequence_label_size a_ : Tuple = initializer_range a_ : Dict = num_labels a_ : str = scope a_ : Optional[int] = range_bbox def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a_ : int = bbox[i, j, 3] a_ : str = bbox[i, j, 1] a_ : List[str] = t if bbox[i, j, 2] < bbox[i, j, 0]: a_ : Tuple = bbox[i, j, 2] a_ : List[str] = bbox[i, j, 0] a_ : Union[str, Any] = t a_ : List[Any] = None if self.use_input_mask: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) a_ : List[Any] = None if self.use_token_type_ids: a_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : int = None a_ : Tuple = None if self.use_labels: a_ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : Optional[int] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> str: a_ : Any = LiltModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Any = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> int: a_ : Any = self.num_labels a_ : str = LiltForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> str: a_ : Union[str, Any] = LiltForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : List[str] = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , start_positions=SCREAMING_SNAKE_CASE__ , end_positions=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: a_ : int = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : List[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'bbox': bbox, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Union[str, Any] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) snake_case__ : str = ( { '''feature-extraction''': LiltModel, '''question-answering''': LiltForQuestionAnswering, '''text-classification''': LiltForSequenceClassification, '''token-classification''': LiltForTokenClassification, '''zero-shot''': LiltForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ) -> int: return True def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: a_ : str = LiltModelTester(self ) a_ : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: a_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a_ : List[str] = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: a_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: a_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : List[Any] = LiltModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: a_ : List[str] = LiltModel.from_pretrained('SCUT-DLVCLab/lilt-roberta-en-base' ).to(SCREAMING_SNAKE_CASE__ ) a_ : str = torch.tensor([[1, 2]] , device=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): a_ : str = model(input_ids=SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = torch.Size([1, 2, 7_6_8] ) a_ : int = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=SCREAMING_SNAKE_CASE__ , ) self.assertTrue(outputs.last_hidden_state.shape , SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) )
32
0
"""simple docstring""" import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class lowerCAmelCase_ (a__ , a__ , unittest.TestCase ): """simple docstring""" __UpperCamelCase : Optional[Any] = IFPipeline __UpperCamelCase : Dict = TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''} __UpperCamelCase : Any = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCamelCase : Union[str, Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} def __magic_name__ (self ) -> Union[str, Any]: """simple docstring""" return self._get_dummy_components() def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0 ) -> List[Any]: """simple docstring""" if str(SCREAMING_SNAKE_CASE__ ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : Dict = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE__ : Any = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def __magic_name__ (self ) -> Tuple: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def __magic_name__ (self ) -> List[str]: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1E-1 ) def __magic_name__ (self ) -> List[Any]: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def __magic_name__ (self ) -> Tuple: """simple docstring""" self._test_save_load_local() def __magic_name__ (self ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __magic_name__ (self ) -> Optional[int]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class lowerCAmelCase_ (unittest.TestCase ): """simple docstring""" def __magic_name__ (self ) -> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __magic_name__ (self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = IFPipeline.from_pretrained("""DeepFloyd/IF-I-XL-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Dict = IFSuperResolutionPipeline.from_pretrained( """DeepFloyd/IF-II-L-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa , text_encoder=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to("""cuda""" ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe_a.encode_prompt("""anime turtle""" , device="""cuda""" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img SCREAMING_SNAKE_CASE__ : Union[str, Any] = IFImgaImgPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE__ : Optional[Any] = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting SCREAMING_SNAKE_CASE__ : Optional[Any] = IFInpaintingPipeline(**pipe_a.components ) SCREAMING_SNAKE_CASE__ : int = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Optional[int]: """simple docstring""" _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : Tuple = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , generator=SCREAMING_SNAKE_CASE__ , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : int = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE__ : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 SCREAMING_SNAKE_CASE__ : Optional[int] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy""" ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : int = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] assert image.shape == (2_56, 2_56, 3) SCREAMING_SNAKE_CASE__ : List[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> str: """simple docstring""" _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : int = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , generator=SCREAMING_SNAKE_CASE__ , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Dict = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE__ : str = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy""" ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , original_image=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[Any] = output.images[0] assert image.shape == (2_56, 2_56, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE__ : str = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , mask_image=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , generator=SCREAMING_SNAKE_CASE__ , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : List[Any] = output.images[0] assert image.shape == (64, 64, 3) SCREAMING_SNAKE_CASE__ : Tuple = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 SCREAMING_SNAKE_CASE__ : Optional[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy""" ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # pipeline 2 _start_torch_memory_measurement() SCREAMING_SNAKE_CASE__ : int = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Dict = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = floats_tensor((1, 3, 2_56, 2_56) , rng=random.Random(1 ) ).to(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = pipe_a( prompt_embeds=SCREAMING_SNAKE_CASE__ , negative_prompt_embeds=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , mask_image=SCREAMING_SNAKE_CASE__ , original_image=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Dict = output.images[0] assert image.shape == (2_56, 2_56, 3) SCREAMING_SNAKE_CASE__ : List[str] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 SCREAMING_SNAKE_CASE__ : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def lowercase_ ( ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
25
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple=1_3 , SCREAMING_SNAKE_CASE__ : str=7 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=9_9 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_2 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Tuple=3_7 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=5_1_2 , SCREAMING_SNAKE_CASE__ : int=1_6 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> Any: a_ : Tuple = parent a_ : int = batch_size a_ : Tuple = seq_length a_ : List[Any] = is_training a_ : List[str] = use_token_type_ids a_ : Dict = use_labels a_ : Any = vocab_size a_ : List[str] = hidden_size a_ : Tuple = num_hidden_layers a_ : List[Any] = num_attention_heads a_ : Dict = intermediate_size a_ : Any = hidden_act a_ : List[str] = hidden_dropout_prob a_ : Tuple = attention_probs_dropout_prob a_ : Optional[Any] = max_position_embeddings a_ : List[Any] = type_vocab_size a_ : int = type_sequence_label_size a_ : List[Any] = initializer_range a_ : List[str] = num_labels a_ : Union[str, Any] = num_choices a_ : str = scope a_ : Tuple = self.vocab_size - 1 def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: a_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = None if self.use_token_type_ids: a_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : List[Any] = None a_ : Union[str, Any] = None a_ : List[Any] = None if self.use_labels: a_ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) a_ : Union[str, Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) a_ : List[str] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: a_ : Dict = OpenAIGPTModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , head_mask=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: a_ : str = OpenAIGPTLMHeadModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: a_ : int = OpenAIGPTDoubleHeadsModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Any = self.num_labels a_ : Dict = OpenAIGPTForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : Optional[Any] = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : Optional[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Tuple = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) snake_case__ : List[str] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly snake_case__ : Dict = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any=False ) -> List[str]: a_ : str = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": a_ : Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : str = inputs_dict['labels'] a_ : Optional[int] = inputs_dict['labels'] a_ : Optional[int] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: a_ : str = OpenAIGPTModelTester(self ) a_ : int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , n_embd=3_7 ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: a_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: a_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: a_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : str = OpenAIGPTModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: a_ : Dict = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt' ) model.to(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) # the president is a_ : Tuple = [ 4_8_1, 4_7_3_5, 5_4_4, 2_4_6, 9_6_3, 8_7_0, 7_6_2, 2_3_9, 2_4_4, 4_0_4_7_7, 2_4_4, 2_4_9, 7_1_9, 8_8_1, 4_8_7, 5_4_4, 2_4_0, 2_4_4, 6_0_3, 4_8_1, ] # the president is a very good man. " \n " i\'m sure he is, " said the a_ : Dict = model.generate(SCREAMING_SNAKE_CASE__ , do_sample=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(output_ids[0].tolist() , SCREAMING_SNAKE_CASE__ )
32
0
from __future__ import annotations import math def lowerCAmelCase_ ( snake_case_ ): if num <= 0: _A : int = f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(snake_case_ ) _A : Optional[Any] = [True] * (num + 1) _A : Optional[Any] = [] _A : Optional[Any] = 2 _A : Tuple = int(math.sqrt(snake_case_ ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(snake_case_ ) # Set multiples of start be False for i in range(start * start,num + 1,snake_case_ ): if sieve[i] is True: _A : Union[str, Any] = False start += 1 for j in range(end + 1,num + 1 ): if sieve[j] is True: prime.append(snake_case_ ) return prime if __name__ == "__main__": print(prime_sieve(int(input("Enter a positive integer: ").strip())))
26
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase_ : Optional[int] = { 'facebook/mask2former-swin-small-coco-instance': ( 'https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase_ : List[str] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = '''mask2former''' snake_case__ : Any = ['''swin'''] snake_case__ : str = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 1_0 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_5_5 , SCREAMING_SNAKE_CASE__ : int = 1_0_0 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : int , ) -> List[Any]: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) a_ : Dict = CONFIG_MAPPING['swin']( image_size=2_2_4 , in_channels=3 , patch_size=4 , embed_dim=9_6 , depths=[2, 2, 1_8, 2] , num_heads=[3, 6, 1_2, 2_4] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): a_ : Any = backbone_config.pop('model_type' ) a_ : Optional[Any] = CONFIG_MAPPING[backbone_model_type] a_ : List[str] = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # 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 Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) a_ : Dict = backbone_config a_ : List[str] = feature_size a_ : List[str] = mask_feature_size a_ : int = hidden_dim a_ : Dict = encoder_feedforward_dim a_ : str = activation_function a_ : List[str] = encoder_layers a_ : List[str] = decoder_layers a_ : Dict = num_attention_heads a_ : str = dropout a_ : Tuple = dim_feedforward a_ : List[str] = pre_norm a_ : Optional[int] = enforce_input_projection a_ : Any = common_stride a_ : Optional[int] = ignore_value a_ : int = num_queries a_ : Tuple = no_object_weight a_ : Dict = class_weight a_ : Optional[int] = mask_weight a_ : Optional[int] = dice_weight a_ : str = train_num_points a_ : List[str] = oversample_ratio a_ : List[Any] = importance_sample_ratio a_ : Any = init_std a_ : Union[str, Any] = init_xavier_std a_ : Union[str, Any] = use_auxiliary_loss a_ : Dict = feature_strides a_ : List[str] = output_auxiliary_logits a_ : Dict = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def SCREAMING_SNAKE_CASE ( cls : str , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict[str, any]: a_ : Optional[int] = copy.deepcopy(self.__dict__ ) a_ : List[Any] = self.backbone_config.to_dict() a_ : Optional[Any] = self.__class__.model_type return output
32
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase : Optional[Any] = logging.get_logger(__name__) __lowercase : Tuple = { 'microsoft/markuplm-base': 'https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json', 'microsoft/markuplm-large': 'https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json', } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "markuplm" def __init__( self , __a=3_0522 , __a=768 , __a=12 , __a=12 , __a=3072 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=2 , __a=0.02 , __a=1E-1_2 , __a=0 , __a=0 , __a=2 , __a=256 , __a=1024 , __a=216 , __a=1001 , __a=32 , __a=50 , __a="absolute" , __a=True , __a=None , **__a , ): '''simple docstring''' super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a , ) __a : List[str] = vocab_size __a : Optional[Any] = hidden_size __a : Optional[int] = num_hidden_layers __a : Optional[Any] = num_attention_heads __a : Optional[int] = hidden_act __a : Union[str, Any] = intermediate_size __a : str = hidden_dropout_prob __a : List[Any] = attention_probs_dropout_prob __a : Dict = max_position_embeddings __a : Optional[Any] = type_vocab_size __a : Union[str, Any] = initializer_range __a : Optional[Any] = layer_norm_eps __a : Optional[Any] = position_embedding_type __a : Optional[int] = use_cache __a : Optional[Any] = classifier_dropout # additional properties __a : int = max_depth __a : Union[str, Any] = max_xpath_tag_unit_embeddings __a : str = max_xpath_subs_unit_embeddings __a : Optional[Any] = tag_pad_id __a : Dict = subs_pad_id __a : List[str] = xpath_unit_hidden_size
27
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Union[str, Any] = { 'google/switch-base-8': 'https://huggingface.co/google/switch-base-8/blob/main/config.json', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : List[str] = '''switch_transformers''' snake_case__ : Optional[int] = ['''past_key_values'''] snake_case__ : Optional[Any] = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int]=3_2_1_2_8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6_4 , SCREAMING_SNAKE_CASE__ : List[str]=2_0_4_8 , SCREAMING_SNAKE_CASE__ : Dict=6_4 , SCREAMING_SNAKE_CASE__ : List[Any]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3 , SCREAMING_SNAKE_CASE__ : Tuple=1_2 , SCREAMING_SNAKE_CASE__ : Tuple=8 , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.01 , SCREAMING_SNAKE_CASE__ : str="float32" , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_2 , SCREAMING_SNAKE_CASE__ : Dict=1_2_8 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=1E-6 , SCREAMING_SNAKE_CASE__ : Dict=0.001 , SCREAMING_SNAKE_CASE__ : Any=0.001 , SCREAMING_SNAKE_CASE__ : Optional[int]=1.0 , SCREAMING_SNAKE_CASE__ : Any="relu" , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : Optional[int]=1 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: a_ : Optional[int] = vocab_size a_ : List[str] = d_model a_ : Tuple = d_kv a_ : Optional[Any] = d_ff a_ : List[Any] = num_sparse_encoder_layers a_ : Any = num_layers a_ : str = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a_ : List[Any] = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: a_ : Optional[int] = self.num_layers // self.num_sparse_encoder_layers else: a_ : List[Any] = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: a_ : Union[str, Any] = self.num_decoder_layers // self.num_sparse_decoder_layers else: a_ : List[str] = self.num_decoder_layers # HACK: this will create 0 sparse layers a_ : Dict = num_heads a_ : str = num_experts a_ : Any = expert_capacity a_ : List[Any] = router_bias a_ : str = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""" ) a_ : Optional[int] = router_dtype a_ : int = router_ignore_padding_tokens a_ : Any = relative_attention_num_buckets a_ : List[str] = relative_attention_max_distance a_ : Optional[Any] = dropout_rate a_ : Tuple = layer_norm_epsilon a_ : Dict = initializer_factor a_ : Any = feed_forward_proj a_ : Tuple = use_cache a_ : str = add_router_probs a_ : Optional[int] = router_z_loss_coef a_ : List[str] = router_aux_loss_coef a_ : int = self.feed_forward_proj.split('-' ) a_ : int = act_info[-1] a_ : Optional[int] = act_info[0] == 'gated' if len(SCREAMING_SNAKE_CASE__ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE__ ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a_ : Any = 'gelu_new' super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
32
0
'''simple docstring''' import inspect import unittest from transformers import ConvNextConfig 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_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Any=1_3 , UpperCamelCase__ : Optional[int]=3_2 , UpperCamelCase__ : Any=3 , UpperCamelCase__ : Tuple=4 , UpperCamelCase__ : str=[1_0, 2_0, 3_0, 4_0] , UpperCamelCase__ : str=[2, 2, 3, 2] , UpperCamelCase__ : Dict=True , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : str=3_7 , UpperCamelCase__ : Union[str, Any]="gelu" , UpperCamelCase__ : Dict=1_0 , UpperCamelCase__ : Union[str, Any]=0.0_2 , UpperCamelCase__ : int=["stage2", "stage3", "stage4"] , UpperCamelCase__ : List[str]=[2, 3, 4] , UpperCamelCase__ : Any=None , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = num_channels UpperCamelCase = num_stages UpperCamelCase = hidden_sizes UpperCamelCase = depths UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = num_labels UpperCamelCase = initializer_range UpperCamelCase = out_features UpperCamelCase = out_indices UpperCamelCase = scope def A ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase = self.get_config() return config, pixel_values, labels def A ( self : List[str] ): """simple docstring""" return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def A ( self : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : str ): """simple docstring""" UpperCamelCase = ConvNextModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() UpperCamelCase = model(UpperCamelCase__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def A ( self : List[str] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : int ): """simple docstring""" UpperCamelCase = ConvNextForImageClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() UpperCamelCase = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A ( self : Tuple , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple , UpperCamelCase__ : str ): """simple docstring""" UpperCamelCase = ConvNextBackbone(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() UpperCamelCase = model(UpperCamelCase__ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None UpperCamelCase = None UpperCamelCase = ConvNextBackbone(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() UpperCamelCase = model(UpperCamelCase__ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def A ( self : Any ): """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( _a , _a , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE = ( {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False def A ( self : Tuple ): """simple docstring""" UpperCamelCase = ConvNextModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ , hidden_size=3_7 ) def A ( self : List[str] ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A ( self : Optional[int] ): """simple docstring""" return @unittest.skip(reason='ConvNext does not use inputs_embeds' ) def A ( self : List[str] ): """simple docstring""" pass @unittest.skip(reason='ConvNext does not support input and output embeddings' ) def A ( self : List[Any] ): """simple docstring""" pass @unittest.skip(reason='ConvNext does not use feedforward chunking' ) def A ( self : Optional[int] ): """simple docstring""" pass def A ( self : Any ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(UpperCamelCase__ ) UpperCamelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) def A ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def A ( self : Tuple ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*UpperCamelCase__ ) def A ( self : Optional[Any] ): """simple docstring""" def check_hidden_states_output(UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Tuple ): UpperCamelCase = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() with torch.no_grad(): UpperCamelCase = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) UpperCamelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase = self.model_tester.num_stages self.assertEqual(len(UpperCamelCase__ ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def A ( self : Dict ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ ) @slow def A ( self : Dict ): """simple docstring""" for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = ConvNextModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def __lowerCamelCase ( ) -> Any: """simple docstring""" UpperCamelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" @cached_property def A ( self : Optional[Any] ): """simple docstring""" return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224' ) if is_vision_available() else None @slow def A ( self : List[Any] ): """simple docstring""" UpperCamelCase = ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224' ).to(UpperCamelCase__ ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(images=UpperCamelCase__ , return_tensors='pt' ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): UpperCamelCase = model(**UpperCamelCase__ ) # verify the logits UpperCamelCase = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) UpperCamelCase = torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1] ).to(UpperCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase__ , atol=1E-4 ) ) @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase , _a ): """simple docstring""" _SCREAMING_SNAKE_CASE = (ConvNextBackbone,) if is_torch_available() else () _SCREAMING_SNAKE_CASE = ConvNextConfig _SCREAMING_SNAKE_CASE = False def A ( self : Tuple ): """simple docstring""" UpperCamelCase = ConvNextModelTester(self )
28
# 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. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase_ : Tuple = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyรจ': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmรฅl': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''facebook/nllb-200-distilled-600M''' snake_case__ : Union[str, Any] = ( '''This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ''' '''be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ''' '''which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ''' '''plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.''' ) snake_case__ : Optional[Any] = '''translator''' snake_case__ : Tuple = AutoTokenizer snake_case__ : Union[str, Any] = AutoModelForSeqaSeqLM snake_case__ : Dict = LANGUAGE_CODES snake_case__ : str = ['''text''', '''text''', '''text'''] snake_case__ : Tuple = ['''text'''] def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: if src_lang not in self.lang_to_code: raise ValueError(F"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(F"""{tgt_lang} is not a supported language.""" ) a_ : str = self.lang_to_code[src_lang] a_ : Any = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors='pt' , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Tuple ) -> Any: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
32
0
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 __UpperCAmelCase = object() # For specifying empty leaf dict `{}` __UpperCAmelCase = object() def lowercase__ ( __snake_case : List[Any] , __snake_case : Optional[int] ): '''simple docstring''' UpperCAmelCase_ : Tuple = tuple((re.compile(x + '$' ) for x in qs) ) for i in range(len(__snake_case ) - len(__snake_case ) + 1 ): UpperCAmelCase_ : Any = [x.match(__snake_case ) for x, y in zip(__snake_case , ks[i:] )] if matches and all(__snake_case ): return True return False def lowercase__ ( __snake_case : Optional[Any] ): '''simple docstring''' def replace(__snake_case : List[Any] , __snake_case : Optional[Any] ): for rule, replacement in rules: if _match(__snake_case , __snake_case ): return replacement return val return replace def lowercase__ ( ): '''simple docstring''' 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 lowercase__ ( __snake_case : List[Any] ): '''simple docstring''' UpperCAmelCase_ : Dict = _get_partition_rules() UpperCAmelCase_ : Optional[Any] = _replacement_rules(__snake_case ) UpperCAmelCase_ : Dict = {k: _unmatched for k in flatten_dict(__snake_case )} UpperCAmelCase_ : Optional[Any] = {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 ) )
29
UpperCAmelCase_ : Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def SCREAMING_SNAKE_CASE_ ( __A : int , __A : int , __A : int ) -> str: """simple docstring""" assert len(str(__A ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: a_ : List[str] = year // 1_00 a_ : Optional[int] = (5 * (century % 4) + 2) % 7 a_ : List[str] = year % 1_00 a_ : str = centurian % 12 a_ : List[str] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 a_ : Any = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) a_ : Any = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
32
0
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging __a = logging.get_logger(__name__) class lowercase__: """simple docstring""" a :str a :str = None @staticmethod def _lowercase ( ) -> Optional[int]: raise NotImplementedError def _lowercase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , **SCREAMING_SNAKE_CASE_ : int ) -> Union[str, Any]: raise NotImplementedError def _lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Optional[int]: raise NotImplementedError def _lowercase ( self : Tuple ) -> Union[str, Any]: if not self.is_available(): raise RuntimeError( f'''You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.''' ) @classmethod def _lowercase ( cls : Dict ) -> Dict: return f'''`pip install {cls.pip_package or cls.name}`''' class lowercase__( UpperCAmelCase ): """simple docstring""" a :Any = 'optuna' @staticmethod def _lowercase ( ) -> str: return is_optuna_available() def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , **SCREAMING_SNAKE_CASE_ : int ) -> str: return run_hp_search_optuna(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Dict , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> str: return default_hp_space_optuna(SCREAMING_SNAKE_CASE_ ) class lowercase__( UpperCAmelCase ): """simple docstring""" a :Tuple = 'ray' a :Optional[int] = '\'ray[tune]\'' @staticmethod def _lowercase ( ) -> Any: return is_ray_available() def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , **SCREAMING_SNAKE_CASE_ : Any ) -> str: return run_hp_search_ray(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> int: return default_hp_space_ray(SCREAMING_SNAKE_CASE_ ) class lowercase__( UpperCAmelCase ): """simple docstring""" a :List[str] = 'sigopt' @staticmethod def _lowercase ( ) -> Union[str, Any]: return is_sigopt_available() def _lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , **SCREAMING_SNAKE_CASE_ : List[Any] ) -> Union[str, Any]: return run_hp_search_sigopt(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Tuple: return default_hp_space_sigopt(SCREAMING_SNAKE_CASE_ ) class lowercase__( UpperCAmelCase ): """simple docstring""" a :str = 'wandb' @staticmethod def _lowercase ( ) -> str: return is_wandb_available() def _lowercase ( self : str , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , **SCREAMING_SNAKE_CASE_ : List[Any] ) -> Tuple: return run_hp_search_wandb(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Any ) -> List[Any]: return default_hp_space_wandb(SCREAMING_SNAKE_CASE_ ) __a = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def a ( ): '''simple docstring''' lowercase_ = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(snake_case__ ) > 0: lowercase_ = available_backends[0].name if len(snake_case__ ) > 1: logger.info( F'''{len(snake_case__ )} hyperparameter search backends available. Using {name} as the default.''' ) return name raise RuntimeError( '''No hyperparameter search backend available.\n''' + '''\n'''.join( F''' - To install {backend.name} run {backend.pip_install()}''' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
30
import math import flax.linen as nn import jax.numpy as jnp def SCREAMING_SNAKE_CASE_ ( __A : jnp.ndarray , __A : int , __A : float = 1 , __A : float = 1 , __A : float = 1.0e4 , __A : bool = False , __A : float = 1.0 , ) -> jnp.ndarray: """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F"""Embedding dimension {embedding_dim} should be even""" a_ : int = float(embedding_dim // 2 ) a_ : str = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) a_ : Optional[int] = min_timescale * jnp.exp(jnp.arange(__A , dtype=jnp.floataa ) * -log_timescale_increment ) a_ : Optional[int] = jnp.expand_dims(__A , 1 ) * jnp.expand_dims(__A , 0 ) # scale embeddings a_ : str = scale * emb if flip_sin_to_cos: a_ : str = jnp.concatenate([jnp.cos(__A ), jnp.sin(__A )] , axis=1 ) else: a_ : Any = jnp.concatenate([jnp.sin(__A ), jnp.cos(__A )] , axis=1 ) a_ : Optional[int] = jnp.reshape(__A , [jnp.shape(__A )[0], embedding_dim] ) return signal class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Optional[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_1' )(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = nn.silu(SCREAMING_SNAKE_CASE__ ) a_ : str = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_2' )(SCREAMING_SNAKE_CASE__ ) return temb class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : bool = False snake_case__ : float = 1 @nn.compact def __call__( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Tuple: return get_sinusoidal_embeddings( SCREAMING_SNAKE_CASE__ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
32
0
'''simple docstring''' def UpperCamelCase_ ( ) -> str: """simple docstring""" _UpperCAmelCase : Dict = 0 for i in range(1 , 1_001 ): total += i**i return str(_UpperCAmelCase )[-10:] if __name__ == "__main__": print(solution())
31
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) UpperCAmelCase_ : str = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCAmelCase_ : Optional[Any] = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) UpperCAmelCase_ : int = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) UpperCAmelCase_ : Union[str, Any] = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) UpperCAmelCase_ : Union[str, Any] = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) UpperCAmelCase_ : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase_ : Dict = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase_ : Dict = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase_ : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase_ : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase_ : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[Any] = FLAX_MODEL_MAPPING UpperCAmelCase_ : Tuple = auto_class_update(FlaxAutoModel) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Any = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[Any] = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase_ : Union[str, Any] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase_ : Optional[int] = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase_ : str = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[str] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase_ : Tuple = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Dict = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase_ : int = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[int] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase_ : Dict = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase_ : str = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[Any] = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase_ : Tuple = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[int] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase_ : Union[str, Any] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
32
0
"""simple docstring""" from collections.abc import Sequence def lowercase ( __snake_case : Sequence[float] , __snake_case : bool = False ): if not arr: return 0 lowercase_ : List[str] = 0 if allow_empty_subarrays else float('''-inf''' ) lowercase_ : Any = 0.0 for num in arr: lowercase_ : Any = max(0 if allow_empty_subarrays else num , curr_sum + num ) lowercase_ : List[Any] = max(__snake_case , __snake_case ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() __A : List[Any] = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(F"""{max_subarray_sum(nums) = }""")
33
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): snake_case__ : Any = GPTSanJapaneseTokenizer snake_case__ : Tuple = False snake_case__ : str = {'''do_clean_text''': False, '''add_prefix_space''': False} def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: super().setUp() # fmt: off a_ : Union[str, Any] = ['ใ“ใ‚“', 'ใ“ใ‚“ใซ', 'ใซใกใฏ', 'ใฐใ‚“ใฏ', 'ไธ–็•Œ,ใ”บ็•Œ', 'ใ€', 'ใ€‚', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on a_ : int = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # ๐Ÿ˜€ a_ : List[Any] = {'unk_token': '<unk>'} a_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) a_ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE__ ) ) def SCREAMING_SNAKE_CASE ( self : List[str] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> int: kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> int: a_ : Optional[int] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : List[str] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Dict: a_ , a_ : Union[str, Any] = self.get_input_output_texts(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) a_ : Dict = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) return text, ids def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: a_ : List[str] = self.get_tokenizer() # Testing tokenization a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ€€ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚' a_ : Optional[int] = ['ใ“ใ‚“', 'ใซใกใฏ', 'ใ€', 'ไธ–็•Œ', 'ใ€‚', '<SP>', 'ใ“ใ‚“', 'ใฐใ‚“ใฏ', 'ใ€', 'ใ”บ็•Œ', 'ใ€‚'] a_ : Dict = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids without special tokens a_ : Tuple = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] a_ : List[Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids with special tokens a_ : int = tokens + [tokenizer.unk_token] a_ : int = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9] a_ : Tuple = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: a_ : Union[str, Any] = self.get_tokenizer() # Testing tokenization a_ : Dict = 'ใ“ใ‚“ใซใกใฏใ€<|bagoftoken|>ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€<|bagoftoken|>ใ”บ็•Œใ€‚' a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚' a_ : Any = tokenizer.encode(SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : str ) -> Dict: a_ : Tuple = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' a_ : int = 'ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : Dict = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' a_ : Optional[int] = tokenizer.encode(prefix_text + input_text ) a_ : Any = tokenizer.encode('' , prefix_text=prefix_text + input_text ) a_ : Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) a_ : str = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: a_ : Tuple = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization a_ : str = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' a_ : List[str] = 'ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : str = len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 a_ : Tuple = len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 a_ : Optional[Any] = [1] + [0] * (len_prefix + len_text + 1) a_ : Optional[Any] = [1] * (len_prefix + len_text + 1) + [0] a_ : Tuple = [1] + [1] * (len_prefix) + [0] * (len_text + 1) a_ : List[str] = tokenizer(prefix_text + input_text ).token_type_ids a_ : Union[str, Any] = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids a_ : Any = tokenizer(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: a_ : str = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) a_ : Optional[int] = tokenizer.encode('ใ‚ใƒณใ„ใƒฏ' ) a_ : Dict = tokenizer.encode('' , prefix_text='ใ‚ใƒณใ„ใƒฏ' ) a_ : Dict = tokenizer.encode('ใ„ใƒฏ' , prefix_text='ใ‚ใƒณ' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: a_ : List[str] = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) a_ : Optional[Any] = [['ๆญฆ็”ฐไฟก็Ž„', 'ใฏใ€'], ['็น”็”ฐไฟก้•ท', 'ใฎ้…ไธ‹ใฎใ€']] a_ : List[str] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) a_ : Dict = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) # fmt: off a_ : List[Any] = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]] a_ : Any = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] a_ : List[Any] = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: # tokenizer has no padding token pass
32
0
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def snake_case_ (_a : Dict , _a : Optional[int] , _a : Dict , _a : Optional[Any] , _a : int ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file UpperCAmelCase = TapasConfig.from_json_file(_a ) # set absolute/relative position embeddings parameter UpperCAmelCase = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": UpperCAmelCase = TapasForQuestionAnswering(config=_a ) elif task == "WTQ": # run_task_main.py hparams UpperCAmelCase = 4 UpperCAmelCase = True # hparam_utils.py hparams UpperCAmelCase = 0.66_4694 UpperCAmelCase = 0.20_7951 UpperCAmelCase = 0.12_1194 UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = 0.035_2513 UpperCAmelCase = TapasForQuestionAnswering(config=_a ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams UpperCAmelCase = 4 UpperCAmelCase = False # hparam_utils.py hparams UpperCAmelCase = 36.4519 UpperCAmelCase = 0.90_3421 UpperCAmelCase = 222.088 UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = 0.76_3141 UpperCAmelCase = TapasForQuestionAnswering(config=_a ) elif task == "TABFACT": UpperCAmelCase = TapasForSequenceClassification(config=_a ) elif task == "MLM": UpperCAmelCase = TapasForMaskedLM(config=_a ) elif task == "INTERMEDIATE_PRETRAINING": UpperCAmelCase = TapasModel(config=_a ) else: raise ValueError(F"Task {task} not supported." ) print(F"Building PyTorch model from configuration: {config}" ) # Load weights from tf checkpoint load_tf_weights_in_tapas(_a , _a , _a ) # Save pytorch-model (weights and configuration) print(F"Save PyTorch model to {pytorch_dump_path}" ) model.save_pretrained(_a ) # Save tokenizer files print(F"Save tokenizer files to {pytorch_dump_path}" ) UpperCAmelCase = TapasTokenizer(vocab_file=tf_checkpoint_path[:-1_0] + '''vocab.txt''' , model_max_length=5_1_2 ) tokenizer.save_pretrained(_a ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": A =argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS 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 =parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
34
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, logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Union[str, Any] = ['''pixel_values'''] def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, int]] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 2_5_5 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) a_ : str = size if size is not None else {'shortest_edge': 2_5_6} a_ : Any = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) a_ : Dict = crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4} a_ : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE__ ) a_ : List[str] = do_resize a_ : Dict = size a_ : Optional[Any] = resample a_ : Optional[int] = do_center_crop a_ : Dict = crop_size a_ : int = do_rescale a_ : int = rescale_factor a_ : Tuple = do_normalize a_ : int = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN a_ : Tuple = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> np.ndarray: a_ : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) a_ : Tuple = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=size['shortest_edge'] , default_to_square=SCREAMING_SNAKE_CASE__ ) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> np.ndarray: a_ : str = get_size_dict(SCREAMING_SNAKE_CASE__ ) return center_crop(SCREAMING_SNAKE_CASE__ , size=(size['height'], size['width']) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> np.ndarray: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[float] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> Union[str, Any]: a_ : List[str] = do_resize if do_resize is not None else self.do_resize a_ : Dict = size if size is not None else self.size a_ : Dict = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = resample if resample is not None else self.resample a_ : List[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop a_ : int = crop_size if crop_size is not None else self.crop_size a_ : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE__ ) a_ : Dict = do_rescale if do_rescale is not None else self.do_rescale a_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor a_ : Any = do_normalize if do_normalize is not None else self.do_normalize a_ : str = image_mean if image_mean is not None else self.image_mean a_ : Dict = image_std if image_std is not None else self.image_std a_ : Optional[int] = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. a_ : Any = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: a_ : str = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_center_crop: a_ : int = [self.center_crop(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: a_ : Optional[Any] = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: a_ : List[Any] = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] a_ : Dict = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] a_ : Tuple = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
32
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __a = { "configuration_bloom": ["BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP", "BloomConfig", "BloomOnnxConfig"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = ["BloomTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ "BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST", "BloomForCausalLM", "BloomModel", "BloomPreTrainedModel", "BloomForSequenceClassification", "BloomForTokenClassification", "BloomForQuestionAnswering", ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys __a = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
35
def SCREAMING_SNAKE_CASE_ ( __A : list[int] , __A : str ) -> list[int]: """simple docstring""" a_ : Any = int(__A ) # Initialize Result a_ : Tuple = [] # Traverse through all denomination for denomination in reversed(__A ): # Find denominations while int(__A ) >= int(__A ): total_value -= int(__A ) answer.append(__A ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = [] UpperCAmelCase_ : Union[str, Any] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase_ : List[Any] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(F'Denomination {i}: ').strip())) UpperCAmelCase_ : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase_ : List[Any] = [1, 2, 5, 10, 20, 50, 100, 500, 2000] UpperCAmelCase_ : str = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(F'Following is minimal change for {value}: ') UpperCAmelCase_ : Optional[Any] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
32
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/config.json", "umberto-commoncrawl-cased-v1": ( "https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json" ), "umberto-wikipedia-uncased-v1": ( "https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json" ), } class UpperCAmelCase_ ( a): lowerCamelCase__ = 'camembert' def __init__( self, __a=3_0522, __a=768, __a=12, __a=12, __a=3072, __a="gelu", __a=0.1, __a=0.1, __a=512, __a=2, __a=0.02, __a=1E-12, __a=1, __a=0, __a=2, __a="absolute", __a=True, __a=None, **__a, ): '''simple docstring''' super().__init__(pad_token_id=__a, bos_token_id=__a, eos_token_id=__a, **__a) _lowerCAmelCase : Optional[Any] = vocab_size _lowerCAmelCase : Optional[int] = hidden_size _lowerCAmelCase : Union[str, Any] = num_hidden_layers _lowerCAmelCase : Optional[int] = num_attention_heads _lowerCAmelCase : Tuple = hidden_act _lowerCAmelCase : Tuple = intermediate_size _lowerCAmelCase : Optional[Any] = hidden_dropout_prob _lowerCAmelCase : Tuple = attention_probs_dropout_prob _lowerCAmelCase : List[Any] = max_position_embeddings _lowerCAmelCase : Optional[Any] = type_vocab_size _lowerCAmelCase : str = initializer_range _lowerCAmelCase : List[Any] = layer_norm_eps _lowerCAmelCase : int = position_embedding_type _lowerCAmelCase : Dict = use_cache _lowerCAmelCase : Dict = classifier_dropout class UpperCAmelCase_ ( a): @property def snake_case__ ( self): '''simple docstring''' if self.task == "multiple-choice": _lowerCAmelCase : Optional[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), ])
36
import flax.linen as nn import jax import jax.numpy as jnp class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : str ) -> int: a_ : Dict = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: a_ , a_ , a_ , a_ : Union[str, Any] = hidden_states.shape a_ : List[str] = jax.image.resize( SCREAMING_SNAKE_CASE__ , shape=(batch, height * 2, width * 2, channels) , method='nearest' , ) a_ : Any = self.conv(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: a_ : Optional[int] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]: # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim # hidden_states = jnp.pad(hidden_states, pad_width=pad) a_ : str = self.conv(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : int = None snake_case__ : float = 0.0 snake_case__ : bool = None snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: a_ : List[str] = self.in_channels if self.out_channels is None else self.out_channels a_ : Optional[int] = nn.GroupNorm(num_groups=3_2 , epsilon=1E-5 ) a_ : Any = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) a_ : Optional[int] = nn.Dense(SCREAMING_SNAKE_CASE__ , dtype=self.dtype ) a_ : Union[str, Any] = nn.GroupNorm(num_groups=3_2 , epsilon=1E-5 ) a_ : int = nn.Dropout(self.dropout_prob ) a_ : Optional[Any] = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) a_ : List[str] = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut a_ : List[Any] = None if use_nin_shortcut: a_ : Union[str, Any] = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(1, 1) , strides=(1, 1) , padding='VALID' , dtype=self.dtype , ) def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any]=True ) -> int: a_ : List[Any] = hidden_states a_ : Any = self.norma(SCREAMING_SNAKE_CASE__ ) a_ : Any = nn.swish(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = self.conva(SCREAMING_SNAKE_CASE__ ) a_ : int = self.time_emb_proj(nn.swish(SCREAMING_SNAKE_CASE__ ) ) a_ : List[str] = jnp.expand_dims(jnp.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , 1 ) a_ : Optional[int] = hidden_states + temb a_ : List[str] = self.norma(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = nn.swish(SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.dropout(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = self.conva(SCREAMING_SNAKE_CASE__ ) if self.conv_shortcut is not None: a_ : List[str] = self.conv_shortcut(SCREAMING_SNAKE_CASE__ ) return hidden_states + residual
32
0
'''simple docstring''' from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING _lowerCAmelCase = logging.get_logger(__name__) @add_end_docstrings(SCREAMING_SNAKE_CASE_ ) class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' def __init__( self ,*__UpperCAmelCase ,**__UpperCAmelCase ) -> int: super().__init__(*__UpperCAmelCase ,**__UpperCAmelCase ) requires_backends(self ,"""vision""" ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == """tf""" else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def UpperCAmelCase_ ( self ,__UpperCAmelCase=None ) -> int: lowerCAmelCase__ : Dict = {} if top_k is not None: lowerCAmelCase__ : Optional[int] = top_k return {}, {}, postprocess_params def __call__( self ,__UpperCAmelCase ,**__UpperCAmelCase ) -> Union[str, Any]: return super().__call__(__UpperCAmelCase ,**__UpperCAmelCase ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> Any: lowerCAmelCase__ : List[str] = load_image(__UpperCAmelCase ) lowerCAmelCase__ : Any = self.image_processor(images=__UpperCAmelCase ,return_tensors=self.framework ) return model_inputs def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> List[Any]: lowerCAmelCase__ : Any = self.model(**__UpperCAmelCase ) return model_outputs def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase=5 ) -> Any: if top_k > self.model.config.num_labels: lowerCAmelCase__ : Union[str, Any] = self.model.config.num_labels if self.framework == "pt": lowerCAmelCase__ : Union[str, Any] = model_outputs.logits.softmax(-1 )[0] lowerCAmelCase__ , lowerCAmelCase__ : Dict = probs.topk(__UpperCAmelCase ) elif self.framework == "tf": lowerCAmelCase__ : Any = stable_softmax(model_outputs.logits ,axis=-1 )[0] lowerCAmelCase__ : List[Any] = tf.math.top_k(__UpperCAmelCase ,k=__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(F"""Unsupported framework: {self.framework}""" ) lowerCAmelCase__ : Tuple = scores.tolist() lowerCAmelCase__ : int = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(__UpperCAmelCase ,__UpperCAmelCase )]
37
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. UpperCAmelCase_ : Dict = {'LayoutLMv2Config', 'LayoutLMv3Config'} @is_pipeline_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): snake_case__ : List[str] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING snake_case__ : Optional[Any] = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: snake_case__ : str = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: snake_case__ : List[Any] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: a_ : List[Any] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' ) a_ : int = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) a_ : Tuple = text_classifier('This is great !' , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}] ) a_ : List[str] = text_classifier(['This is great !', 'This is bad'] , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], ] , ) a_ : Tuple = text_classifier('This is great !' , top_k=1 ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) # Legacy behavior a_ : Union[str, Any] = text_classifier('This is great !' , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) a_ : List[str] = text_classifier('This is great !' , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}]] ) a_ : int = text_classifier(['This is great !', 'Something else'] , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], ] , ) a_ : str = text_classifier(['This is great !', 'Something else'] , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ {'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_0', 'score': 0.504}, ] , ) @require_torch def SCREAMING_SNAKE_CASE ( self : int ) -> Dict: import torch a_ : List[Any] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' , device=torch.device('cpu' ) , ) a_ : Any = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) @require_tf def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: a_ : List[str] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='tf' ) a_ : Optional[int] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) @slow @require_torch def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: a_ : List[str] = pipeline('text-classification' ) a_ : Dict = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 1.0}] ) a_ : Union[str, Any] = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'NEGATIVE', 'score': 1.0}] ) a_ : Tuple = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 0.988}] ) @slow @require_tf def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: a_ : Dict = pipeline('text-classification' , framework='tf' ) a_ : Optional[Any] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 1.0}] ) a_ : int = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'NEGATIVE', 'score': 1.0}] ) a_ : Optional[int] = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 0.988}] ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: a_ : Optional[Any] = TextClassificationPipeline(model=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ ) return text_classifier, ["HuggingFace is in", "This is another test"] def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: a_ : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 a_ : Union[str, Any] = 'HuggingFace is in' a_ : int = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) a_ : Union[str, Any] = ['HuggingFace is in ', 'Paris is in France'] a_ : int = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}, {'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) self.assertTrue(outputs[1]['label'] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format a_ : List[Any] = text_classifier(SCREAMING_SNAKE_CASE__ , top_k=SCREAMING_SNAKE_CASE__ ) a_ : Dict = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [[{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] * N, [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] * N] , ) a_ : int = {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'} a_ : Optional[int] = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , {'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )} , ) self.assertTrue(outputs['label'] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. a_ : Any = [['HuggingFace is in ', 'Paris is in France']] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): text_classifier(SCREAMING_SNAKE_CASE__ ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility a_ : Tuple = text_classifier([[['HuggingFace is in ', 'Paris is in France']]] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )
32
0
import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Dict , __lowerCamelCase : Any=0.01 , __lowerCamelCase : Optional[Any]=1_000 ): UpperCamelCase :Dict = p_stop UpperCamelCase :Dict = max_length def __iter__( self : List[str] ): UpperCamelCase :Optional[Any] = 0 UpperCamelCase :int = False while not stop and count < self.max_length: yield count count += 1 UpperCamelCase :List[Any] = random.random() < self.p_stop class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _A ( self : List[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any]=False , __lowerCamelCase : Optional[Any]=True ): UpperCamelCase :str = [ BatchSamplerShard(__lowerCamelCase , 2 , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) for i in range(2 ) ] UpperCamelCase :Union[str, Any] = [list(__lowerCamelCase ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(__lowerCamelCase ) for shard in batch_sampler_shards] , [len(__lowerCamelCase ) for e in expected] ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) def _A ( self : List[str] ): # Check the shards when the dataset is a round multiple of total batch size. UpperCamelCase :Optional[Any] = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Any = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. UpperCamelCase :Tuple = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[Any] = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :str = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. UpperCamelCase :Any = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Dict = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Union[str, Any] = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :List[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. UpperCamelCase :Union[str, Any] = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Optional[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Optional[Any] = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Dict = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is very small. UpperCamelCase :List[Any] = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :int = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) UpperCamelCase :Union[str, Any] = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) def _A ( self : Dict ): # Check the shards when the dataset is a round multiple of batch size. UpperCamelCase :Any = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :str = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) UpperCamelCase :List[str] = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size. UpperCamelCase :Optional[int] = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) UpperCamelCase :Tuple = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Any = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. UpperCamelCase :int = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Optional[int] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Optional[Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. UpperCamelCase :Tuple = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :List[str] = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) UpperCamelCase :Dict = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :int = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) def _A ( self : Dict ): # Check the shards when the dataset is a round multiple of total batch size. UpperCamelCase :str = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Optional[Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :Optional[Any] = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. UpperCamelCase :Union[str, Any] = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Any = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :int = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :str = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. UpperCamelCase :Tuple = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Any = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :Optional[Any] = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. UpperCamelCase :List[Any] = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :str = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. UpperCamelCase :Union[str, Any] = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [[[0, 1]], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :Optional[Any] = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) UpperCamelCase :Optional[int] = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) def _A ( self : List[Any] ): # Check the shards when the dataset is a round multiple of batch size. UpperCamelCase :Optional[int] = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :int = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :Any = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size. UpperCamelCase :int = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :Union[str, Any] = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Any = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. UpperCamelCase :str = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :List[Any] = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :int = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :str = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. UpperCamelCase :List[str] = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :str = [[[0, 1]], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) UpperCamelCase :List[str] = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Tuple = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) def _A ( self : Dict ): UpperCamelCase :Tuple = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]] UpperCamelCase :int = [BatchSamplerShard(__lowerCamelCase , 2 , __lowerCamelCase , even_batches=__lowerCamelCase ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) , 3 ) self.assertEqual(len(batch_sampler_shards[1] ) , 2 ) self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [12, 13]] ) self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 10, 11]] ) def _A ( self : Optional[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Any , __lowerCamelCase : List[str]=False , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : Tuple=False ): random.seed(__lowerCamelCase ) UpperCamelCase :Any = list(__lowerCamelCase ) UpperCamelCase :Union[str, Any] = [ IterableDatasetShard( __lowerCamelCase , batch_size=__lowerCamelCase , drop_last=__lowerCamelCase , num_processes=__lowerCamelCase , process_index=__lowerCamelCase , split_batches=__lowerCamelCase , ) for i in range(__lowerCamelCase ) ] UpperCamelCase :Union[str, Any] = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(__lowerCamelCase ) iterable_dataset_lists.append(list(__lowerCamelCase ) ) UpperCamelCase :List[str] = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size UpperCamelCase :Dict = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) self.assertTrue(len(__lowerCamelCase ) % shard_batch_size == 0 ) UpperCamelCase :List[str] = [] for idx in range(0 , len(__lowerCamelCase ) , __lowerCamelCase ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(__lowerCamelCase ) < len(__lowerCamelCase ): reference += reference self.assertListEqual(__lowerCamelCase , reference[: len(__lowerCamelCase )] ) def _A ( self : int ): UpperCamelCase :Optional[int] = 42 UpperCamelCase :Optional[Any] = RandomIterableDataset() self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) # Edge case with a very small dataset UpperCamelCase :Optional[int] = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) def _A ( self : Tuple ): UpperCamelCase :Union[str, Any] = BatchSampler(range(16 ) , batch_size=4 , drop_last=__lowerCamelCase ) UpperCamelCase :Any = SkipBatchSampler(__lowerCamelCase , 2 ) self.assertListEqual(list(__lowerCamelCase ) , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def _A ( self : Optional[Any] ): UpperCamelCase :Tuple = SkipDataLoader(list(range(16 ) ) , batch_size=4 , skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def _A ( self : int ): UpperCamelCase :Dict = DataLoader(list(range(16 ) ) , batch_size=4 ) UpperCamelCase :Union[str, Any] = skip_first_batches(__lowerCamelCase , num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def _A ( self : Any ): UpperCamelCase :Union[str, Any] = DataLoaderShard(list(range(16 ) ) , batch_size=4 ) for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) def _A ( self : List[str] ): Accelerator() UpperCamelCase :Optional[int] = DataLoaderDispatcher(range(16 ) , batch_size=4 ) for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
38
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : str = 'T5Config' def SCREAMING_SNAKE_CASE_ ( __A : jnp.array , __A : int , __A : int ) -> jnp.ndarray: """simple docstring""" a_ : Dict = jnp.zeros_like(__A ) a_ : Dict = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) a_ : str = shifted_input_ids.at[:, 0].set(__A ) a_ : int = jnp.where(shifted_input_ids == -1_00 , __A , __A ) return shifted_input_ids class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[Any] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[str] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = '''mt5''' snake_case__ : Union[str, Any] = MTaConfig
32
0
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _a = '''https://www.indeed.co.in/jobs?q=mobile+app+development&l=''' def __A ( __lowerCAmelCase = "mumbai" )-> Generator[tuple[str, str], None, None]: """simple docstring""" _UpperCAmelCase = BeautifulSoup(requests.get(url + location ).content , 'html.parser' ) # This attribute finds out all the specifics listed in a job for job in soup.find_all('div' , attrs={'data-tn-component': 'organicJob'} ): _UpperCAmelCase = job.find('a' , attrs={'data-tn-element': 'jobTitle'} ).text.strip() _UpperCAmelCase = job.find('span' , {'class': 'company'} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('''Bangalore'''), 1): print(F'''Job {i:>2} is {job[0]} at {job[1]}''')
39
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent UpperCAmelCase_ : Any = {'UserAgent': UserAgent().random} def SCREAMING_SNAKE_CASE_ ( __A : Optional[int] ) -> dict: """simple docstring""" a_ : Tuple = script.contents[0] a_ : int = json.loads(data[data.find('{"config"' ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: a_ : Tuple = F"""https://www.instagram.com/{username}/""" a_ : Optional[Any] = self.get_json() def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> dict: a_ : Any = requests.get(self.url , headers=SCREAMING_SNAKE_CASE__ ).text a_ : Dict = BeautifulSoup(SCREAMING_SNAKE_CASE__ , 'html.parser' ).find_all('script' ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Union[str, Any] ) -> str: return F"""{self.__class__.__name__}('{self.username}')""" def __str__( self : Optional[int] ) -> str: return F"""{self.fullname} ({self.username}) is {self.biography}""" @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: return self.user_data["username"] @property def SCREAMING_SNAKE_CASE ( self : str ) -> str: return self.user_data["full_name"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> str: return self.user_data["biography"] @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: return self.user_data["business_email"] @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: return self.user_data["external_url"] @property def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return self.user_data["edge_followed_by"]["count"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> int: return self.user_data["edge_follow"]["count"] @property def SCREAMING_SNAKE_CASE ( self : str ) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: return self.user_data["profile_pic_url_hd"] @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> bool: return self.user_data["is_verified"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.user_data["is_private"] def SCREAMING_SNAKE_CASE_ ( __A : str = "github" ) -> None: """simple docstring""" import os if os.environ.get('CI' ): return # test failing on GitHub Actions a_ : int = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 1_50 assert instagram_user.number_of_followers > 12_00_00 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith('https://instagram.' ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase_ : Union[str, Any] = InstagramUser('github') print(instagram_user) print(F'{instagram_user.number_of_posts = }') print(F'{instagram_user.number_of_followers = }') print(F'{instagram_user.number_of_followings = }') print(F'{instagram_user.email = }') print(F'{instagram_user.website = }') print(F'{instagram_user.profile_picture_url = }') print(F'{instagram_user.is_verified = }') print(F'{instagram_user.is_private = }')
32
0
"""simple docstring""" def lowercase ( A_ , A_ )-> float: '''simple docstring''' if mass < 0: raise ValueError("The mass of a body cannot be negative" ) return 0.5 * mass * abs(A_ ) * abs(A_ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
40
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Tuple = ['''image_processor''', '''tokenizer'''] snake_case__ : Union[str, Any] = '''CLIPImageProcessor''' snake_case__ : Dict = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : int ) -> Any: a_ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , SCREAMING_SNAKE_CASE__ , ) a_ : Tuple = kwargs.pop('feature_extractor' ) a_ : Tuple = 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 : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE__ : str ) -> Optional[Any]: if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: a_ : List[str] = self.tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if images is not None: a_ : Dict = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None and images is not None: a_ : Dict = 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 SCREAMING_SNAKE_CASE ( self : Any , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[Any]: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: a_ : str = self.tokenizer.model_input_names a_ : Tuple = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def SCREAMING_SNAKE_CASE ( self : str ) -> str: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , SCREAMING_SNAKE_CASE__ , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , SCREAMING_SNAKE_CASE__ , ) return self.image_processor
32
0
'''simple docstring''' from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets _A : Union[str, Any] ='''\ @inproceedings{wang2019glue, title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding}, author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.}, note={In the Proceedings of ICLR.}, year={2019} } ''' _A : Optional[Any] ='''\ GLUE, the General Language Understanding Evaluation benchmark (https://gluebenchmark.com/) is a collection of resources for training, evaluating, and analyzing natural language understanding systems. ''' _A : Optional[int] =''' Compute GLUE evaluation metric associated to each GLUE dataset. Args: predictions: list of predictions to score. Each translation should be tokenized into a list of tokens. references: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. Returns: depending on the GLUE subset, one or several of: "accuracy": Accuracy "f1": F1 score "pearson": Pearson Correlation "spearmanr": Spearman Correlation "matthews_correlation": Matthew Correlation Examples: >>> glue_metric = datasets.load_metric(\'glue\', \'sst2\') # \'sst2\' or any of ["mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> glue_metric = datasets.load_metric(\'glue\', \'mrpc\') # \'mrpc\' or \'qqp\' >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> glue_metric = datasets.load_metric(\'glue\', \'stsb\') >>> references = [0., 1., 2., 3., 4., 5.] >>> predictions = [0., 1., 2., 3., 4., 5.] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print({"pearson": round(results["pearson"], 2), "spearmanr": round(results["spearmanr"], 2)}) {\'pearson\': 1.0, \'spearmanr\': 1.0} >>> glue_metric = datasets.load_metric(\'glue\', \'cola\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : Optional[int] = simple_accuracy(UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : Any = float(fa_score(y_true=UpperCamelCase , y_pred=UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> str: lowerCamelCase__ : int = float(pearsonr(UpperCamelCase , UpperCamelCase )[0] ) lowerCamelCase__ : Tuple = float(spearmanr(UpperCamelCase , UpperCamelCase )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowercase ( datasets.Metric ): def lowerCamelCase_ ( self: Optional[Any] ): if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """ """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ), """references""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" , ) def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: str , UpperCamelCase__: Optional[Any] ): if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(UpperCamelCase__ , UpperCamelCase__ )} elif self.config_name == "stsb": return pearson_and_spearman(UpperCamelCase__ , UpperCamelCase__ ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(UpperCamelCase__ , UpperCamelCase__ ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(UpperCamelCase__ , UpperCamelCase__ )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """ """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" )
41
from __future__ import annotations UpperCAmelCase_ : Tuple = [] def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] , __A : int , __A : int ) -> bool: """simple docstring""" for i in range(len(__A ) ): if board[row][i] == 1: return False for i in range(len(__A ) ): if board[i][column] == 1: return False for i, j in zip(range(__A , -1 , -1 ) , range(__A , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(__A , -1 , -1 ) , range(__A , len(__A ) ) ): if board[i][j] == 1: return False return True def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] , __A : int ) -> bool: """simple docstring""" if row >= len(__A ): solution.append(__A ) printboard(__A ) print() return True for i in range(len(__A ) ): if is_safe(__A , __A , __A ): a_ : Any = 1 solve(__A , row + 1 ) a_ : Tuple = 0 return False def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] ) -> None: """simple docstring""" for i in range(len(__A ) ): for j in range(len(__A ) ): if board[i][j] == 1: print('Q' , end=' ' ) else: print('.' , end=' ' ) print() # n=int(input("The no. of queens")) UpperCAmelCase_ : List[str] = 8 UpperCAmelCase_ : str = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
32
0
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer lowercase : Optional[int] = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase : Optional[Any] = "\n Examples:\n ```py\n >>> from PIL import Image\n >>> import torch\n >>> from diffusers import DiffusionPipeline\n >>> from diffusers.utils import export_to_gif, load_image\n\n >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n >>> repo = \"openai/shap-e-img2img\"\n >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n >>> pipe = pipe.to(device)\n\n >>> guidance_scale = 3.0\n >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n >>> image = load_image(image_url).convert(\"RGB\")\n\n >>> images = pipe(\n ... image,\n ... guidance_scale=guidance_scale,\n ... num_inference_steps=64,\n ... frame_size=256,\n ... ).images\n\n >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")\n ```\n" @dataclass class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = 42 class __UpperCAmelCase ( _lowerCamelCase ): def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): """simple docstring""" super().__init__() self.register_modules( prior=lowerCAmelCase_ , image_encoder=lowerCAmelCase_ , image_processor=lowerCAmelCase_ , scheduler=lowerCAmelCase_ , renderer=lowerCAmelCase_ , ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" if latents is None: _snake_case = randn_tensor(lowerCAmelCase_ , generator=lowerCAmelCase_ , device=lowerCAmelCase_ , dtype=lowerCAmelCase_ ) else: if latents.shape != shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}' ) _snake_case = latents.to(lowerCAmelCase_ ) _snake_case = latents * scheduler.init_noise_sigma return latents def lowerCamelCase ( self , lowerCAmelCase_=0 ): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) _snake_case = torch.device(F'cuda:{gpu_id}' ) _snake_case = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCAmelCase_ , lowerCAmelCase_ ) @property def lowerCamelCase ( self ): """simple docstring""" if self.device != torch.device('meta' ) or not hasattr(self.image_encoder , '_hf_hook' ): return self.device for module in self.image_encoder.modules(): if ( hasattr(lowerCAmelCase_ , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(image[0] , torch.Tensor ): _snake_case = torch.cat(lowerCAmelCase_ , axis=0 ) if image[0].ndim == 4 else torch.stack(lowerCAmelCase_ , axis=0 ) if not isinstance(lowerCAmelCase_ , torch.Tensor ): _snake_case = self.image_processor(lowerCAmelCase_ , return_tensors='pt' ).pixel_values[0].unsqueeze(0 ) _snake_case = image.to(dtype=self.image_encoder.dtype , device=lowerCAmelCase_ ) _snake_case = self.image_encoder(lowerCAmelCase_ )['last_hidden_state'] _snake_case = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 _snake_case = image_embeds.repeat_interleave(lowerCAmelCase_ , dim=0 ) if do_classifier_free_guidance: _snake_case = torch.zeros_like(lowerCAmelCase_ ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _snake_case = torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(lowerCAmelCase_ ) def __call__( self , lowerCAmelCase_ , lowerCAmelCase_ = 1 , lowerCAmelCase_ = 25 , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = 4.0 , lowerCAmelCase_ = 64 , lowerCAmelCase_ = "pil" , lowerCAmelCase_ = True , ): """simple docstring""" if isinstance(lowerCAmelCase_ , PIL.Image.Image ): _snake_case = 1 elif isinstance(lowerCAmelCase_ , torch.Tensor ): _snake_case = image.shape[0] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): _snake_case = len(lowerCAmelCase_ ) else: raise ValueError( F'`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(lowerCAmelCase_ )}' ) _snake_case = self._execution_device _snake_case = batch_size * num_images_per_prompt _snake_case = guidance_scale > 1.0 _snake_case = self._encode_image(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # prior self.scheduler.set_timesteps(lowerCAmelCase_ , device=lowerCAmelCase_ ) _snake_case = self.scheduler.timesteps _snake_case = self.prior.config.num_embeddings _snake_case = self.prior.config.embedding_dim _snake_case = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim _snake_case = latents.reshape(latents.shape[0] , lowerCAmelCase_ , lowerCAmelCase_ ) for i, t in enumerate(self.progress_bar(lowerCAmelCase_ ) ): # expand the latents if we are doing classifier free guidance _snake_case = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _snake_case = self.scheduler.scale_model_input(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = self.prior( lowerCAmelCase_ , timestep=lowerCAmelCase_ , proj_embedding=lowerCAmelCase_ , ).predicted_image_embedding # remove the variance _snake_case , _snake_case = noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: _snake_case , _snake_case = noise_pred.chunk(2 ) _snake_case = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) _snake_case = self.scheduler.step( lowerCAmelCase_ , timestep=lowerCAmelCase_ , sample=lowerCAmelCase_ , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=lowerCAmelCase_ ) _snake_case = [] for i, latent in enumerate(lowerCAmelCase_ ): print() _snake_case = self.renderer.decode( latent[None, :] , lowerCAmelCase_ , size=lowerCAmelCase_ , ray_batch_size=40_96 , n_coarse_samples=64 , n_fine_samples=1_28 , ) images.append(lowerCAmelCase_ ) _snake_case = torch.stack(lowerCAmelCase_ ) if output_type not in ["np", "pil"]: raise ValueError(F'Only the output types `pil` and `np` are supported not output_type={output_type}' ) _snake_case = images.cpu().numpy() if output_type == "pil": _snake_case = [self.numpy_to_pil(lowerCAmelCase_ ) for image in images] # Offload last model to CPU if hasattr(self , 'final_offload_hook' ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=lowerCAmelCase_ )
42
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def SCREAMING_SNAKE_CASE_ ( ) -> Any: """simple docstring""" a_ : Optional[Any] = HfArgumentParser(__A ) a_ : Optional[int] = parser.parse_args_into_dataclasses()[0] a_ : List[Any] = TensorFlowBenchmark(args=__A ) try: a_ : List[str] = parser.parse_args_into_dataclasses()[0] except ValueError as e: a_ : Dict = 'Arg --no_{0} is no longer used, please use --no-{0} instead.' a_ : Dict = ' '.join(str(__A ).split(' ' )[:-1] ) a_ : int = '' a_ : int = eval(str(__A ).split(' ' )[-1] ) a_ : Any = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__A ) if len(__A ) > 0: a_ : str = full_error_msg + begin_error_msg + str(__A ) raise ValueError(__A ) benchmark.run() if __name__ == "__main__": main()
32
0
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self , __lowercase , __lowercase) -> Optional[int]: __UpperCamelCase :Any = params __UpperCamelCase :Optional[int] = np.array(__lowercase) __UpperCamelCase :Union[str, Any] = np.array([len(__lowercase) for t in data]) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , __lowercase) -> Union[str, Any]: return (self.token_ids[index], self.lengths[index]) def __len__( self) -> Optional[Any]: return len(self.lengths) def UpperCamelCase__ ( self) -> List[Any]: assert len(self.token_ids) == len(self.lengths) assert all(self.lengths[i] == len(self.token_ids[i]) for i in range(len(self.lengths))) def UpperCamelCase__ ( self) -> Dict: __UpperCamelCase :Optional[Any] = self.params.max_model_input_size __UpperCamelCase :int = self.lengths > max_len logger.info(f"""Splitting {sum(__lowercase)} too long sequences.""") def divide_chunks(__lowercase , __lowercase): return [l[i : i + n] for i in range(0 , len(__lowercase) , __lowercase)] __UpperCamelCase :str = [] __UpperCamelCase :Union[str, Any] = [] if self.params.mlm: __UpperCamelCase , __UpperCamelCase :Any = self.params.special_tok_ids['''cls_token'''], self.params.special_tok_ids['''sep_token'''] else: __UpperCamelCase , __UpperCamelCase :str = self.params.special_tok_ids['''bos_token'''], self.params.special_tok_ids['''eos_token'''] for seq_, len_ in zip(self.token_ids , self.lengths): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_) new_lengths.append(len_) else: __UpperCamelCase :Any = [] for sub_s in divide_chunks(seq_ , max_len - 2): if sub_s[0] != cls_id: __UpperCamelCase :Dict = np.insert(__lowercase , 0 , __lowercase) if sub_s[-1] != sep_id: __UpperCamelCase :Optional[int] = np.insert(__lowercase , len(__lowercase) , __lowercase) assert len(__lowercase) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(__lowercase) new_tok_ids.extend(__lowercase) new_lengths.extend([len(__lowercase) for l in sub_seqs]) __UpperCamelCase :str = np.array(__lowercase) __UpperCamelCase :str = np.array(__lowercase) def UpperCamelCase__ ( self) -> Dict: __UpperCamelCase :Union[str, Any] = len(self) __UpperCamelCase :List[Any] = self.lengths > 11 __UpperCamelCase :Optional[Any] = self.token_ids[indices] __UpperCamelCase :List[str] = self.lengths[indices] __UpperCamelCase :Optional[Any] = len(self) logger.info(f"""Remove {init_size - new_size} too short (<=11 tokens) sequences.""") def UpperCamelCase__ ( self) -> Union[str, Any]: if "unk_token" not in self.params.special_tok_ids: return else: __UpperCamelCase :Dict = self.params.special_tok_ids['''unk_token'''] __UpperCamelCase :int = len(self) __UpperCamelCase :str = np.array([np.count_nonzero(a == unk_token_id) for a in self.token_ids]) __UpperCamelCase :Dict = (unk_occs / self.lengths) < 0.5 __UpperCamelCase :str = self.token_ids[indices] __UpperCamelCase :int = self.lengths[indices] __UpperCamelCase :List[Any] = len(self) logger.info(f"""Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).""") def UpperCamelCase__ ( self) -> int: if not self.params.is_master: return logger.info(f"""{len(self)} sequences""") # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def UpperCamelCase__ ( self , __lowercase) -> List[Any]: __UpperCamelCase :List[str] = [t[0] for t in batch] __UpperCamelCase :Optional[int] = [t[1] for t in batch] assert len(__lowercase) == len(__lowercase) # Max for paddings __UpperCamelCase :List[Any] = max(__lowercase) # Pad token ids if self.params.mlm: __UpperCamelCase :Optional[int] = self.params.special_tok_ids['''pad_token'''] else: __UpperCamelCase :Any = self.params.special_tok_ids['''unk_token'''] __UpperCamelCase :str = [list(t.astype(__lowercase)) + [pad_idx] * (max_seq_len_ - len(__lowercase)) for t in token_ids] assert len(tk_) == len(__lowercase) assert all(len(__lowercase) == max_seq_len_ for t in tk_) __UpperCamelCase :Optional[int] = torch.tensor(tk_) # (bs, max_seq_len_) __UpperCamelCase :List[Any] = torch.tensor(__lowercase) # (bs) return tk_t, lg_t
43
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): snake_case__ : Optional[Any] = TextToVideoSDPipeline snake_case__ : Optional[int] = TEXT_TO_IMAGE_PARAMS snake_case__ : str = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. snake_case__ : Optional[Any] = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: torch.manual_seed(0 ) a_ : Optional[int] = UNetaDConditionModel( block_out_channels=(3_2, 6_4, 6_4, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D') , up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D') , cross_attention_dim=3_2 , attention_head_dim=4 , ) a_ : int = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) a_ : int = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) a_ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=5_1_2 , ) a_ : Dict = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) a_ : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> List[str]: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): a_ : Dict = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: a_ : Optional[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) a_ : int = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'pt', } return inputs def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator a_ : Dict = self.get_dummy_components() a_ : str = TextToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) a_ : Dict = 'np' a_ : Dict = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames a_ : int = frames[0][-3:, -3:, -1] assert frames[0].shape == (6_4, 6_4, 3) a_ : Union[str, Any] = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=3E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def SCREAMING_SNAKE_CASE ( self : Any ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=1E-2 ) @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: pass @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: pass @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: pass def SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: return super().test_progress_bar() @slow @skip_mps class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: a_ : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy' ) a_ : Any = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) a_ : Optional[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) a_ : Optional[Any] = pipe.to('cuda' ) a_ : Any = 'Spiderman is surfing' a_ : List[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) a_ : Optional[Any] = pipe(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2_5 , output_type='pt' ).frames a_ : str = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2 def SCREAMING_SNAKE_CASE ( self : Any ) -> Any: a_ : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy' ) a_ : Tuple = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) a_ : Tuple = pipe.to('cuda' ) a_ : Any = 'Spiderman is surfing' a_ : List[str] = torch.Generator(device='cpu' ).manual_seed(0 ) a_ : List[Any] = pipe(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type='pt' ).frames a_ : List[str] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2
32
0
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _a : Tuple = { 'configuration_informer': [ 'INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : List[str] = [ 'INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'InformerForPrediction', 'InformerModel', 'InformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys _a : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
44
import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): # TODO: is there an appropriate internal test set? snake_case__ : Any = '''ssube/stable-diffusion-x4-upscaler-onnx''' def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : int=0 ) -> Tuple: a_ : Union[str, Any] = floats_tensor((1, 3, 1_2_8, 1_2_8) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ) a_ : Dict = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: a_ : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.get_dummy_inputs() a_ : int = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : Tuple = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : List[Any] = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: a_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : int = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : List[str] = self.get_dummy_inputs() a_ : List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : str = np.array( [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: a_ : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : Optional[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.get_dummy_inputs() a_ : Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : Optional[Any] = np.array( [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: a_ : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : int = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = self.get_dummy_inputs() a_ : Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : int = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: a_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : Optional[int] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = self.get_dummy_inputs() a_ : List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : Union[str, Any] = np.array( [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: a_ : List[str] = ort.SessionOptions() a_ : int = False return options def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: a_ : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) a_ : int = init_image.resize((1_2_8, 1_2_8) ) # using the PNDM scheduler by default a_ : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Tuple = 'A fantasy landscape, trending on artstation' a_ : str = torch.manual_seed(0 ) a_ : List[str] = pipe( prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=1_0 , generator=SCREAMING_SNAKE_CASE__ , output_type='np' , ) a_ : Dict = output.images a_ : Any = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) a_ : str = np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: a_ : Dict = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) a_ : List[str] = init_image.resize((1_2_8, 1_2_8) ) a_ : Dict = LMSDiscreteScheduler.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , subfolder='scheduler' ) a_ : Union[str, Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , scheduler=SCREAMING_SNAKE_CASE__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Any = 'A fantasy landscape, trending on artstation' a_ : Tuple = torch.manual_seed(0 ) a_ : Optional[Any] = pipe( prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=2_0 , generator=SCREAMING_SNAKE_CASE__ , output_type='np' , ) a_ : str = output.images a_ : List[Any] = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) a_ : Tuple = np.array( [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
32
0
"""simple docstring""" import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py lowercase_ = "." if __name__ == "__main__": lowercase_ = os.path.join(REPO_PATH, "utils/documentation_tests.txt") lowercase_ = [] lowercase_ = [] with open(doctest_file_path) as fp: for line in fp: lowercase_ = line.strip() lowercase_ = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: lowercase_ = "\n".join(non_existent_paths) raise ValueError(F'''`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}''') if all_paths != sorted(all_paths): raise ValueError("Files in `utils/documentation_tests.txt` are not in alphabetical order.")
45
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> str: """simple docstring""" a_ : Tuple = [] for line in lines: a_ : Any = re.sub(R'#.*' , '' , __A ) # remove comments if line: filtered_lines.append(__A ) a_ : Tuple = '\n'.join(__A ) # Make a hash from all this code a_ : Tuple = full_str.encode('utf-8' ) return shaaaa(__A ).hexdigest() # get importable module names and hash for caching UpperCAmelCase_ : List[Any] = { 'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), 'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), 'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), 'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), 'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), 'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), 'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), 'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions UpperCAmelCase_ : Dict = { '.csv': ('csv', {}), '.tsv': ('csv', {'sep': '\t'}), '.json': ('json', {}), '.jsonl': ('json', {}), '.parquet': ('parquet', {}), '.arrow': ('arrow', {}), '.txt': ('text', {}), } _EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) UpperCAmelCase_ : Optional[int] = {'imagefolder', 'audiofolder'} # Used to filter data files based on extensions given a module name UpperCAmelCase_ : Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('.zip') _MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')
32
0
"""simple docstring""" import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets SCREAMING_SNAKE_CASE__ = "\\n@inproceedings{snover-etal-2006-study,\n title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",\n author = \"Snover, Matthew and\n Dorr, Bonnie and\n Schwartz, Rich and\n Micciulla, Linnea and\n Makhoul, John\",\n booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",\n month = aug # \" 8-12\",\n year = \"2006\",\n address = \"Cambridge, Massachusetts, USA\",\n publisher = \"Association for Machine Translation in the Americas\",\n url = \"https://aclanthology.org/2006.amta-papers.25\",\n pages = \"223--231\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ = "\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n" SCREAMING_SNAKE_CASE__ = "\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n predictions (list of str): The system stream (a sequence of segments).\n references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n Only applies if `normalized = True`. Defaults to `False`.\n case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n 'score' (float): TER score (num_edits / sum_ref_lengths * 100)\n 'num_edits' (int): The cumulative number of edits\n 'ref_length' (float): The cumulative average reference length\n\nExamples:\n Example 1:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\",\n ... \"What did the TER metric user say to the developer?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n ... [\"Your jokes are...\", \"...TERrible\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}\n\n Example 2:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}\n\n Example 3:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... normalized=True,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}\n\n Example 4:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}\n\n Example 5:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\",\n ... \"What did the TER metric user say to the developer?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n ... [\"Your jokes are...\", \"...TERrible\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase ( datasets.Metric ): def _snake_case ( self ) -> Tuple: if version.parse(scb.__version__ ) < version.parse("""1.4.12""" ): raise ImportWarning( """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n""" """You can install it with `pip install \"sacrebleu>=1.4.12\"`.""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""http://www.cs.umd.edu/~snover/tercom/""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ), } ) , codebase_urls=["""https://github.com/mjpost/sacreBLEU#ter"""] , reference_urls=[ """https://github.com/jhclark/tercom""", ] , ) def _snake_case ( self , lowercase , lowercase , lowercase = False , lowercase = False , lowercase = False , lowercase = False , ) -> Optional[int]: lowerCAmelCase = len(references[0] ) if any(len(lowercase ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) lowerCAmelCase = [[refs[i] for refs in references] for i in range(lowercase )] lowerCAmelCase = TER( normalized=lowercase , no_punct=lowercase , asian_support=lowercase , case_sensitive=lowercase , ) lowerCAmelCase = sb_ter.corpus_score(lowercase , lowercase ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
46
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Optional[int] = '''convbert''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=3_0_5_2_2 , SCREAMING_SNAKE_CASE__ : Dict=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[int]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : Any=1E-12 , SCREAMING_SNAKE_CASE__ : int=1 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=9 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : Dict=None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> Any: super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) a_ : Tuple = vocab_size a_ : List[str] = hidden_size a_ : List[str] = num_hidden_layers a_ : Dict = num_attention_heads a_ : Optional[int] = intermediate_size a_ : int = hidden_act a_ : Dict = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : str = max_position_embeddings a_ : List[str] = type_vocab_size a_ : List[str] = initializer_range a_ : Tuple = layer_norm_eps a_ : Optional[int] = embedding_size a_ : List[Any] = head_ratio a_ : List[Any] = conv_kernel_size a_ : Tuple = num_groups a_ : Tuple = classifier_dropout class SCREAMING_SNAKE_CASE__ ( lowercase__ ): @property def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": a_ : Tuple = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a_ : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
32
0
'''simple docstring''' import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _lowerCAmelCase ( _UpperCamelCase : Optional[int] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Optional[int] ) -> Optional[Any]: """simple docstring""" if openai_config_file == "": _SCREAMING_SNAKE_CASE =OpenAIGPTConfig() else: _SCREAMING_SNAKE_CASE =OpenAIGPTConfig.from_json_file(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =OpenAIGPTModel(_UpperCamelCase ) # Load weights from numpy load_tf_weights_in_openai_gpt(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # Save pytorch-model _SCREAMING_SNAKE_CASE =pytorch_dump_folder_path + '/' + WEIGHTS_NAME _SCREAMING_SNAKE_CASE =pytorch_dump_folder_path + '/' + CONFIG_NAME print(f"Save PyTorch model to {pytorch_weights_dump_path}" ) torch.save(model.state_dict() , _UpperCamelCase ) print(f"Save configuration file to {pytorch_config_dump_path}" ) with open(_UpperCamelCase , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": lowerCamelCase : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( "--openai_checkpoint_folder_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--openai_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained OpenAI model. \n" "This specifies the model architecture." ), ) lowerCamelCase : str = parser.parse_args() convert_openai_checkpoint_to_pytorch( args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path )
47
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE__ : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str=1_3 , SCREAMING_SNAKE_CASE__ : Optional[int]=7 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=9_9 , SCREAMING_SNAKE_CASE__ : str=2_4 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6 , SCREAMING_SNAKE_CASE__ : Optional[int]=3_7 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 , SCREAMING_SNAKE_CASE__ : List[str]=1_6 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Tuple=1_0_0_0 , ) -> str: a_ : Optional[Any] = parent a_ : List[str] = batch_size a_ : List[str] = seq_length a_ : str = is_training a_ : str = use_input_mask a_ : int = use_token_type_ids a_ : List[str] = use_labels a_ : Optional[int] = vocab_size a_ : Any = hidden_size a_ : int = num_hidden_layers a_ : List[str] = num_attention_heads a_ : str = intermediate_size a_ : Union[str, Any] = hidden_act a_ : List[str] = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : int = max_position_embeddings a_ : Tuple = type_vocab_size a_ : Optional[Any] = type_sequence_label_size a_ : Tuple = initializer_range a_ : Dict = num_labels a_ : str = scope a_ : Optional[int] = range_bbox def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a_ : int = bbox[i, j, 3] a_ : str = bbox[i, j, 1] a_ : List[str] = t if bbox[i, j, 2] < bbox[i, j, 0]: a_ : Tuple = bbox[i, j, 2] a_ : List[str] = bbox[i, j, 0] a_ : Union[str, Any] = t a_ : List[Any] = None if self.use_input_mask: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) a_ : List[Any] = None if self.use_token_type_ids: a_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : int = None a_ : Tuple = None if self.use_labels: a_ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : Optional[int] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> str: a_ : Any = LiltModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Any = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> int: a_ : Any = self.num_labels a_ : str = LiltForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> str: a_ : Union[str, Any] = LiltForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : List[str] = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , start_positions=SCREAMING_SNAKE_CASE__ , end_positions=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: a_ : int = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : List[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'bbox': bbox, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Union[str, Any] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) snake_case__ : str = ( { '''feature-extraction''': LiltModel, '''question-answering''': LiltForQuestionAnswering, '''text-classification''': LiltForSequenceClassification, '''token-classification''': LiltForTokenClassification, '''zero-shot''': LiltForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ) -> int: return True def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: a_ : str = LiltModelTester(self ) a_ : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: a_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a_ : List[str] = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: a_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: a_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : List[Any] = LiltModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: a_ : List[str] = LiltModel.from_pretrained('SCUT-DLVCLab/lilt-roberta-en-base' ).to(SCREAMING_SNAKE_CASE__ ) a_ : str = torch.tensor([[1, 2]] , device=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): a_ : str = model(input_ids=SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = torch.Size([1, 2, 7_6_8] ) a_ : int = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=SCREAMING_SNAKE_CASE__ , ) self.assertTrue(outputs.last_hidden_state.shape , SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) )
32
0
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 SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[str] = 'โ–' SCREAMING_SNAKE_CASE__ : Any = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE__ : Dict = { 'vocab_file': { 'google/reformer-crime-and-punishment': ( 'https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model' ) } } SCREAMING_SNAKE_CASE__ : List[Any] = { 'google/reformer-crime-and-punishment': 524288, } class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : Any = VOCAB_FILES_NAMES lowerCamelCase_ : List[Any] = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ : Optional[Any] = ["""input_ids""", """attention_mask"""] def __init__( self , UpperCamelCase__ , UpperCamelCase__="</s>" , UpperCamelCase__="<unk>" , UpperCamelCase__=[] , UpperCamelCase__ = None , **UpperCamelCase__ , ) -> None: lowerCamelCase : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase__ , ) lowerCamelCase : str = vocab_file lowerCamelCase : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCamelCase__ ) @property def _lowercase ( self ) -> Dict: return self.sp_model.get_piece_size() def _lowercase ( self ) -> Dict[str, int]: lowerCamelCase : Optional[Any] = {self.convert_ids_to_tokens(UpperCamelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> str: lowerCamelCase : Optional[int] = self.__dict__.copy() lowerCamelCase : Dict = None return state def __setstate__( self , UpperCamelCase__ ) -> Union[str, Any]: lowerCamelCase : Any = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCamelCase : Any = {} lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowercase ( self , UpperCamelCase__ ) -> List[str]: return self.sp_model.encode(UpperCamelCase__ , out_type=UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ ) -> Union[str, Any]: return self.sp_model.piece_to_id(UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ ) -> int: if index < self.sp_model.get_piece_size(): lowerCamelCase : Dict = self.sp_model.IdToPiece(UpperCamelCase__ ) return token def _lowercase ( self , UpperCamelCase__ ) -> Dict: lowerCamelCase : Any = [] lowerCamelCase : str = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(UpperCamelCase__ ) + token lowerCamelCase : Union[str, Any] = [] else: current_sub_tokens.append(UpperCamelCase__ ) out_string += self.sp_model.decode(UpperCamelCase__ ) return out_string.strip() def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ = None ) -> Tuple[str]: if not os.path.isdir(UpperCamelCase__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase : Optional[int] = os.path.join( UpperCamelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCamelCase__ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCamelCase__ , "wb" ) as fi: lowerCamelCase : Tuple = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase__ ) return (out_vocab_file,)
48
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple=1_3 , SCREAMING_SNAKE_CASE__ : str=7 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=9_9 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_2 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Tuple=3_7 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=5_1_2 , SCREAMING_SNAKE_CASE__ : int=1_6 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> Any: a_ : Tuple = parent a_ : int = batch_size a_ : Tuple = seq_length a_ : List[Any] = is_training a_ : List[str] = use_token_type_ids a_ : Dict = use_labels a_ : Any = vocab_size a_ : List[str] = hidden_size a_ : Tuple = num_hidden_layers a_ : List[Any] = num_attention_heads a_ : Dict = intermediate_size a_ : Any = hidden_act a_ : List[str] = hidden_dropout_prob a_ : Tuple = attention_probs_dropout_prob a_ : Optional[Any] = max_position_embeddings a_ : List[Any] = type_vocab_size a_ : int = type_sequence_label_size a_ : List[Any] = initializer_range a_ : List[str] = num_labels a_ : Union[str, Any] = num_choices a_ : str = scope a_ : Tuple = self.vocab_size - 1 def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: a_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = None if self.use_token_type_ids: a_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : List[Any] = None a_ : Union[str, Any] = None a_ : List[Any] = None if self.use_labels: a_ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) a_ : Union[str, Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) a_ : List[str] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: a_ : Dict = OpenAIGPTModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , head_mask=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: a_ : str = OpenAIGPTLMHeadModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: a_ : int = OpenAIGPTDoubleHeadsModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Any = self.num_labels a_ : Dict = OpenAIGPTForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : Optional[Any] = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : Optional[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Tuple = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) snake_case__ : List[str] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly snake_case__ : Dict = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any=False ) -> List[str]: a_ : str = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": a_ : Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : str = inputs_dict['labels'] a_ : Optional[int] = inputs_dict['labels'] a_ : Optional[int] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: a_ : str = OpenAIGPTModelTester(self ) a_ : int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , n_embd=3_7 ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: a_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: a_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: a_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : str = OpenAIGPTModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: a_ : Dict = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt' ) model.to(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) # the president is a_ : Tuple = [ 4_8_1, 4_7_3_5, 5_4_4, 2_4_6, 9_6_3, 8_7_0, 7_6_2, 2_3_9, 2_4_4, 4_0_4_7_7, 2_4_4, 2_4_9, 7_1_9, 8_8_1, 4_8_7, 5_4_4, 2_4_0, 2_4_4, 6_0_3, 4_8_1, ] # the president is a very good man. " \n " i\'m sure he is, " said the a_ : Dict = model.generate(SCREAMING_SNAKE_CASE__ , do_sample=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(output_ids[0].tolist() , SCREAMING_SNAKE_CASE__ )
32
0
import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _A ( __UpperCAmelCase ,unittest.TestCase ): UpperCamelCase__ : Any = LEDTokenizer UpperCamelCase__ : str = LEDTokenizerFast UpperCamelCase__ : List[Any] = True def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' super().setUp() __a = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] __a = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE)))) __a = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] __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(__SCREAMING_SNAKE_CASE) + '''\n''') with open(self.merges_file , '''w''' , encoding='''utf-8''') as fp: fp.write('''\n'''.join(__SCREAMING_SNAKE_CASE)) def _lowerCamelCase ( self : str , **__SCREAMING_SNAKE_CASE : Dict): '''simple docstring''' kwargs.update(self.special_tokens_map) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : int , **__SCREAMING_SNAKE_CASE : int): '''simple docstring''' kwargs.update(self.special_tokens_map) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any]): '''simple docstring''' return "lower newer", "lower newer" @cached_property def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' return LEDTokenizer.from_pretrained('''allenai/led-base-16384''') @cached_property def _lowerCamelCase ( self : Any): '''simple docstring''' return LEDTokenizerFast.from_pretrained('''allenai/led-base-16384''') @require_torch def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' __a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] __a = [0, 250, 251, 17_818, 13, 39_186, 1_938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(__SCREAMING_SNAKE_CASE , max_length=len(__SCREAMING_SNAKE_CASE) , padding=__SCREAMING_SNAKE_CASE , return_tensors='''pt''') self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) self.assertEqual((2, 9) , batch.input_ids.shape) self.assertEqual((2, 9) , batch.attention_mask.shape) __a = batch.input_ids.tolist()[0] self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) @require_torch def _lowerCamelCase ( self : Union[str, Any]): '''simple docstring''' __a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , return_tensors='''pt''') self.assertIn('''input_ids''' , __SCREAMING_SNAKE_CASE) self.assertIn('''attention_mask''' , __SCREAMING_SNAKE_CASE) self.assertNotIn('''labels''' , __SCREAMING_SNAKE_CASE) self.assertNotIn('''decoder_attention_mask''' , __SCREAMING_SNAKE_CASE) @require_torch def _lowerCamelCase ( self : List[Any]): '''simple docstring''' __a = [ '''Summary of the text.''', '''Another summary.''', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(text_target=__SCREAMING_SNAKE_CASE , max_length=32 , padding='''max_length''' , return_tensors='''pt''') self.assertEqual(32 , targets['''input_ids'''].shape[1]) @require_torch def _lowerCamelCase ( self : Union[str, Any]): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer( ['''I am a small frog''' * 1_024, '''I am a small frog'''] , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , return_tensors='''pt''') self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) self.assertEqual(batch.input_ids.shape , (2, 5_122)) @require_torch def _lowerCamelCase ( self : List[Any]): '''simple docstring''' __a = ['''A long paragraph for summarization.'''] __a = [ '''Summary of the text.''', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(__SCREAMING_SNAKE_CASE , return_tensors='''pt''') __a = tokenizer(text_target=__SCREAMING_SNAKE_CASE , return_tensors='''pt''') __a = inputs['''input_ids'''] __a = targets['''input_ids'''] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item()) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item()) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item()) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item()) @require_torch def _lowerCamelCase ( self : Tuple): '''simple docstring''' for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = ['''Summary of the text.''', '''Another summary.'''] __a = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] __a = tokenizer(__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE) __a = [[0] * len(__SCREAMING_SNAKE_CASE) for x in encoded_output['''input_ids''']] __a = tokenizer.pad(__SCREAMING_SNAKE_CASE) self.assertSequenceEqual(outputs['''global_attention_mask'''] , __SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Dict): '''simple docstring''' pass def _lowerCamelCase ( self : Tuple): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'): __a = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) __a = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) __a = '''A, <mask> AllenNLP sentence.''' __a = tokenizer_r.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE) __a = tokenizer_p.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE) self.assertEqual(sum(tokens_r['''token_type_ids''']) , sum(tokens_p['''token_type_ids'''])) self.assertEqual( sum(tokens_r['''attention_mask''']) / len(tokens_r['''attention_mask''']) , sum(tokens_p['''attention_mask''']) / len(tokens_p['''attention_mask''']) , ) __a = tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids''']) __a = tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids''']) self.assertSequenceEqual(tokens_p['''input_ids'''] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2]) self.assertSequenceEqual(tokens_r['''input_ids'''] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2]) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ฤ Allen''', '''N''', '''LP''', '''ฤ sentence''', '''.''', '''</s>''']) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ฤ Allen''', '''N''', '''LP''', '''ฤ sentence''', '''.''', '''</s>'''])
49
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase_ : Optional[int] = { 'facebook/mask2former-swin-small-coco-instance': ( 'https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase_ : List[str] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = '''mask2former''' snake_case__ : Any = ['''swin'''] snake_case__ : str = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 1_0 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_5_5 , SCREAMING_SNAKE_CASE__ : int = 1_0_0 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : int , ) -> List[Any]: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) a_ : Dict = CONFIG_MAPPING['swin']( image_size=2_2_4 , in_channels=3 , patch_size=4 , embed_dim=9_6 , depths=[2, 2, 1_8, 2] , num_heads=[3, 6, 1_2, 2_4] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): a_ : Any = backbone_config.pop('model_type' ) a_ : Optional[Any] = CONFIG_MAPPING[backbone_model_type] a_ : List[str] = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # 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 Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) a_ : Dict = backbone_config a_ : List[str] = feature_size a_ : List[str] = mask_feature_size a_ : int = hidden_dim a_ : Dict = encoder_feedforward_dim a_ : str = activation_function a_ : List[str] = encoder_layers a_ : List[str] = decoder_layers a_ : Dict = num_attention_heads a_ : str = dropout a_ : Tuple = dim_feedforward a_ : List[str] = pre_norm a_ : Optional[int] = enforce_input_projection a_ : Any = common_stride a_ : Optional[int] = ignore_value a_ : int = num_queries a_ : Tuple = no_object_weight a_ : Dict = class_weight a_ : Optional[int] = mask_weight a_ : Optional[int] = dice_weight a_ : str = train_num_points a_ : List[str] = oversample_ratio a_ : List[Any] = importance_sample_ratio a_ : Any = init_std a_ : Union[str, Any] = init_xavier_std a_ : Union[str, Any] = use_auxiliary_loss a_ : Dict = feature_strides a_ : List[str] = output_auxiliary_logits a_ : Dict = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def SCREAMING_SNAKE_CASE ( cls : str , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict[str, any]: a_ : Optional[int] = copy.deepcopy(self.__dict__ ) a_ : List[Any] = self.backbone_config.to_dict() a_ : Optional[Any] = self.__class__.model_type return output
32
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : List[Any] = logging.get_logger(__name__) _UpperCAmelCase : Optional[int] = { """SCUT-DLVCLab/lilt-roberta-en-base""": ( """https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json""" ), } class lowerCAmelCase ( __UpperCamelCase ): UpperCAmelCase__ = """lilt""" def __init__( self : Dict , UpperCAmelCase : int=30522 , UpperCAmelCase : Tuple=768 , UpperCAmelCase : Optional[int]=12 , UpperCAmelCase : List[str]=12 , UpperCAmelCase : Union[str, Any]=3072 , UpperCAmelCase : Tuple="gelu" , UpperCAmelCase : Optional[int]=0.1 , UpperCAmelCase : List[str]=0.1 , UpperCAmelCase : Any=512 , UpperCAmelCase : List[str]=2 , UpperCAmelCase : str=0.0_2 , UpperCAmelCase : List[Any]=1e-12 , UpperCAmelCase : List[str]=0 , UpperCAmelCase : Union[str, Any]="absolute" , UpperCAmelCase : str=None , UpperCAmelCase : Optional[Any]=4 , UpperCAmelCase : Union[str, Any]=1024 , **UpperCAmelCase : str , ) -> Dict: super().__init__(pad_token_id=UpperCAmelCase , **UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = vocab_size lowerCamelCase__ : Dict = hidden_size lowerCamelCase__ : Tuple = num_hidden_layers lowerCamelCase__ : Optional[Any] = num_attention_heads lowerCamelCase__ : Tuple = hidden_act lowerCamelCase__ : Union[str, Any] = intermediate_size lowerCamelCase__ : List[Any] = hidden_dropout_prob lowerCamelCase__ : Union[str, Any] = attention_probs_dropout_prob lowerCamelCase__ : Optional[int] = max_position_embeddings lowerCamelCase__ : Tuple = type_vocab_size lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : Union[str, Any] = layer_norm_eps lowerCamelCase__ : Any = position_embedding_type lowerCamelCase__ : List[str] = classifier_dropout lowerCamelCase__ : int = channel_shrink_ratio lowerCamelCase__ : int = max_ad_position_embeddings
50
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Union[str, Any] = { 'google/switch-base-8': 'https://huggingface.co/google/switch-base-8/blob/main/config.json', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : List[str] = '''switch_transformers''' snake_case__ : Optional[int] = ['''past_key_values'''] snake_case__ : Optional[Any] = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int]=3_2_1_2_8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6_4 , SCREAMING_SNAKE_CASE__ : List[str]=2_0_4_8 , SCREAMING_SNAKE_CASE__ : Dict=6_4 , SCREAMING_SNAKE_CASE__ : List[Any]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3 , SCREAMING_SNAKE_CASE__ : Tuple=1_2 , SCREAMING_SNAKE_CASE__ : Tuple=8 , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.01 , SCREAMING_SNAKE_CASE__ : str="float32" , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_2 , SCREAMING_SNAKE_CASE__ : Dict=1_2_8 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=1E-6 , SCREAMING_SNAKE_CASE__ : Dict=0.001 , SCREAMING_SNAKE_CASE__ : Any=0.001 , SCREAMING_SNAKE_CASE__ : Optional[int]=1.0 , SCREAMING_SNAKE_CASE__ : Any="relu" , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : Optional[int]=1 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: a_ : Optional[int] = vocab_size a_ : List[str] = d_model a_ : Tuple = d_kv a_ : Optional[Any] = d_ff a_ : List[Any] = num_sparse_encoder_layers a_ : Any = num_layers a_ : str = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a_ : List[Any] = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: a_ : Optional[int] = self.num_layers // self.num_sparse_encoder_layers else: a_ : List[Any] = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: a_ : Union[str, Any] = self.num_decoder_layers // self.num_sparse_decoder_layers else: a_ : List[str] = self.num_decoder_layers # HACK: this will create 0 sparse layers a_ : Dict = num_heads a_ : str = num_experts a_ : Any = expert_capacity a_ : List[Any] = router_bias a_ : str = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""" ) a_ : Optional[int] = router_dtype a_ : int = router_ignore_padding_tokens a_ : Any = relative_attention_num_buckets a_ : List[str] = relative_attention_max_distance a_ : Optional[Any] = dropout_rate a_ : Tuple = layer_norm_epsilon a_ : Dict = initializer_factor a_ : Any = feed_forward_proj a_ : Tuple = use_cache a_ : str = add_router_probs a_ : Optional[int] = router_z_loss_coef a_ : List[str] = router_aux_loss_coef a_ : int = self.feed_forward_proj.split('-' ) a_ : int = act_info[-1] a_ : Optional[int] = act_info[0] == 'gated' if len(SCREAMING_SNAKE_CASE__ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE__ ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a_ : Any = 'gelu_new' super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
32
0
import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class __snake_case ( unittest.TestCase ): @parameterized.expand([(None,), ('''foo.json''',)]) def lowerCamelCase ( self : Optional[int] , _snake_case : Dict): """simple docstring""" UpperCAmelCase_ = GenerationConfig( do_sample=_snake_case , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_snake_case , config_name=_snake_case) UpperCAmelCase_ = GenerationConfig.from_pretrained(_snake_case , config_name=_snake_case) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , _snake_case) self.assertEqual(loaded_config.temperature , 0.7) self.assertEqual(loaded_config.length_penalty , 1.0) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50) self.assertEqual(loaded_config.max_length , 20) self.assertEqual(loaded_config.max_time , _snake_case) def lowerCamelCase ( self : Any): """simple docstring""" UpperCAmelCase_ = AutoConfig.from_pretrained('''gpt2''') UpperCAmelCase_ = GenerationConfig.from_model_config(_snake_case) UpperCAmelCase_ = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(_snake_case , _snake_case) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id) def lowerCamelCase ( self : Tuple): """simple docstring""" UpperCAmelCase_ = GenerationConfig() UpperCAmelCase_ = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } UpperCAmelCase_ = copy.deepcopy(_snake_case) UpperCAmelCase_ = generation_config.update(**_snake_case) # update_kwargs was not modified (no side effects) self.assertEqual(_snake_case , _snake_case) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024) # `.update()` returns a dictionary of unused kwargs self.assertEqual(_snake_case , {'''foo''': '''bar'''}) def lowerCamelCase ( self : Optional[Any]): """simple docstring""" UpperCAmelCase_ = GenerationConfig() UpperCAmelCase_ = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir: generation_config.save_pretrained(_snake_case) UpperCAmelCase_ = GenerationConfig.from_pretrained(_snake_case) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''') UpperCAmelCase_ = GenerationConfig.from_model_config(_snake_case) assert not hasattr(_snake_case , '''foo''') # no new kwargs should be initialized if from config def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" UpperCAmelCase_ = GenerationConfig() self.assertEqual(default_config.temperature , 1.0) self.assertEqual(default_config.do_sample , _snake_case) self.assertEqual(default_config.num_beams , 1) UpperCAmelCase_ = GenerationConfig( do_sample=_snake_case , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7) self.assertEqual(config.do_sample , _snake_case) self.assertEqual(config.num_beams , 1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_snake_case) UpperCAmelCase_ = GenerationConfig.from_pretrained(_snake_case , temperature=1.0) self.assertEqual(loaded_config.temperature , 1.0) self.assertEqual(loaded_config.do_sample , _snake_case) self.assertEqual(loaded_config.num_beams , 1) # default value @is_staging_test class __snake_case ( unittest.TestCase ): @classmethod def lowerCamelCase ( cls : Tuple): """simple docstring""" UpperCAmelCase_ = TOKEN HfFolder.save_token(_snake_case) @classmethod def lowerCamelCase ( cls : Tuple): """simple docstring""" try: delete_repo(token=cls._token , repo_id='''test-generation-config''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''') except HTTPError: pass def lowerCamelCase ( self : List[Any]): """simple docstring""" UpperCAmelCase_ = GenerationConfig( do_sample=_snake_case , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token) UpperCAmelCase_ = GenerationConfig.from_pretrained(F"""{USER}/test-generation-config""") for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case)) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _snake_case , repo_id='''test-generation-config''' , push_to_hub=_snake_case , use_auth_token=self._token) UpperCAmelCase_ = GenerationConfig.from_pretrained(F"""{USER}/test-generation-config""") for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case)) def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" UpperCAmelCase_ = GenerationConfig( do_sample=_snake_case , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token) UpperCAmelCase_ = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case)) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( _snake_case , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=_snake_case , use_auth_token=self._token) UpperCAmelCase_ = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(_snake_case , getattr(_snake_case , _snake_case))
51
# 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. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase_ : Tuple = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyรจ': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmรฅl': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''facebook/nllb-200-distilled-600M''' snake_case__ : Union[str, Any] = ( '''This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ''' '''be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ''' '''which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ''' '''plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.''' ) snake_case__ : Optional[Any] = '''translator''' snake_case__ : Tuple = AutoTokenizer snake_case__ : Union[str, Any] = AutoModelForSeqaSeqLM snake_case__ : Dict = LANGUAGE_CODES snake_case__ : str = ['''text''', '''text''', '''text'''] snake_case__ : Tuple = ['''text'''] def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: if src_lang not in self.lang_to_code: raise ValueError(F"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(F"""{tgt_lang} is not a supported language.""" ) a_ : str = self.lang_to_code[src_lang] a_ : Any = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors='pt' , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Tuple ) -> Any: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
32
0
import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() __lowerCamelCase : List[str] = logging.get_logger(__name__) __lowerCamelCase : List[Any] = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn.grep_linear""": """encoder.layers.*.attention.gru_rel_pos_linear""", """self_attn.relative_attention_bias""": """encoder.layers.*.attention.rel_attn_embed""", """self_attn.grep_a""": """encoder.layers.*.attention.gru_rel_pos_const""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } __lowerCamelCase : str = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Dict: for attribute in key.split("." ): UpperCamelCase : Dict = getattr(_lowerCAmelCase , _lowerCAmelCase ) if weight_type is not None: UpperCamelCase : Union[str, Any] = getattr(_lowerCAmelCase , _lowerCAmelCase ).shape else: UpperCamelCase : Tuple = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCamelCase : int = value elif weight_type == "weight_g": UpperCamelCase : Optional[int] = value elif weight_type == "weight_v": UpperCamelCase : str = value elif weight_type == "bias": UpperCamelCase : Union[str, Any] = value else: UpperCamelCase : List[str] = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> str: UpperCamelCase : Optional[int] = [] UpperCamelCase : Optional[int] = fairseq_model.state_dict() UpperCamelCase : Optional[Any] = hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase : Dict = False if "conv_layers" in name: load_conv_layer( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , hf_model.config.feat_extract_norm == "group" , ) UpperCamelCase : Any = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: UpperCamelCase : Dict = True if "*" in mapped_key: UpperCamelCase : Any = name.split(_lowerCAmelCase )[0].split("." )[-2] UpperCamelCase : Optional[int] = mapped_key.replace("*" , _lowerCAmelCase ) if "weight_g" in name: UpperCamelCase : List[str] = "weight_g" elif "weight_v" in name: UpperCamelCase : str = "weight_v" elif "bias" in name and "relative_attention_bias" not in name: UpperCamelCase : Optional[Any] = "bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase : int = "weight" else: UpperCamelCase : str = None set_recursively(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) continue if not is_used: unused_weights.append(_lowerCAmelCase ) logger.warning(F"""Unused weights: {unused_weights}""" ) def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Tuple: UpperCamelCase : str = full_name.split("conv_layers." )[-1] UpperCamelCase : List[Any] = name.split("." ) UpperCamelCase : Union[str, Any] = int(items[0] ) UpperCamelCase : Tuple = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCamelCase : List[Any] = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCamelCase : str = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCamelCase : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCamelCase : Optional[Any] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_lowerCAmelCase ) @torch.no_grad() def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None ) -> str: # load the pre-trained checkpoints UpperCamelCase : Tuple = torch.load(_lowerCAmelCase ) UpperCamelCase : List[Any] = WavLMConfigOrig(checkpoint["cfg"] ) UpperCamelCase : Any = WavLMOrig(_lowerCAmelCase ) model.load_state_dict(checkpoint["model"] ) model.eval() if config_path is not None: UpperCamelCase : Dict = WavLMConfig.from_pretrained(_lowerCAmelCase ) else: UpperCamelCase : Tuple = WavLMConfig() UpperCamelCase : Any = WavLMModel(_lowerCAmelCase ) recursively_load_weights(_lowerCAmelCase , _lowerCAmelCase ) hf_wavlm.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": __lowerCamelCase : Tuple = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") __lowerCamelCase : int = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
52
UpperCAmelCase_ : Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def SCREAMING_SNAKE_CASE_ ( __A : int , __A : int , __A : int ) -> str: """simple docstring""" assert len(str(__A ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: a_ : List[str] = year // 1_00 a_ : Optional[int] = (5 * (century % 4) + 2) % 7 a_ : List[str] = year % 1_00 a_ : str = centurian % 12 a_ : List[str] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 a_ : Any = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) a_ : Any = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
32
0
'''simple docstring''' def lowercase__ ( __lowercase : str , __lowercase : int ) -> list: """simple docstring""" __UpperCamelCase = word.split() def justify(__lowercase : list , __lowercase : int , __lowercase : int ) -> str: __UpperCamelCase = max_width - width __UpperCamelCase = len(__lowercase ) if len(__lowercase ) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: __UpperCamelCase = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] __UpperCamelCase = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] __UpperCamelCase = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(__lowercase ): num_spaces_between_words_list[i] += 1 __UpperCamelCase = [] for i in range(__lowercase ): # add the word aligned_words_list.append(line[i] ) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * ' ' ) # just add the last word to the sentence aligned_words_list.append(line[-1] ) # join the aligned words list to form a justified line return "".join(__lowercase ) __UpperCamelCase = [] __UpperCamelCase = [] __UpperCamelCase = 0 for word in words: if width + len(__lowercase ) + len(__lowercase ) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(__lowercase ) width += len(__lowercase ) else: # justify the line and add it to result answer.append(justify(__lowercase , __lowercase , __lowercase ) ) # reset new line and new width __UpperCamelCase , __UpperCamelCase = [word], len(__lowercase ) __UpperCamelCase = max_width - width - len(__lowercase ) answer.append(' '.join(__lowercase ) + (remaining_spaces + 1) * ' ' ) return answer if __name__ == "__main__": from doctest import testmod testmod()
53
import math import flax.linen as nn import jax.numpy as jnp def SCREAMING_SNAKE_CASE_ ( __A : jnp.ndarray , __A : int , __A : float = 1 , __A : float = 1 , __A : float = 1.0e4 , __A : bool = False , __A : float = 1.0 , ) -> jnp.ndarray: """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F"""Embedding dimension {embedding_dim} should be even""" a_ : int = float(embedding_dim // 2 ) a_ : str = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) a_ : Optional[int] = min_timescale * jnp.exp(jnp.arange(__A , dtype=jnp.floataa ) * -log_timescale_increment ) a_ : Optional[int] = jnp.expand_dims(__A , 1 ) * jnp.expand_dims(__A , 0 ) # scale embeddings a_ : str = scale * emb if flip_sin_to_cos: a_ : str = jnp.concatenate([jnp.cos(__A ), jnp.sin(__A )] , axis=1 ) else: a_ : Any = jnp.concatenate([jnp.sin(__A ), jnp.cos(__A )] , axis=1 ) a_ : Optional[int] = jnp.reshape(__A , [jnp.shape(__A )[0], embedding_dim] ) return signal class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Optional[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_1' )(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = nn.silu(SCREAMING_SNAKE_CASE__ ) a_ : str = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_2' )(SCREAMING_SNAKE_CASE__ ) return temb class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : bool = False snake_case__ : float = 1 @nn.compact def __call__( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Tuple: return get_sinusoidal_embeddings( SCREAMING_SNAKE_CASE__ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
32
0
"""simple docstring""" from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration a__ : Any = HfArgumentParser(InitializationArguments) a__ : Any = parser.parse_args() # Load codeparrot tokenizer trained for Python code tokenization a__ : int = AutoTokenizer.from_pretrained(args.tokenizer_name) # Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks a__ : Dict = { '''vocab_size''': len(tokenizer), '''scale_attn_by_inverse_layer_idx''': True, '''reorder_and_upcast_attn''': True, } # Load model config (GPT-2 large in this case) a__ : str = AutoConfig.from_pretrained(args.config_name, **config_kwargs) # Initialize new model with config a__ : int = AutoModelForCausalLM.from_config(config) # Save model to the hub model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
54
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) UpperCAmelCase_ : str = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCAmelCase_ : Optional[Any] = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) UpperCAmelCase_ : int = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) UpperCAmelCase_ : Union[str, Any] = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) UpperCAmelCase_ : Union[str, Any] = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) UpperCAmelCase_ : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase_ : Dict = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase_ : Dict = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase_ : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase_ : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase_ : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[Any] = FLAX_MODEL_MAPPING UpperCAmelCase_ : Tuple = auto_class_update(FlaxAutoModel) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Any = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[Any] = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase_ : Union[str, Any] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase_ : Optional[int] = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase_ : str = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[str] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase_ : Tuple = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Dict = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase_ : int = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[int] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase_ : Dict = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase_ : str = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[Any] = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase_ : Tuple = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[int] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase_ : Union[str, Any] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
32
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor a_ : int = logging.get_logger(__name__) class snake_case ( lowercase ): """simple docstring""" def __init__( self , *UpperCamelCase , **UpperCamelCase ): """simple docstring""" warnings.warn( "The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DPTImageProcessor instead." , UpperCamelCase , ) super().__init__(*UpperCamelCase , **UpperCamelCase )
55
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): snake_case__ : Any = GPTSanJapaneseTokenizer snake_case__ : Tuple = False snake_case__ : str = {'''do_clean_text''': False, '''add_prefix_space''': False} def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: super().setUp() # fmt: off a_ : Union[str, Any] = ['ใ“ใ‚“', 'ใ“ใ‚“ใซ', 'ใซใกใฏ', 'ใฐใ‚“ใฏ', 'ไธ–็•Œ,ใ”บ็•Œ', 'ใ€', 'ใ€‚', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on a_ : int = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # ๐Ÿ˜€ a_ : List[Any] = {'unk_token': '<unk>'} a_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) a_ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE__ ) ) def SCREAMING_SNAKE_CASE ( self : List[str] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> int: kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> int: a_ : Optional[int] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : List[str] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Dict: a_ , a_ : Union[str, Any] = self.get_input_output_texts(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) a_ : Dict = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) return text, ids def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: a_ : List[str] = self.get_tokenizer() # Testing tokenization a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ€€ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚' a_ : Optional[int] = ['ใ“ใ‚“', 'ใซใกใฏ', 'ใ€', 'ไธ–็•Œ', 'ใ€‚', '<SP>', 'ใ“ใ‚“', 'ใฐใ‚“ใฏ', 'ใ€', 'ใ”บ็•Œ', 'ใ€‚'] a_ : Dict = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids without special tokens a_ : Tuple = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] a_ : List[Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids with special tokens a_ : int = tokens + [tokenizer.unk_token] a_ : int = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9] a_ : Tuple = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: a_ : Union[str, Any] = self.get_tokenizer() # Testing tokenization a_ : Dict = 'ใ“ใ‚“ใซใกใฏใ€<|bagoftoken|>ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€<|bagoftoken|>ใ”บ็•Œใ€‚' a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚' a_ : Any = tokenizer.encode(SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : str ) -> Dict: a_ : Tuple = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' a_ : int = 'ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : Dict = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' a_ : Optional[int] = tokenizer.encode(prefix_text + input_text ) a_ : Any = tokenizer.encode('' , prefix_text=prefix_text + input_text ) a_ : Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) a_ : str = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: a_ : Tuple = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization a_ : str = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' a_ : List[str] = 'ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : str = len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 a_ : Tuple = len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 a_ : Optional[Any] = [1] + [0] * (len_prefix + len_text + 1) a_ : Optional[Any] = [1] * (len_prefix + len_text + 1) + [0] a_ : Tuple = [1] + [1] * (len_prefix) + [0] * (len_text + 1) a_ : List[str] = tokenizer(prefix_text + input_text ).token_type_ids a_ : Union[str, Any] = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids a_ : Any = tokenizer(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: a_ : str = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) a_ : Optional[int] = tokenizer.encode('ใ‚ใƒณใ„ใƒฏ' ) a_ : Dict = tokenizer.encode('' , prefix_text='ใ‚ใƒณใ„ใƒฏ' ) a_ : Dict = tokenizer.encode('ใ„ใƒฏ' , prefix_text='ใ‚ใƒณ' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: a_ : List[str] = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) a_ : Optional[Any] = [['ๆญฆ็”ฐไฟก็Ž„', 'ใฏใ€'], ['็น”็”ฐไฟก้•ท', 'ใฎ้…ไธ‹ใฎใ€']] a_ : List[str] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) a_ : Dict = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) # fmt: off a_ : List[Any] = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]] a_ : Any = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] a_ : List[Any] = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: # tokenizer has no padding token pass
32
0
'''simple docstring''' a : Optional[Any] = { '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 a : Optional[Any] = {value: key for key, value in MORSE_CODE_DICT.items()} def __magic_name__ ( __UpperCAmelCase ) -> str: '''simple docstring''' return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def __magic_name__ ( __UpperCAmelCase ) -> str: '''simple docstring''' return "".join(REVERSE_DICT[char] for char in message.split() ) def __magic_name__ ( ) -> None: '''simple docstring''' snake_case_ = '''Morse code here!''' print(__UpperCAmelCase ) snake_case_ = encrypt(__UpperCAmelCase ) print(__UpperCAmelCase ) snake_case_ = decrypt(__UpperCAmelCase ) print(__UpperCAmelCase ) if __name__ == "__main__": main()
56
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, logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Union[str, Any] = ['''pixel_values'''] def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, int]] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 2_5_5 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) a_ : str = size if size is not None else {'shortest_edge': 2_5_6} a_ : Any = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) a_ : Dict = crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4} a_ : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE__ ) a_ : List[str] = do_resize a_ : Dict = size a_ : Optional[Any] = resample a_ : Optional[int] = do_center_crop a_ : Dict = crop_size a_ : int = do_rescale a_ : int = rescale_factor a_ : Tuple = do_normalize a_ : int = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN a_ : Tuple = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> np.ndarray: a_ : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) a_ : Tuple = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=size['shortest_edge'] , default_to_square=SCREAMING_SNAKE_CASE__ ) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> np.ndarray: a_ : str = get_size_dict(SCREAMING_SNAKE_CASE__ ) return center_crop(SCREAMING_SNAKE_CASE__ , size=(size['height'], size['width']) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> np.ndarray: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[float] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> Union[str, Any]: a_ : List[str] = do_resize if do_resize is not None else self.do_resize a_ : Dict = size if size is not None else self.size a_ : Dict = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = resample if resample is not None else self.resample a_ : List[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop a_ : int = crop_size if crop_size is not None else self.crop_size a_ : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE__ ) a_ : Dict = do_rescale if do_rescale is not None else self.do_rescale a_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor a_ : Any = do_normalize if do_normalize is not None else self.do_normalize a_ : str = image_mean if image_mean is not None else self.image_mean a_ : Dict = image_std if image_std is not None else self.image_std a_ : Optional[int] = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. a_ : Any = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: a_ : str = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_center_crop: a_ : int = [self.center_crop(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: a_ : Optional[Any] = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: a_ : List[Any] = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] a_ : Dict = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] a_ : Tuple = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
32
0
"""simple docstring""" from math import sqrt def _lowerCamelCase ( _UpperCamelCase = 100_0000 ): '''simple docstring''' __lowerCAmelCase = 0 __lowerCAmelCase = 0 __lowerCAmelCase = 42 while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(_UpperCamelCase , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f'''{solution() = }''')
57
def SCREAMING_SNAKE_CASE_ ( __A : list[int] , __A : str ) -> list[int]: """simple docstring""" a_ : Any = int(__A ) # Initialize Result a_ : Tuple = [] # Traverse through all denomination for denomination in reversed(__A ): # Find denominations while int(__A ) >= int(__A ): total_value -= int(__A ) answer.append(__A ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = [] UpperCAmelCase_ : Union[str, Any] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase_ : List[Any] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(F'Denomination {i}: ').strip())) UpperCAmelCase_ : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase_ : List[Any] = [1, 2, 5, 10, 20, 50, 100, 500, 2000] UpperCAmelCase_ : str = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(F'Following is minimal change for {value}: ') UpperCAmelCase_ : Optional[Any] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
32
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase_ = { """configuration_encodec""": [ """ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP""", """EncodecConfig""", ], """feature_extraction_encodec""": ["""EncodecFeatureExtractor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST""", """EncodecModel""", """EncodecPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
import flax.linen as nn import jax import jax.numpy as jnp class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : str ) -> int: a_ : Dict = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: a_ , a_ , a_ , a_ : Union[str, Any] = hidden_states.shape a_ : List[str] = jax.image.resize( SCREAMING_SNAKE_CASE__ , shape=(batch, height * 2, width * 2, channels) , method='nearest' , ) a_ : Any = self.conv(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: a_ : Optional[int] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]: # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim # hidden_states = jnp.pad(hidden_states, pad_width=pad) a_ : str = self.conv(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : int = None snake_case__ : float = 0.0 snake_case__ : bool = None snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: a_ : List[str] = self.in_channels if self.out_channels is None else self.out_channels a_ : Optional[int] = nn.GroupNorm(num_groups=3_2 , epsilon=1E-5 ) a_ : Any = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) a_ : Optional[int] = nn.Dense(SCREAMING_SNAKE_CASE__ , dtype=self.dtype ) a_ : Union[str, Any] = nn.GroupNorm(num_groups=3_2 , epsilon=1E-5 ) a_ : int = nn.Dropout(self.dropout_prob ) a_ : Optional[Any] = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) a_ : List[str] = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut a_ : List[Any] = None if use_nin_shortcut: a_ : Union[str, Any] = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(1, 1) , strides=(1, 1) , padding='VALID' , dtype=self.dtype , ) def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any]=True ) -> int: a_ : List[Any] = hidden_states a_ : Any = self.norma(SCREAMING_SNAKE_CASE__ ) a_ : Any = nn.swish(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = self.conva(SCREAMING_SNAKE_CASE__ ) a_ : int = self.time_emb_proj(nn.swish(SCREAMING_SNAKE_CASE__ ) ) a_ : List[str] = jnp.expand_dims(jnp.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , 1 ) a_ : Optional[int] = hidden_states + temb a_ : List[str] = self.norma(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = nn.swish(SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.dropout(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = self.conva(SCREAMING_SNAKE_CASE__ ) if self.conv_shortcut is not None: a_ : List[str] = self.conv_shortcut(SCREAMING_SNAKE_CASE__ ) return hidden_states + residual
32
0
import math def UpperCamelCase ( __lowerCamelCase : float , __lowerCamelCase : float ): if initial_intensity < 0: raise ValueError("The value of intensity cannot be negative" ) # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueError("In Malus Law, the angle is in the range 0-360 degrees" ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(__lowerCamelCase ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name="""malus_law""")
59
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. UpperCAmelCase_ : Dict = {'LayoutLMv2Config', 'LayoutLMv3Config'} @is_pipeline_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): snake_case__ : List[str] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING snake_case__ : Optional[Any] = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: snake_case__ : str = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: snake_case__ : List[Any] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: a_ : List[Any] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' ) a_ : int = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) a_ : Tuple = text_classifier('This is great !' , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}] ) a_ : List[str] = text_classifier(['This is great !', 'This is bad'] , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], ] , ) a_ : Tuple = text_classifier('This is great !' , top_k=1 ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) # Legacy behavior a_ : Union[str, Any] = text_classifier('This is great !' , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) a_ : List[str] = text_classifier('This is great !' , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}]] ) a_ : int = text_classifier(['This is great !', 'Something else'] , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], ] , ) a_ : str = text_classifier(['This is great !', 'Something else'] , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ {'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_0', 'score': 0.504}, ] , ) @require_torch def SCREAMING_SNAKE_CASE ( self : int ) -> Dict: import torch a_ : List[Any] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' , device=torch.device('cpu' ) , ) a_ : Any = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) @require_tf def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: a_ : List[str] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='tf' ) a_ : Optional[int] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) @slow @require_torch def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: a_ : List[str] = pipeline('text-classification' ) a_ : Dict = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 1.0}] ) a_ : Union[str, Any] = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'NEGATIVE', 'score': 1.0}] ) a_ : Tuple = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 0.988}] ) @slow @require_tf def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: a_ : Dict = pipeline('text-classification' , framework='tf' ) a_ : Optional[Any] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 1.0}] ) a_ : int = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'NEGATIVE', 'score': 1.0}] ) a_ : Optional[int] = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 0.988}] ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: a_ : Optional[Any] = TextClassificationPipeline(model=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ ) return text_classifier, ["HuggingFace is in", "This is another test"] def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: a_ : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 a_ : Union[str, Any] = 'HuggingFace is in' a_ : int = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) a_ : Union[str, Any] = ['HuggingFace is in ', 'Paris is in France'] a_ : int = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}, {'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) self.assertTrue(outputs[1]['label'] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format a_ : List[Any] = text_classifier(SCREAMING_SNAKE_CASE__ , top_k=SCREAMING_SNAKE_CASE__ ) a_ : Dict = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [[{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] * N, [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] * N] , ) a_ : int = {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'} a_ : Optional[int] = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , {'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )} , ) self.assertTrue(outputs['label'] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. a_ : Any = [['HuggingFace is in ', 'Paris is in France']] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): text_classifier(SCREAMING_SNAKE_CASE__ ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility a_ : Tuple = text_classifier([[['HuggingFace is in ', 'Paris is in France']]] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )
32
0
"""simple docstring""" import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging snake_case__ : Optional[int] = logging.get_logger(__name__) snake_case__ : Optional[Any] = {'''vocab_file''': '''vocab.txt'''} snake_case__ : Any = { '''vocab_file''': { '''openbmb/cpm-ant-10b''': '''https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt''', }, } snake_case__ : Tuple = { '''openbmb/cpm-ant-10b''': 1_024, } def _snake_case ( _snake_case : int ): lowerCAmelCase : List[str] = collections.OrderedDict() with open(_snake_case , '''r''' , encoding='''utf-8''' ) as reader: lowerCAmelCase : List[Any] = reader.readlines() for index, token in enumerate(_snake_case ): lowerCAmelCase : List[Any] = token.rstrip('''\n''' ) lowerCAmelCase : Tuple = index return vocab class snake_case_( a__ ): def __init__( self : List[Any] , UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str]="<unk>" , UpperCamelCase_ : Any=2_0_0 ): lowerCAmelCase : Any = vocab lowerCAmelCase : List[Any] = unk_token lowerCAmelCase : Dict = max_input_chars_per_word def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Tuple ): lowerCAmelCase : Any = list(UpperCamelCase_ ) if len(UpperCamelCase_ ) > self.max_input_chars_per_word: return [self.unk_token] lowerCAmelCase : Tuple = 0 lowerCAmelCase : Optional[int] = [] while start < len(UpperCamelCase_ ): lowerCAmelCase : List[str] = len(UpperCamelCase_ ) lowerCAmelCase : Dict = None while start < end: lowerCAmelCase : Union[str, Any] = ''''''.join(chars[start:end] ) if substr in self.vocab: lowerCAmelCase : Any = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(UpperCamelCase_ ) lowerCAmelCase : List[Any] = end return sub_tokens class snake_case_( a__ ): __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ['''input_ids''', '''attention_mask'''] __UpperCamelCase = False def __init__( self : int , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Union[str, Any]="<d>" , UpperCamelCase_ : int="</d>" , UpperCamelCase_ : str="<s>" , UpperCamelCase_ : str="</s>" , UpperCamelCase_ : Optional[int]="<pad>" , UpperCamelCase_ : Optional[int]="<unk>" , UpperCamelCase_ : Any="</n>" , UpperCamelCase_ : List[Any]="</_>" , UpperCamelCase_ : int="left" , **UpperCamelCase_ : List[str] , ): requires_backends(self , ['''jieba'''] ) super().__init__( bod_token=UpperCamelCase_ , eod_token=UpperCamelCase_ , bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , line_token=UpperCamelCase_ , space_token=UpperCamelCase_ , padding_side=UpperCamelCase_ , **UpperCamelCase_ , ) lowerCAmelCase : Any = bod_token lowerCAmelCase : Union[str, Any] = eod_token lowerCAmelCase : Optional[Any] = load_vocab(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = self.encoder[space_token] lowerCAmelCase : Union[str, Any] = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] lowerCAmelCase : Any = collections.OrderedDict(sorted(self.encoder.items() , key=lambda UpperCamelCase_ : x[1] ) ) lowerCAmelCase : Tuple = {v: k for k, v in self.encoder.items()} lowerCAmelCase : Any = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def lowerCamelCase__ ( self : Optional[int] ): return self.encoder[self.bod_token] @property def lowerCamelCase__ ( self : List[str] ): return self.encoder[self.eod_token] @property def lowerCamelCase__ ( self : Any ): return self.encoder["\n"] @property def lowerCamelCase__ ( self : List[Any] ): return len(self.encoder ) def lowerCamelCase__ ( self : str ): return dict(self.encoder , **self.added_tokens_encoder ) def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : List[Any] ): lowerCAmelCase : Dict = [] for x in jieba.cut(UpperCamelCase_ , cut_all=UpperCamelCase_ ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(UpperCamelCase_ ) ) return output_tokens def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Dict , **UpperCamelCase_ : Union[str, Any] ): lowerCAmelCase : Tuple = [i for i in token_ids if i >= 0] lowerCAmelCase : Dict = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(UpperCamelCase_ , **UpperCamelCase_ ) def lowerCamelCase__ ( self : int , UpperCamelCase_ : str ): return token in self.encoder def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : List[str] ): return "".join(UpperCamelCase_ ) def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : int ): return self.encoder.get(UpperCamelCase_ , self.encoder.get(self.unk_token ) ) def lowerCamelCase__ ( self : str , UpperCamelCase_ : Dict ): return self.decoder.get(UpperCamelCase_ , self.unk_token ) def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : str , UpperCamelCase_ : Optional[str] = None ): if os.path.isdir(UpperCamelCase_ ): lowerCAmelCase : Optional[int] = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) else: lowerCAmelCase : int = (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory lowerCAmelCase : Any = 0 if " " in self.encoder: lowerCAmelCase : int = self.encoder[''' '''] del self.encoder[" "] if "\n" in self.encoder: lowerCAmelCase : Optional[Any] = self.encoder['''\n'''] del self.encoder["\n"] lowerCAmelCase : List[Any] = collections.OrderedDict(sorted(self.encoder.items() , key=lambda UpperCamelCase_ : x[1] ) ) with open(UpperCamelCase_ , '''w''' , encoding='''utf-8''' ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.''' ''' Please check that the vocabulary is not corrupted!''' ) lowerCAmelCase : str = token_index writer.write(token + '''\n''' ) index += 1 return (vocab_file,) def lowerCamelCase__ ( self : str , UpperCamelCase_ : List[int] , UpperCamelCase_ : List[int] = None ): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None , UpperCamelCase_ : bool = 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 not None: return [1] + ([0] * len(UpperCamelCase_ )) + [1] + ([0] * len(UpperCamelCase_ )) return [1] + ([0] * len(UpperCamelCase_ ))
60
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : str = 'T5Config' def SCREAMING_SNAKE_CASE_ ( __A : jnp.array , __A : int , __A : int ) -> jnp.ndarray: """simple docstring""" a_ : Dict = jnp.zeros_like(__A ) a_ : Dict = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) a_ : str = shifted_input_ids.at[:, 0].set(__A ) a_ : int = jnp.where(shifted_input_ids == -1_00 , __A , __A ) return shifted_input_ids class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[Any] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[str] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = '''mt5''' snake_case__ : Union[str, Any] = MTaConfig
32
0
"""simple docstring""" _a = { 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f', } def __a ( __lowerCamelCase ): assert type(__lowerCamelCase ) in (int, float) and decimal == int(__lowerCamelCase ) UpperCAmelCase_ : Any = int(__lowerCamelCase ) UpperCAmelCase_ : List[Any] = "" UpperCAmelCase_ : Union[str, Any] = False if decimal < 0: UpperCAmelCase_ : Optional[int] = True decimal *= -1 while decimal > 0: UpperCAmelCase_ , UpperCAmelCase_ : Tuple = divmod(__lowerCamelCase, 16 ) UpperCAmelCase_ : Optional[int] = values[remainder] + hexadecimal UpperCAmelCase_ : List[Any] = "0x" + hexadecimal if negative: UpperCAmelCase_ : Any = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
61
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent UpperCAmelCase_ : Any = {'UserAgent': UserAgent().random} def SCREAMING_SNAKE_CASE_ ( __A : Optional[int] ) -> dict: """simple docstring""" a_ : Tuple = script.contents[0] a_ : int = json.loads(data[data.find('{"config"' ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: a_ : Tuple = F"""https://www.instagram.com/{username}/""" a_ : Optional[Any] = self.get_json() def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> dict: a_ : Any = requests.get(self.url , headers=SCREAMING_SNAKE_CASE__ ).text a_ : Dict = BeautifulSoup(SCREAMING_SNAKE_CASE__ , 'html.parser' ).find_all('script' ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Union[str, Any] ) -> str: return F"""{self.__class__.__name__}('{self.username}')""" def __str__( self : Optional[int] ) -> str: return F"""{self.fullname} ({self.username}) is {self.biography}""" @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: return self.user_data["username"] @property def SCREAMING_SNAKE_CASE ( self : str ) -> str: return self.user_data["full_name"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> str: return self.user_data["biography"] @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: return self.user_data["business_email"] @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: return self.user_data["external_url"] @property def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return self.user_data["edge_followed_by"]["count"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> int: return self.user_data["edge_follow"]["count"] @property def SCREAMING_SNAKE_CASE ( self : str ) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: return self.user_data["profile_pic_url_hd"] @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> bool: return self.user_data["is_verified"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.user_data["is_private"] def SCREAMING_SNAKE_CASE_ ( __A : str = "github" ) -> None: """simple docstring""" import os if os.environ.get('CI' ): return # test failing on GitHub Actions a_ : int = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 1_50 assert instagram_user.number_of_followers > 12_00_00 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith('https://instagram.' ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase_ : Union[str, Any] = InstagramUser('github') print(instagram_user) print(F'{instagram_user.number_of_posts = }') print(F'{instagram_user.number_of_followers = }') print(F'{instagram_user.number_of_followings = }') print(F'{instagram_user.email = }') print(F'{instagram_user.website = }') print(F'{instagram_user.profile_picture_url = }') print(F'{instagram_user.is_verified = }') print(F'{instagram_user.is_private = }')
32
0
from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : str = field( metadata={"help": "The output directory where the model will be written."} , ) UpperCAmelCase__ : str = field( metadata={ "help": ( "The encoder model checkpoint for weights initialization." "Don't set if you want to train an encoder model from scratch." ) } , ) UpperCAmelCase__ : str = field( metadata={ "help": ( "The decoder model checkpoint for weights initialization." "Don't set if you want to train a decoder model from scratch." ) } , ) UpperCAmelCase__ : Optional[str] = field( default=A_ , metadata={"help": "Pretrained encoder config name or path if not the same as encoder_model_name"} ) UpperCAmelCase__ : Optional[str] = field( default=A_ , metadata={"help": "Pretrained decoder config name or path if not the same as decoder_model_name"} ) def _UpperCAmelCase ( ): __UpperCamelCase =HfArgumentParser((ModelArguments,) ) ((__UpperCamelCase) , ) =parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: __UpperCamelCase =AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: __UpperCamelCase =AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: __UpperCamelCase =AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: __UpperCamelCase =AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed __UpperCamelCase =True __UpperCamelCase =True __UpperCamelCase =FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=model_args.encoder_model_name_or_path , decoder_pretrained_model_name_or_path=model_args.decoder_model_name_or_path , encoder_config=SCREAMING_SNAKE_CASE__ , decoder_config=SCREAMING_SNAKE_CASE__ , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens __UpperCamelCase =decoder_config.decoder_start_token_id __UpperCamelCase =decoder_config.pad_token_id if decoder_start_token_id is None: __UpperCamelCase =decoder_config.bos_token_id if pad_token_id is None: __UpperCamelCase =decoder_config.eos_token_id # This is necessary to make Flax's generate() work __UpperCamelCase =decoder_config.eos_token_id __UpperCamelCase =decoder_start_token_id __UpperCamelCase =pad_token_id __UpperCamelCase =AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) __UpperCamelCase =AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) __UpperCamelCase =tokenizer.convert_ids_to_tokens(model.config.pad_token_id ) model.save_pretrained(model_args.output_dir ) image_processor.save_pretrained(model_args.output_dir ) tokenizer.save_pretrained(model_args.output_dir ) if __name__ == "__main__": main()
62
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Tuple = ['''image_processor''', '''tokenizer'''] snake_case__ : Union[str, Any] = '''CLIPImageProcessor''' snake_case__ : Dict = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : int ) -> Any: a_ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , SCREAMING_SNAKE_CASE__ , ) a_ : Tuple = kwargs.pop('feature_extractor' ) a_ : Tuple = 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 : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE__ : str ) -> Optional[Any]: if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: a_ : List[str] = self.tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if images is not None: a_ : Dict = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None and images is not None: a_ : Dict = 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 SCREAMING_SNAKE_CASE ( self : Any , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[Any]: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: a_ : str = self.tokenizer.model_input_names a_ : Tuple = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def SCREAMING_SNAKE_CASE ( self : str ) -> str: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , SCREAMING_SNAKE_CASE__ , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , SCREAMING_SNAKE_CASE__ , ) return self.image_processor
32
0
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. lowerCAmelCase_ : List[Any] = 10 def _lowerCamelCase ( lowercase : int , lowercase : int , lowercase : list[int] , lowercase : int ) -> int: for i in range(lowercase , lowercase ): if array[i] == target: return i return -1 def _lowerCamelCase ( lowercase : list[int] , lowercase : int ) -> int: _a = 0 _a = len(lowercase ) while left <= right: if right - left < precision: return lin_search(lowercase , lowercase , lowercase , lowercase ) _a = (left + right) // 3 + 1 _a = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: _a = one_third - 1 elif array[two_third] < target: _a = two_third + 1 else: _a = one_third + 1 _a = two_third - 1 else: return -1 def _lowerCamelCase ( lowercase : int , lowercase : int , lowercase : list[int] , lowercase : int ) -> int: if left < right: if right - left < precision: return lin_search(lowercase , lowercase , lowercase , lowercase ) _a = (left + right) // 3 + 1 _a = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(lowercase , one_third - 1 , lowercase , lowercase ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , lowercase , lowercase , lowercase ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , lowercase , lowercase ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase_ : int = input('Enter numbers separated by comma:\n').strip() lowerCAmelCase_ : Tuple = [int(item.strip()) for item in user_input.split(',')] assert collection == sorted(collection), f"List must be ordered.\n{collection}." lowerCAmelCase_ : str = int(input('Enter the number to be found in the list:\n').strip()) lowerCAmelCase_ : Optional[int] = ite_ternary_search(collection, target) lowerCAmelCase_ : Optional[int] = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f"""Iterative search: {target} found at positions: {resulta}""") print(f"""Recursive search: {target} found at positions: {resulta}""") else: print('Not found')
63
from __future__ import annotations UpperCAmelCase_ : Tuple = [] def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] , __A : int , __A : int ) -> bool: """simple docstring""" for i in range(len(__A ) ): if board[row][i] == 1: return False for i in range(len(__A ) ): if board[i][column] == 1: return False for i, j in zip(range(__A , -1 , -1 ) , range(__A , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(__A , -1 , -1 ) , range(__A , len(__A ) ) ): if board[i][j] == 1: return False return True def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] , __A : int ) -> bool: """simple docstring""" if row >= len(__A ): solution.append(__A ) printboard(__A ) print() return True for i in range(len(__A ) ): if is_safe(__A , __A , __A ): a_ : Any = 1 solve(__A , row + 1 ) a_ : Tuple = 0 return False def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] ) -> None: """simple docstring""" for i in range(len(__A ) ): for j in range(len(__A ) ): if board[i][j] == 1: print('Q' , end=' ' ) else: print('.' , end=' ' ) print() # n=int(input("The no. of queens")) UpperCAmelCase_ : List[str] = 8 UpperCAmelCase_ : str = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
32
0
"""simple docstring""" # 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.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
64
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def SCREAMING_SNAKE_CASE_ ( ) -> Any: """simple docstring""" a_ : Optional[Any] = HfArgumentParser(__A ) a_ : Optional[int] = parser.parse_args_into_dataclasses()[0] a_ : List[Any] = TensorFlowBenchmark(args=__A ) try: a_ : List[str] = parser.parse_args_into_dataclasses()[0] except ValueError as e: a_ : Dict = 'Arg --no_{0} is no longer used, please use --no-{0} instead.' a_ : Dict = ' '.join(str(__A ).split(' ' )[:-1] ) a_ : int = '' a_ : int = eval(str(__A ).split(' ' )[-1] ) a_ : Any = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__A ) if len(__A ) > 0: a_ : str = full_error_msg + begin_error_msg + str(__A ) raise ValueError(__A ) benchmark.run() if __name__ == "__main__": main()
32
0
def lowerCAmelCase_ ( __A, __A, __A, __A ) -> List[Any]: '''simple docstring''' global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: UpperCAmelCase__ = mf_knapsack(i - 1, __A, __A, __A ) else: UpperCAmelCase__ = max( mf_knapsack(i - 1, __A, __A, __A ), mf_knapsack(i - 1, __A, __A, j - wt[i - 1] ) + val[i - 1], ) UpperCAmelCase__ = val return f[i][j] def lowerCAmelCase_ ( __A, __A, __A, __A ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase__ = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1, n + 1 ): for w_ in range(1, w + 1 ): if wt[i - 1] <= w_: UpperCAmelCase__ = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]], dp[i - 1][w_] ) else: UpperCAmelCase__ = dp[i - 1][w_] return dp[n][w_], dp def lowerCAmelCase_ ( __A, __A, __A ) -> Optional[Any]: '''simple docstring''' if not (isinstance(__A, (list, tuple) ) and isinstance(__A, (list, tuple) )): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) UpperCAmelCase__ = len(__A ) if num_items != len(__A ): UpperCAmelCase__ = ( "The number of weights must be the same as the number of values.\n" f"""But got {num_items} weights and {len(__A )} values""" ) raise ValueError(__A ) for i in range(__A ): if not isinstance(wt[i], __A ): UpperCAmelCase__ = ( "All weights must be integers but got weight of " f"""type {type(wt[i] )} at index {i}""" ) raise TypeError(__A ) UpperCAmelCase__ , UpperCAmelCase__ = knapsack(__A, __A, __A, __A ) UpperCAmelCase__ = set() _construct_solution(__A, __A, __A, __A, __A ) return optimal_val, example_optional_set def lowerCAmelCase_ ( __A, __A, __A, __A, __A ) -> Optional[int]: '''simple docstring''' if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(__A, __A, i - 1, __A, __A ) else: optimal_set.add(__A ) _construct_solution(__A, __A, i - 1, j - wt[i - 1], __A ) if __name__ == "__main__": UpperCamelCase__ = [3, 2, 4, 4] UpperCamelCase__ = [4, 3, 2, 3] UpperCamelCase__ = 4 UpperCamelCase__ = 6 UpperCamelCase__ = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] UpperCamelCase__ , UpperCamelCase__ = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 UpperCamelCase__ , UpperCamelCase__ = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print('optimal_value = ', optimal_solution) print('An optimal subset corresponding to the optimal value', optimal_subset)
65
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): snake_case__ : Optional[Any] = TextToVideoSDPipeline snake_case__ : Optional[int] = TEXT_TO_IMAGE_PARAMS snake_case__ : str = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. snake_case__ : Optional[Any] = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: torch.manual_seed(0 ) a_ : Optional[int] = UNetaDConditionModel( block_out_channels=(3_2, 6_4, 6_4, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D') , up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D') , cross_attention_dim=3_2 , attention_head_dim=4 , ) a_ : int = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) a_ : int = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) a_ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=5_1_2 , ) a_ : Dict = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) a_ : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> List[str]: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): a_ : Dict = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: a_ : Optional[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) a_ : int = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'pt', } return inputs def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator a_ : Dict = self.get_dummy_components() a_ : str = TextToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) a_ : Dict = 'np' a_ : Dict = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames a_ : int = frames[0][-3:, -3:, -1] assert frames[0].shape == (6_4, 6_4, 3) a_ : Union[str, Any] = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=3E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def SCREAMING_SNAKE_CASE ( self : Any ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=1E-2 ) @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: pass @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: pass @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: pass def SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: return super().test_progress_bar() @slow @skip_mps class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: a_ : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy' ) a_ : Any = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) a_ : Optional[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) a_ : Optional[Any] = pipe.to('cuda' ) a_ : Any = 'Spiderman is surfing' a_ : List[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) a_ : Optional[Any] = pipe(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2_5 , output_type='pt' ).frames a_ : str = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2 def SCREAMING_SNAKE_CASE ( self : Any ) -> Any: a_ : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy' ) a_ : Tuple = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) a_ : Tuple = pipe.to('cuda' ) a_ : Any = 'Spiderman is surfing' a_ : List[str] = torch.Generator(device='cpu' ).manual_seed(0 ) a_ : List[Any] = pipe(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type='pt' ).frames a_ : List[str] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2
32
0
"""simple docstring""" 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 ): '''simple docstring''' def __init__( self: List[Any] , snake_case: List[str] , snake_case: Optional[Any]=13 , snake_case: List[str]=7 , snake_case: Dict=True , snake_case: List[str]=True , snake_case: Optional[int]=True , snake_case: Any=True , snake_case: Optional[Any]=99 , snake_case: Tuple=32 , snake_case: Tuple=5 , snake_case: Dict=4 , snake_case: Optional[Any]=37 , snake_case: Union[str, Any]="gelu" , snake_case: Tuple=0.1 , snake_case: List[Any]=0.1 , snake_case: List[str]=512 , snake_case: Optional[int]=16 , snake_case: int=2 , snake_case: List[Any]=0.0_2 , snake_case: Union[str, Any]=4 , ) -> List[str]: snake_case_ :Dict = parent snake_case_ :Any = batch_size snake_case_ :Any = seq_length snake_case_ :List[str] = is_training snake_case_ :Optional[Any] = use_attention_mask snake_case_ :Dict = use_token_type_ids snake_case_ :Union[str, Any] = use_labels snake_case_ :str = vocab_size snake_case_ :int = hidden_size snake_case_ :List[str] = num_hidden_layers snake_case_ :Dict = num_attention_heads snake_case_ :Any = intermediate_size snake_case_ :Tuple = hidden_act snake_case_ :int = hidden_dropout_prob snake_case_ :Optional[Any] = attention_probs_dropout_prob snake_case_ :Any = max_position_embeddings snake_case_ :Union[str, Any] = type_vocab_size snake_case_ :Optional[int] = type_sequence_label_size snake_case_ :Union[str, Any] = initializer_range snake_case_ :Tuple = num_choices def lowerCAmelCase_ ( self: Tuple ) -> str: snake_case_ :Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ :Union[str, Any] = None if self.use_attention_mask: snake_case_ :str = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ :Any = None if self.use_token_type_ids: snake_case_ :List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ :int = 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=snake_case , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCAmelCase_ ( self: Optional[int] ) -> int: snake_case_ :str = self.prepare_config_and_inputs() snake_case_, snake_case_, snake_case_, snake_case_ :Optional[int] = config_and_inputs snake_case_ :Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCAmelCase_ ( self: Optional[Any] ) -> Any: snake_case_ :int = self.prepare_config_and_inputs() snake_case_, snake_case_, snake_case_, snake_case_ :Dict = config_and_inputs snake_case_ :Union[str, Any] = True snake_case_ :Optional[int] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) snake_case_ :Tuple = 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 ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' _A : List[str] = True _A : Dict = ( ( FlaxBertModel, FlaxBertForPreTraining, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForQuestionAnswering, FlaxBertForNextSentencePrediction, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase_ ( self: int ) -> List[str]: snake_case_ :Any = FlaxBertModelTester(self ) @slow def lowerCAmelCase_ ( self: List[str] ) -> Dict: # Only check this for base model, not necessary for all model classes. # This will also help speed-up tests. snake_case_ :Dict = FlaxBertModel.from_pretrained("""bert-base-cased""" ) snake_case_ :Dict = model(np.ones((1, 1) ) ) self.assertIsNotNone(snake_case )
66
import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): # TODO: is there an appropriate internal test set? snake_case__ : Any = '''ssube/stable-diffusion-x4-upscaler-onnx''' def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : int=0 ) -> Tuple: a_ : Union[str, Any] = floats_tensor((1, 3, 1_2_8, 1_2_8) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ) a_ : Dict = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: a_ : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.get_dummy_inputs() a_ : int = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : Tuple = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : List[Any] = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: a_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : int = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : List[str] = self.get_dummy_inputs() a_ : List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : str = np.array( [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: a_ : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : Optional[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.get_dummy_inputs() a_ : Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : Optional[Any] = np.array( [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: a_ : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : int = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = self.get_dummy_inputs() a_ : Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : int = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: a_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : Optional[int] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = self.get_dummy_inputs() a_ : List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : Union[str, Any] = np.array( [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: a_ : List[str] = ort.SessionOptions() a_ : int = False return options def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: a_ : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) a_ : int = init_image.resize((1_2_8, 1_2_8) ) # using the PNDM scheduler by default a_ : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Tuple = 'A fantasy landscape, trending on artstation' a_ : str = torch.manual_seed(0 ) a_ : List[str] = pipe( prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=1_0 , generator=SCREAMING_SNAKE_CASE__ , output_type='np' , ) a_ : Dict = output.images a_ : Any = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) a_ : str = np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: a_ : Dict = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) a_ : List[str] = init_image.resize((1_2_8, 1_2_8) ) a_ : Dict = LMSDiscreteScheduler.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , subfolder='scheduler' ) a_ : Union[str, Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , scheduler=SCREAMING_SNAKE_CASE__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Any = 'A fantasy landscape, trending on artstation' a_ : Tuple = torch.manual_seed(0 ) a_ : Optional[Any] = pipe( prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=2_0 , generator=SCREAMING_SNAKE_CASE__ , output_type='np' , ) a_ : str = output.images a_ : List[Any] = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) a_ : Tuple = np.array( [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
32
0
'''simple docstring''' import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class a__ : def __init__( self : Tuple , a : Optional[int] , a : Optional[Any]=13 , a : List[Any]=64 , a : str=2 , a : int=3 , a : Union[str, Any]=True , a : List[str]=True , a : str=32 , a : List[Any]=5 , a : int=4 , a : Optional[int]=37 , a : Any="gelu" , a : List[Any]=0.1 , a : Tuple=0.1 , a : int=10 , a : Optional[int]=0.02 , a : int=[1, 16, 4, 4] , a : Dict=None , ): """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 __lowerCamelCase = scope __lowerCamelCase = backbone_featmap_shape # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) # the number of patches is based on the feature map of the backbone, which by default uses an output stride # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size __lowerCamelCase = (self.image_size // 32) ** 2 __lowerCamelCase = num_patches + 1 def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase = None if self.use_labels: __lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" __lowerCamelCase = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [4, 8, 16, 32], '''num_groups''': 2, } return ViTHybridConfig( 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 , backbone_featmap_shape=self.backbone_featmap_shape , backbone_config=a , ) def SCREAMING_SNAKE_CASE__ ( self : List[str] , a : Any , a : Optional[int] , a : Tuple ): """simple docstring""" __lowerCamelCase = ViTHybridModel(config=a ) model.to(a ) model.eval() __lowerCamelCase = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : Any , a : Dict , a : Dict , a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = self.type_sequence_label_size __lowerCamelCase = ViTHybridForImageClassification(a ) model.to(a ) model.eval() __lowerCamelCase = model(a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = config_and_inputs __lowerCamelCase = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class a__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): lowerCamelCase : Optional[Any] =(ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else () lowerCamelCase : Tuple =( {"feature-extraction": ViTHybridModel, "image-classification": ViTHybridForImageClassification} if is_torch_available() else {} ) lowerCamelCase : List[Any] =False lowerCamelCase : Tuple =False lowerCamelCase : List[str] =False def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = ViTHybridModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=a , has_text_modality=a , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" pass def SCREAMING_SNAKE_CASE__ ( self : 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 ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __lowerCamelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a , nn.Linear ) ) def SCREAMING_SNAKE_CASE__ ( self : 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.forward ) # 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 SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCamelCase = _config_zero_init(a ) for model_class in self.all_model_classes: __lowerCamelCase = model_class(config=a ) # Skip the check for the backbone for name, module in model.named_modules(): if module.__class__.__name__ == "ViTHybridPatchEmbeddings": __lowerCamelCase = [f"""{name}.{key}""" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @slow def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase = ViTHybridModel.from_pretrained(a ) self.assertIsNotNone(a ) def __lowerCAmelCase ( ) -> Optional[int]: __lowerCamelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class a__ ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" return ( ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( a ) __lowerCamelCase = self.default_image_processor __lowerCamelCase = prepare_img() __lowerCamelCase = image_processor(images=a , return_tensors='''pt''' ).to(a ) # forward pass with torch.no_grad(): __lowerCamelCase = model(**a ) # verify the logits __lowerCamelCase = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , a ) __lowerCamelCase = torch.tensor([-1.90_90, -0.49_93, -0.23_89] ).to(a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a , atol=1e-4 ) ) @slow @require_accelerate def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = ViTHybridImageProcessor.from_pretrained('''google/vit-hybrid-base-bit-384''' ) __lowerCamelCase = ViTHybridForImageClassification.from_pretrained('''google/vit-hybrid-base-bit-384''' , device_map='''auto''' ) __lowerCamelCase = prepare_img() __lowerCamelCase = image_processor(images=a , return_tensors='''pt''' ) __lowerCamelCase = model(**a ) __lowerCamelCase = outputs.logits # model predicts one of the 1000 ImageNet classes __lowerCamelCase = logits.argmax(-1 ).item() self.assertTrue(model.config.idalabel[predicted_class_idx] , '''tabby, tabby cat''' )
67
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> str: """simple docstring""" a_ : Tuple = [] for line in lines: a_ : Any = re.sub(R'#.*' , '' , __A ) # remove comments if line: filtered_lines.append(__A ) a_ : Tuple = '\n'.join(__A ) # Make a hash from all this code a_ : Tuple = full_str.encode('utf-8' ) return shaaaa(__A ).hexdigest() # get importable module names and hash for caching UpperCAmelCase_ : List[Any] = { 'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), 'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), 'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), 'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), 'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), 'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), 'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), 'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions UpperCAmelCase_ : Dict = { '.csv': ('csv', {}), '.tsv': ('csv', {'sep': '\t'}), '.json': ('json', {}), '.jsonl': ('json', {}), '.parquet': ('parquet', {}), '.arrow': ('arrow', {}), '.txt': ('text', {}), } _EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) UpperCAmelCase_ : Optional[int] = {'imagefolder', 'audiofolder'} # Used to filter data files based on extensions given a module name UpperCAmelCase_ : Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('.zip') _MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')
32
0
class a__ : """simple docstring""" def __init__( self ) -> None: '''simple docstring''' A__ = {} # Mapping from char to TrieNode A__ = False def UpperCamelCase ( self , lowercase ) -> None: '''simple docstring''' for word in words: self.insert(lowercase ) def UpperCamelCase ( self , lowercase ) -> None: '''simple docstring''' A__ = self for char in word: if char not in curr.nodes: A__ = TrieNode() A__ = curr.nodes[char] A__ = True def UpperCamelCase ( self , lowercase ) -> bool: '''simple docstring''' A__ = self for char in word: if char not in curr.nodes: return False A__ = curr.nodes[char] return curr.is_leaf def UpperCamelCase ( self , lowercase ) -> None: '''simple docstring''' def _delete(lowercase , lowercase , lowercase ) -> bool: if index == len(lowercase ): # If word does not exist if not curr.is_leaf: return False A__ = False return len(curr.nodes ) == 0 A__ = word[index] A__ = curr.nodes.get(lowercase ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted A__ = _delete(lowercase , lowercase , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , lowercase , 0 ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: TrieNode , SCREAMING_SNAKE_CASE_: str ) -> None: '''simple docstring''' if node.is_leaf: print(SCREAMING_SNAKE_CASE_ , end=" " ) for key, value in node.nodes.items(): print_words(SCREAMING_SNAKE_CASE_ , word + key ) def lowerCAmelCase__ ( ) -> bool: '''simple docstring''' A__ = "banana bananas bandana band apple all beast".split() A__ = TrieNode() root.insert_many(SCREAMING_SNAKE_CASE_ ) # print_words(root, "") assert all(root.find(SCREAMING_SNAKE_CASE_ ) for word in words ) assert root.find("banana" ) assert not root.find("bandanas" ) assert not root.find("apps" ) assert root.find("apple" ) assert root.find("all" ) root.delete("all" ) assert not root.find("all" ) root.delete("banana" ) assert not root.find("banana" ) assert root.find("bananas" ) return True def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: bool ) -> None: '''simple docstring''' print(str(SCREAMING_SNAKE_CASE_ ) , "works!" if passes else "doesn't work :(" ) def lowerCAmelCase__ ( ) -> None: '''simple docstring''' assert test_trie() def lowerCAmelCase__ ( ) -> None: '''simple docstring''' print_results("Testing trie functionality" , test_trie() ) if __name__ == "__main__": main()
68
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Optional[int] = '''convbert''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=3_0_5_2_2 , SCREAMING_SNAKE_CASE__ : Dict=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[int]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : Any=1E-12 , SCREAMING_SNAKE_CASE__ : int=1 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=9 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : Dict=None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> Any: super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) a_ : Tuple = vocab_size a_ : List[str] = hidden_size a_ : List[str] = num_hidden_layers a_ : Dict = num_attention_heads a_ : Optional[int] = intermediate_size a_ : int = hidden_act a_ : Dict = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : str = max_position_embeddings a_ : List[str] = type_vocab_size a_ : List[str] = initializer_range a_ : Tuple = layer_norm_eps a_ : Optional[int] = embedding_size a_ : List[Any] = head_ratio a_ : List[Any] = conv_kernel_size a_ : Tuple = num_groups a_ : Tuple = classifier_dropout class SCREAMING_SNAKE_CASE__ ( lowercase__ ): @property def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": a_ : Tuple = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a_ : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
32
0
"""simple docstring""" import argparse import math import os from copy import deepcopy import torch from audio_diffusion.models import DiffusionAttnUnetaD from diffusion import sampling from torch import nn from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel __UpperCamelCase = { '''gwf-440k''': { '''url''': '''https://model-server.zqevans2.workers.dev/gwf-440k.ckpt''', '''sample_rate''': 4_8000, '''sample_size''': 6_5536, }, '''jmann-small-190k''': { '''url''': '''https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt''', '''sample_rate''': 4_8000, '''sample_size''': 6_5536, }, '''jmann-large-580k''': { '''url''': '''https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt''', '''sample_rate''': 4_8000, '''sample_size''': 13_1072, }, '''maestro-uncond-150k''': { '''url''': '''https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt''', '''sample_rate''': 1_6000, '''sample_size''': 6_5536, }, '''unlocked-uncond-250k''': { '''url''': '''https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt''', '''sample_rate''': 1_6000, '''sample_size''': 6_5536, }, '''honk-140k''': { '''url''': '''https://model-server.zqevans2.workers.dev/honk-140k.ckpt''', '''sample_rate''': 1_6000, '''sample_size''': 6_5536, }, } def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase ) -> str: return torch.atana(UpperCAmelCase , UpperCAmelCase ) / math.pi * 2 def UpperCAmelCase ( UpperCAmelCase ) -> Union[str, Any]: snake_case_ = torch.sin(t * math.pi / 2 ) ** 2 snake_case_ = (1 - sigma**2) ** 0.5 return alpha_sigma_to_t(UpperCAmelCase , UpperCAmelCase ) class UpperCamelCase ( lowerCAmelCase__ ): pass class UpperCamelCase ( nn.Module ): def __init__( self, lowerCAmelCase__) -> Tuple: super().__init__() snake_case_ = DiffusionAttnUnetaD(lowerCAmelCase__, n_attn_layers=4) snake_case_ = deepcopy(self.diffusion) snake_case_ = torch.quasirandom.SobolEngine(1, scramble=lowerCAmelCase__) def UpperCAmelCase ( UpperCAmelCase ) -> Dict: snake_case_ = MODELS_MAP[model_name]['url'] os.system(f'wget {url} ./' ) return f'./{model_name}.ckpt' __UpperCamelCase = { '''1''': '''resnets.0''', '''2''': '''attentions.0''', '''3''': '''resnets.1''', '''4''': '''attentions.1''', '''5''': '''resnets.2''', '''6''': '''attentions.2''', } __UpperCamelCase = { '''8''': '''resnets.0''', '''9''': '''attentions.0''', '''10''': '''resnets.1''', '''11''': '''attentions.1''', '''12''': '''resnets.2''', '''13''': '''attentions.2''', } __UpperCamelCase = { '''1''': '''resnets.0''', '''2''': '''attentions.0''', '''3''': '''resnets.1''', '''4''': '''attentions.1''', '''5''': '''resnets.2''', '''6''': '''attentions.2''', '''8''': '''resnets.3''', '''9''': '''attentions.3''', '''10''': '''resnets.4''', '''11''': '''attentions.4''', '''12''': '''resnets.5''', '''13''': '''attentions.5''', } __UpperCamelCase = { '''0''': '''resnets.0''', '''1''': '''resnets.1''', '''2''': '''resnets.2''', '''4''': '''resnets.0''', '''5''': '''resnets.1''', '''6''': '''resnets.2''', } __UpperCamelCase = { '''skip''': '''conv_skip''', '''main.0''': '''conv_1''', '''main.1''': '''group_norm_1''', '''main.3''': '''conv_2''', '''main.4''': '''group_norm_2''', } __UpperCamelCase = { '''norm''': '''group_norm''', '''qkv_proj''': ['''query''', '''key''', '''value'''], '''out_proj''': ['''proj_attn'''], } def UpperCAmelCase ( UpperCAmelCase ) -> Dict: if name.startswith('skip' ): return name.replace('skip' , RES_CONV_MAP['skip'] ) # name has to be of format main.{digit} if not name.startswith('main.' ): raise ValueError(f'ResConvBlock error with {name}' ) return name.replace(name[:6] , RES_CONV_MAP[name[:6]] ) def UpperCAmelCase ( UpperCAmelCase ) -> str: for key, value in ATTN_MAP.items(): if name.startswith(UpperCAmelCase ) and not isinstance(UpperCAmelCase , UpperCAmelCase ): return name.replace(UpperCAmelCase , UpperCAmelCase ) elif name.startswith(UpperCAmelCase ): return [name.replace(UpperCAmelCase , UpperCAmelCase ) for v in value] raise ValueError(f'Attn error with {name}' ) def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase=13 ) -> Optional[int]: snake_case_ = input_string if string.split('.' )[0] == "timestep_embed": return string.replace('timestep_embed' , 'time_proj' ) snake_case_ = 0 if string.startswith('net.3.' ): depth += 1 snake_case_ = string[6:] elif string.startswith('net.' ): snake_case_ = string[4:] while string.startswith('main.7.' ): depth += 1 snake_case_ = string[7:] if string.startswith('main.' ): snake_case_ = string[5:] # mid block if string[:2].isdigit(): snake_case_ = string[:2] snake_case_ = string[2:] else: snake_case_ = string[0] snake_case_ = string[1:] if depth == max_depth: snake_case_ = MID_NUM_TO_LAYER[layer_num] snake_case_ = 'mid_block' elif depth > 0 and int(UpperCAmelCase ) < 7: snake_case_ = DOWN_NUM_TO_LAYER[layer_num] snake_case_ = f'down_blocks.{depth}' elif depth > 0 and int(UpperCAmelCase ) > 7: snake_case_ = UP_NUM_TO_LAYER[layer_num] snake_case_ = f'up_blocks.{max_depth - depth - 1}' elif depth == 0: snake_case_ = DEPTH_0_TO_LAYER[layer_num] snake_case_ = f'up_blocks.{max_depth - 1}' if int(UpperCAmelCase ) > 3 else 'down_blocks.0' if not string_left.startswith('.' ): raise ValueError(f'Naming error with {input_string} and string_left: {string_left}.' ) snake_case_ = string_left[1:] if "resnets" in new_layer: snake_case_ = convert_resconv_naming(UpperCAmelCase ) elif "attentions" in new_layer: snake_case_ = convert_attn_naming(UpperCAmelCase ) snake_case_ = new_string_left if not isinstance(UpperCAmelCase , UpperCAmelCase ): snake_case_ = prefix + '.' + new_layer + '.' + string_left else: snake_case_ = [prefix + '.' + new_layer + '.' + s for s in string_left] return new_string def UpperCAmelCase ( UpperCAmelCase ) -> int: snake_case_ = {} for k, v in state_dict.items(): if k.endswith('kernel' ): # up- and downsample layers, don't have trainable weights continue snake_case_ = rename(UpperCAmelCase ) # check if we need to transform from Conv => Linear for attention if isinstance(UpperCAmelCase , UpperCAmelCase ): snake_case_ = transform_conv_attns(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) else: snake_case_ = v return new_state_dict def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Optional[int]: if len(UpperCAmelCase ) == 1: if len(v.shape ) == 3: # weight snake_case_ = v[:, :, 0] else: # bias snake_case_ = v else: # qkv matrices snake_case_ = v.shape[0] snake_case_ = trippled_shape // 3 for i in range(3 ): if len(v.shape ) == 3: snake_case_ = v[i * single_shape : (i + 1) * single_shape, :, 0] else: snake_case_ = v[i * single_shape : (i + 1) * single_shape] return new_state_dict def UpperCAmelCase ( UpperCAmelCase ) -> Union[str, Any]: snake_case_ = torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) snake_case_ = args.model_path.split('/' )[-1].split('.' )[0] if not os.path.isfile(args.model_path ): assert ( model_name == args.model_path ), f'Make sure to provide one of the official model names {MODELS_MAP.keys()}' snake_case_ = download(UpperCAmelCase ) snake_case_ = MODELS_MAP[model_name]['sample_rate'] snake_case_ = MODELS_MAP[model_name]['sample_size'] snake_case_ = Object() snake_case_ = sample_size snake_case_ = sample_rate snake_case_ = 0 snake_case_ = UNetaDModel(sample_size=UpperCAmelCase , sample_rate=UpperCAmelCase ) snake_case_ = diffusers_model.state_dict() snake_case_ = DiffusionUncond(UpperCAmelCase ) orig_model.load_state_dict(torch.load(args.model_path , map_location=UpperCAmelCase )['state_dict'] ) snake_case_ = orig_model.diffusion_ema.eval() snake_case_ = orig_model.state_dict() snake_case_ = rename_orig_weights(UpperCAmelCase ) snake_case_ = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() ) snake_case_ = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() ) assert len(UpperCAmelCase ) == 0, f'Problem with {renamed_minus_diffusers}' assert all(k.endswith('kernel' ) for k in list(UpperCAmelCase ) ), f'Problem with {diffusers_minus_renamed}' for key, value in renamed_state_dict.items(): assert ( diffusers_state_dict[key].squeeze().shape == value.squeeze().shape ), f'Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}' if key == "time_proj.weight": snake_case_ = value.squeeze() snake_case_ = value diffusers_model.load_state_dict(UpperCAmelCase ) snake_case_ = 100 snake_case_ = 33 snake_case_ = IPNDMScheduler(num_train_timesteps=UpperCAmelCase ) snake_case_ = torch.manual_seed(UpperCAmelCase ) snake_case_ = torch.randn([1, 2, config.sample_size] , generator=UpperCAmelCase ).to(UpperCAmelCase ) snake_case_ = torch.linspace(1 , 0 , steps + 1 , device=UpperCAmelCase )[:-1] snake_case_ = get_crash_schedule(UpperCAmelCase ) snake_case_ = DanceDiffusionPipeline(unet=UpperCAmelCase , scheduler=UpperCAmelCase ) snake_case_ = torch.manual_seed(33 ) snake_case_ = pipe(num_inference_steps=UpperCAmelCase , generator=UpperCAmelCase ).audios snake_case_ = sampling.iplms_sample(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , {} ) snake_case_ = generated.clamp(-1 , 1 ) snake_case_ = (generated - audio).abs().sum() snake_case_ = (generated - audio).abs().max() if args.save: pipe.save_pretrained(args.checkpoint_path ) print('Diff sum' , UpperCAmelCase ) print('Diff max' , UpperCAmelCase ) assert diff_max < 1e-3, f'Diff max: {diff_max} is too much :-/' print(f'Conversion for {model_name} successful!' ) if __name__ == "__main__": __UpperCamelCase = argparse.ArgumentParser() parser.add_argument('''--model_path''', default=None, type=str, required=True, help='''Path to the model to convert.''') parser.add_argument( '''--save''', default=True, type=bool, required=False, help='''Whether to save the converted model or not.''' ) parser.add_argument('''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the output model.''') __UpperCamelCase = parser.parse_args() main(args)
69
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE__ : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str=1_3 , SCREAMING_SNAKE_CASE__ : Optional[int]=7 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=9_9 , SCREAMING_SNAKE_CASE__ : str=2_4 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6 , SCREAMING_SNAKE_CASE__ : Optional[int]=3_7 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 , SCREAMING_SNAKE_CASE__ : List[str]=1_6 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Tuple=1_0_0_0 , ) -> str: a_ : Optional[Any] = parent a_ : List[str] = batch_size a_ : List[str] = seq_length a_ : str = is_training a_ : str = use_input_mask a_ : int = use_token_type_ids a_ : List[str] = use_labels a_ : Optional[int] = vocab_size a_ : Any = hidden_size a_ : int = num_hidden_layers a_ : List[str] = num_attention_heads a_ : str = intermediate_size a_ : Union[str, Any] = hidden_act a_ : List[str] = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : int = max_position_embeddings a_ : Tuple = type_vocab_size a_ : Optional[Any] = type_sequence_label_size a_ : Tuple = initializer_range a_ : Dict = num_labels a_ : str = scope a_ : Optional[int] = range_bbox def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a_ : int = bbox[i, j, 3] a_ : str = bbox[i, j, 1] a_ : List[str] = t if bbox[i, j, 2] < bbox[i, j, 0]: a_ : Tuple = bbox[i, j, 2] a_ : List[str] = bbox[i, j, 0] a_ : Union[str, Any] = t a_ : List[Any] = None if self.use_input_mask: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) a_ : List[Any] = None if self.use_token_type_ids: a_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : int = None a_ : Tuple = None if self.use_labels: a_ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : Optional[int] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> str: a_ : Any = LiltModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Any = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> int: a_ : Any = self.num_labels a_ : str = LiltForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> str: a_ : Union[str, Any] = LiltForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : List[str] = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , start_positions=SCREAMING_SNAKE_CASE__ , end_positions=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: a_ : int = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : List[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'bbox': bbox, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Union[str, Any] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) snake_case__ : str = ( { '''feature-extraction''': LiltModel, '''question-answering''': LiltForQuestionAnswering, '''text-classification''': LiltForSequenceClassification, '''token-classification''': LiltForTokenClassification, '''zero-shot''': LiltForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ) -> int: return True def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: a_ : str = LiltModelTester(self ) a_ : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: a_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a_ : List[str] = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: a_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: a_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : List[Any] = LiltModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: a_ : List[str] = LiltModel.from_pretrained('SCUT-DLVCLab/lilt-roberta-en-base' ).to(SCREAMING_SNAKE_CASE__ ) a_ : str = torch.tensor([[1, 2]] , device=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): a_ : str = model(input_ids=SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = torch.Size([1, 2, 7_6_8] ) a_ : int = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=SCREAMING_SNAKE_CASE__ , ) self.assertTrue(outputs.last_hidden_state.shape , SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) )
32
0
'''simple docstring''' import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class UpperCAmelCase ( snake_case_ , unittest.TestCase ): _lowercase: Union[str, Any] = BarthezTokenizer _lowercase: List[str] = BarthezTokenizerFast _lowercase: Tuple = True _lowercase: str = True def lowercase__ ( self : Optional[int] ) -> Any: super().setUp() _lowerCAmelCase = BarthezTokenizerFast.from_pretrained("""moussaKam/mbarthez""" ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=__snake_case ) _lowerCAmelCase = tokenizer def lowercase__ ( self : Optional[int] ) -> int: _lowerCAmelCase = """<pad>""" _lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__snake_case ) , __snake_case ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__snake_case ) , __snake_case ) def lowercase__ ( self : List[str] ) -> Optional[int]: _lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(__snake_case ) , 10_11_22 ) def lowercase__ ( self : Any ) -> Optional[Any]: self.assertEqual(self.get_tokenizer().vocab_size , 10_11_22 ) @require_torch def lowercase__ ( self : int ) -> Union[str, Any]: _lowerCAmelCase = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] _lowerCAmelCase = [0, 57, 30_18, 7_03_07, 91, 2] _lowerCAmelCase = self.tokenizer( __snake_case , max_length=len(__snake_case ) , padding=__snake_case , truncation=__snake_case , return_tensors="""pt""" ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) _lowerCAmelCase = batch.input_ids.tolist()[0] self.assertListEqual(__snake_case , __snake_case ) def lowercase__ ( self : List[Any] ) -> Any: if not self.test_rust_tokenizer: return _lowerCAmelCase = self.get_tokenizer() _lowerCAmelCase = self.get_rust_tokenizer() _lowerCAmelCase = """I was born in 92000, and this is falsรฉ.""" _lowerCAmelCase = tokenizer.tokenize(__snake_case ) _lowerCAmelCase = rust_tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) _lowerCAmelCase = tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) _lowerCAmelCase = rust_tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) self.assertListEqual(__snake_case , __snake_case ) _lowerCAmelCase = self.get_rust_tokenizer() _lowerCAmelCase = tokenizer.encode(__snake_case ) _lowerCAmelCase = rust_tokenizer.encode(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) @slow def lowercase__ ( self : str ) -> List[str]: # fmt: off _lowerCAmelCase = {"""input_ids""": [[0, 4_90, 1_43_28, 45_07, 3_54, 47, 4_36_69, 95, 25, 7_81_17, 2_02_15, 1_97_79, 1_90, 22, 4_00, 4, 3_53_43, 8_03_10, 6_03, 86, 2_49_37, 1_05, 3_34_38, 9_47_62, 1_96, 3_96_42, 7, 15, 1_59_33, 1_73, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1_05_34, 87, 25, 66, 33_58, 1_96, 5_52_89, 8, 8_29_61, 81, 22_04, 7_52_03, 7, 15, 7_63, 1_29_56, 2_16, 1_78, 1_43_28, 95_95, 13_77, 6_96_93, 7, 4_48, 7_10_21, 1_96, 1_81_06, 14_37, 1_39_74, 1_08, 90_83, 4, 4_93_15, 7, 39, 86, 13_26, 27_93, 4_63_33, 4, 4_48, 1_96, 7_45_88, 7, 4_93_15, 7, 39, 21, 8_22, 3_84_70, 74, 21, 6_67_23, 6_24_80, 8, 2_20_50, 5, 2]], """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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. _lowerCAmelCase = [ """Le transformeur est un modรจle d'apprentissage profond introduit en 2017, """ """utilisรฉ principalement dans le domaine du traitement automatique des langues (TAL).""", """ร€ l'instar des rรฉseaux de neurones rรฉcurrents (RNN), les transformeurs sont conรงus """ """pour gรฉrer des donnรฉes sรฉquentielles, telles que le langage naturel, pour des tรขches """ """telles que la traduction et la synthรจse de texte.""", ] self.tokenizer_integration_test_util( expected_encoding=__snake_case , model_name="""moussaKam/mbarthez""" , revision="""c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6""" , sequences=__snake_case , )
70
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple=1_3 , SCREAMING_SNAKE_CASE__ : str=7 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=9_9 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_2 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Tuple=3_7 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=5_1_2 , SCREAMING_SNAKE_CASE__ : int=1_6 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> Any: a_ : Tuple = parent a_ : int = batch_size a_ : Tuple = seq_length a_ : List[Any] = is_training a_ : List[str] = use_token_type_ids a_ : Dict = use_labels a_ : Any = vocab_size a_ : List[str] = hidden_size a_ : Tuple = num_hidden_layers a_ : List[Any] = num_attention_heads a_ : Dict = intermediate_size a_ : Any = hidden_act a_ : List[str] = hidden_dropout_prob a_ : Tuple = attention_probs_dropout_prob a_ : Optional[Any] = max_position_embeddings a_ : List[Any] = type_vocab_size a_ : int = type_sequence_label_size a_ : List[Any] = initializer_range a_ : List[str] = num_labels a_ : Union[str, Any] = num_choices a_ : str = scope a_ : Tuple = self.vocab_size - 1 def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: a_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = None if self.use_token_type_ids: a_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : List[Any] = None a_ : Union[str, Any] = None a_ : List[Any] = None if self.use_labels: a_ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) a_ : Union[str, Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) a_ : List[str] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: a_ : Dict = OpenAIGPTModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , head_mask=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: a_ : str = OpenAIGPTLMHeadModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: a_ : int = OpenAIGPTDoubleHeadsModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Any = self.num_labels a_ : Dict = OpenAIGPTForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : Optional[Any] = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : Optional[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Tuple = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) snake_case__ : List[str] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly snake_case__ : Dict = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any=False ) -> List[str]: a_ : str = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": a_ : Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : str = inputs_dict['labels'] a_ : Optional[int] = inputs_dict['labels'] a_ : Optional[int] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: a_ : str = OpenAIGPTModelTester(self ) a_ : int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , n_embd=3_7 ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: a_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: a_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: a_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : str = OpenAIGPTModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: a_ : Dict = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt' ) model.to(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) # the president is a_ : Tuple = [ 4_8_1, 4_7_3_5, 5_4_4, 2_4_6, 9_6_3, 8_7_0, 7_6_2, 2_3_9, 2_4_4, 4_0_4_7_7, 2_4_4, 2_4_9, 7_1_9, 8_8_1, 4_8_7, 5_4_4, 2_4_0, 2_4_4, 6_0_3, 4_8_1, ] # the president is a very good man. " \n " i\'m sure he is, " said the a_ : Dict = model.generate(SCREAMING_SNAKE_CASE__ , do_sample=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(output_ids[0].tolist() , SCREAMING_SNAKE_CASE__ )
32
0
def A ( ) -> Tuple: __UpperCamelCase : str =0 for i in range(1 ,1_001 ): total += i**i return str(a_ )[-10:] if __name__ == "__main__": print(solution())
71
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase_ : Optional[int] = { 'facebook/mask2former-swin-small-coco-instance': ( 'https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase_ : List[str] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = '''mask2former''' snake_case__ : Any = ['''swin'''] snake_case__ : str = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 1_0 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_5_5 , SCREAMING_SNAKE_CASE__ : int = 1_0_0 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : int , ) -> List[Any]: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) a_ : Dict = CONFIG_MAPPING['swin']( image_size=2_2_4 , in_channels=3 , patch_size=4 , embed_dim=9_6 , depths=[2, 2, 1_8, 2] , num_heads=[3, 6, 1_2, 2_4] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): a_ : Any = backbone_config.pop('model_type' ) a_ : Optional[Any] = CONFIG_MAPPING[backbone_model_type] a_ : List[str] = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # 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 Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) a_ : Dict = backbone_config a_ : List[str] = feature_size a_ : List[str] = mask_feature_size a_ : int = hidden_dim a_ : Dict = encoder_feedforward_dim a_ : str = activation_function a_ : List[str] = encoder_layers a_ : List[str] = decoder_layers a_ : Dict = num_attention_heads a_ : str = dropout a_ : Tuple = dim_feedforward a_ : List[str] = pre_norm a_ : Optional[int] = enforce_input_projection a_ : Any = common_stride a_ : Optional[int] = ignore_value a_ : int = num_queries a_ : Tuple = no_object_weight a_ : Dict = class_weight a_ : Optional[int] = mask_weight a_ : Optional[int] = dice_weight a_ : str = train_num_points a_ : List[str] = oversample_ratio a_ : List[Any] = importance_sample_ratio a_ : Any = init_std a_ : Union[str, Any] = init_xavier_std a_ : Union[str, Any] = use_auxiliary_loss a_ : Dict = feature_strides a_ : List[str] = output_auxiliary_logits a_ : Dict = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def SCREAMING_SNAKE_CASE ( cls : str , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict[str, any]: a_ : Optional[int] = copy.deepcopy(self.__dict__ ) a_ : List[Any] = self.backbone_config.to_dict() a_ : Optional[Any] = self.__class__.model_type return output
32
0
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCAmelCase__ = ''' Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. ''' lowerCAmelCase__ = ''' Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric("pearsonr") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results[\'pearsonr\'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric("pearsonr") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) [\'p-value\', \'pearsonr\'] >>> print(round(results[\'pearsonr\'], 2)) -0.74 >>> print(round(results[\'p-value\'], 2)) 0.15 ''' lowerCAmelCase__ = ''' @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __snake_case ( datasets.Metric): def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[Any]=False ): """simple docstring""" if return_pvalue: _lowerCamelCase : List[Any] = pearsonr(__lowerCAmelCase , __lowerCAmelCase ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__lowerCAmelCase , __lowerCAmelCase )[0] )}
72
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Union[str, Any] = { 'google/switch-base-8': 'https://huggingface.co/google/switch-base-8/blob/main/config.json', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : List[str] = '''switch_transformers''' snake_case__ : Optional[int] = ['''past_key_values'''] snake_case__ : Optional[Any] = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int]=3_2_1_2_8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6_4 , SCREAMING_SNAKE_CASE__ : List[str]=2_0_4_8 , SCREAMING_SNAKE_CASE__ : Dict=6_4 , SCREAMING_SNAKE_CASE__ : List[Any]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3 , SCREAMING_SNAKE_CASE__ : Tuple=1_2 , SCREAMING_SNAKE_CASE__ : Tuple=8 , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.01 , SCREAMING_SNAKE_CASE__ : str="float32" , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_2 , SCREAMING_SNAKE_CASE__ : Dict=1_2_8 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=1E-6 , SCREAMING_SNAKE_CASE__ : Dict=0.001 , SCREAMING_SNAKE_CASE__ : Any=0.001 , SCREAMING_SNAKE_CASE__ : Optional[int]=1.0 , SCREAMING_SNAKE_CASE__ : Any="relu" , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : Optional[int]=1 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: a_ : Optional[int] = vocab_size a_ : List[str] = d_model a_ : Tuple = d_kv a_ : Optional[Any] = d_ff a_ : List[Any] = num_sparse_encoder_layers a_ : Any = num_layers a_ : str = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a_ : List[Any] = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: a_ : Optional[int] = self.num_layers // self.num_sparse_encoder_layers else: a_ : List[Any] = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: a_ : Union[str, Any] = self.num_decoder_layers // self.num_sparse_decoder_layers else: a_ : List[str] = self.num_decoder_layers # HACK: this will create 0 sparse layers a_ : Dict = num_heads a_ : str = num_experts a_ : Any = expert_capacity a_ : List[Any] = router_bias a_ : str = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""" ) a_ : Optional[int] = router_dtype a_ : int = router_ignore_padding_tokens a_ : Any = relative_attention_num_buckets a_ : List[str] = relative_attention_max_distance a_ : Optional[Any] = dropout_rate a_ : Tuple = layer_norm_epsilon a_ : Dict = initializer_factor a_ : Any = feed_forward_proj a_ : Tuple = use_cache a_ : str = add_router_probs a_ : Optional[int] = router_z_loss_coef a_ : List[str] = router_aux_loss_coef a_ : int = self.feed_forward_proj.split('-' ) a_ : int = act_info[-1] a_ : Optional[int] = act_info[0] == 'gated' if len(SCREAMING_SNAKE_CASE__ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE__ ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a_ : Any = 'gelu_new' super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
32
0
from math import sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(sqrt(lowerCamelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1_0_0_0_1 ) -> int: __lowerCamelCase : List[Any] = 0 __lowerCamelCase : str = 1 while count != nth and number < 3: number += 1 if is_prime(lowerCamelCase__ ): count += 1 while count != nth: number += 2 if is_prime(lowerCamelCase__ ): count += 1 return number if __name__ == "__main__": print(F"""{solution() = }""")
73
# 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. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase_ : Tuple = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyรจ': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmรฅl': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''facebook/nllb-200-distilled-600M''' snake_case__ : Union[str, Any] = ( '''This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ''' '''be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ''' '''which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ''' '''plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.''' ) snake_case__ : Optional[Any] = '''translator''' snake_case__ : Tuple = AutoTokenizer snake_case__ : Union[str, Any] = AutoModelForSeqaSeqLM snake_case__ : Dict = LANGUAGE_CODES snake_case__ : str = ['''text''', '''text''', '''text'''] snake_case__ : Tuple = ['''text'''] def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: if src_lang not in self.lang_to_code: raise ValueError(F"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(F"""{tgt_lang} is not a supported language.""" ) a_ : str = self.lang_to_code[src_lang] a_ : Any = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors='pt' , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Tuple ) -> Any: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
32
0
"""simple docstring""" from __future__ import annotations _lowercase = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] _lowercase = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def _snake_case ( snake_case__ : list[float] ): A = [] A = len(snake_case__ ) for i in range(snake_case__ ): A = -1 for j in range(i + 1 , snake_case__ ): if arr[i] < arr[j]: A = arr[j] break result.append(snake_case__ ) return result def _snake_case ( snake_case__ : list[float] ): A = [] for i, outer in enumerate(snake_case__ ): A = -1 for inner in arr[i + 1 :]: if outer < inner: A = inner break result.append(snake_case__ ) return result def _snake_case ( snake_case__ : list[float] ): A = len(snake_case__ ) A = [] A = [-1] * arr_size for index in reversed(range(snake_case__ ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: A = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) _lowercase = ( '''from __main__ import arr, next_greatest_element_slow, ''' '''next_greatest_element_fast, next_greatest_element''' ) print( '''next_greatest_element_slow():''', timeit('''next_greatest_element_slow(arr)''', setup=setup), ) print( '''next_greatest_element_fast():''', timeit('''next_greatest_element_fast(arr)''', setup=setup), ) print( ''' next_greatest_element():''', timeit('''next_greatest_element(arr)''', setup=setup), )
74
UpperCAmelCase_ : Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def SCREAMING_SNAKE_CASE_ ( __A : int , __A : int , __A : int ) -> str: """simple docstring""" assert len(str(__A ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: a_ : List[str] = year // 1_00 a_ : Optional[int] = (5 * (century % 4) + 2) % 7 a_ : List[str] = year % 1_00 a_ : str = centurian % 12 a_ : List[str] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 a_ : Any = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) a_ : Any = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
32
0
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCamelCase ( unittest.TestCase ): def __init__( self, lowerCAmelCase, lowerCAmelCase=3, lowerCAmelCase=32, lowerCAmelCase=3, lowerCAmelCase=10, lowerCAmelCase=[10, 20, 30, 40], lowerCAmelCase=[1, 1, 2, 1], lowerCAmelCase=True, lowerCAmelCase=True, lowerCAmelCase="relu", lowerCAmelCase=3, lowerCAmelCase=None, ): """simple docstring""" lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =image_size lowerCamelCase_ =num_channels lowerCamelCase_ =embeddings_size lowerCamelCase_ =hidden_sizes lowerCamelCase_ =depths lowerCamelCase_ =is_training lowerCamelCase_ =use_labels lowerCamelCase_ =hidden_act lowerCamelCase_ =num_labels lowerCamelCase_ =scope lowerCamelCase_ =len(lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase_ =self.get_config() return config, pixel_values def lowercase__ ( self ): """simple docstring""" return RegNetConfig( num_channels=self.num_channels, embeddings_size=self.embeddings_size, hidden_sizes=self.hidden_sizes, depths=self.depths, hidden_act=self.hidden_act, num_labels=self.num_labels, image_size=self.image_size, ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =FlaxRegNetModel(config=lowerCAmelCase ) lowerCamelCase_ =model(lowerCAmelCase ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32), ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =self.num_labels lowerCamelCase_ =FlaxRegNetForImageClassification(config=lowerCAmelCase ) lowerCamelCase_ =model(lowerCAmelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def lowercase__ ( self ): """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 __UpperCamelCase ( lowerCamelCase__ , unittest.TestCase ): lowercase : List[Any] =(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () lowercase : List[str] =False lowercase : List[str] =False lowercase : Optional[int] =False def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =FlaxRegNetModelTester(self ) lowerCamelCase_ =ConfigTester(self, config_class=lowerCAmelCase, has_text_modality=lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowercase__ ( self ): """simple docstring""" return def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase ) @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def lowercase__ ( self ): """simple docstring""" pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def lowercase__ ( self ): """simple docstring""" pass def lowercase__ ( self ): """simple docstring""" lowerCamelCase_, lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =model_class(lowerCAmelCase ) 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], lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" def check_hidden_states_output(lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ): lowerCamelCase_ =model_class(lowerCAmelCase ) lowerCamelCase_ =model(**self._prepare_for_class(lowerCAmelCase, lowerCAmelCase ) ) lowerCamelCase_ =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase_ =self.model_tester.num_stages self.assertEqual(len(lowerCAmelCase ), expected_num_stages + 1 ) lowerCamelCase_, lowerCamelCase_ =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ =True check_hidden_states_output(lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase_ =True check_hidden_states_output(lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ) def lowercase__ ( self ): """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(lowerCAmelCase, lowerCAmelCase ) lowerCamelCase_ =model_class(lowerCAmelCase ) @jax.jit def model_jitted(lowerCAmelCase, **lowerCAmelCase ): return model(pixel_values=lowerCAmelCase, **lowerCAmelCase ) with self.subTest('''JIT Enabled''' ): lowerCamelCase_ =model_jitted(**lowerCAmelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowerCamelCase_ =model_jitted(**lowerCAmelCase ).to_tuple() self.assertEqual(len(lowerCAmelCase ), len(lowerCAmelCase ) ) for jitted_output, output in zip(lowerCAmelCase, lowerCAmelCase ): self.assertEqual(jitted_output.shape, output.shape ) def a_ ( ) -> int: """simple docstring""" lowerCamelCase_ =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class __UpperCamelCase ( unittest.TestCase ): @cached_property def lowercase__ ( self ): """simple docstring""" return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) lowerCamelCase_ =self.default_image_processor lowerCamelCase_ =prepare_img() lowerCamelCase_ =image_processor(images=lowerCAmelCase, return_tensors='''np''' ) lowerCamelCase_ =model(**lowerCAmelCase ) # verify the logits lowerCamelCase_ =(1, 1_000) self.assertEqual(outputs.logits.shape, lowerCAmelCase ) lowerCamelCase_ =jnp.array([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3], lowerCAmelCase, atol=1e-4 ) )
75
import math import flax.linen as nn import jax.numpy as jnp def SCREAMING_SNAKE_CASE_ ( __A : jnp.ndarray , __A : int , __A : float = 1 , __A : float = 1 , __A : float = 1.0e4 , __A : bool = False , __A : float = 1.0 , ) -> jnp.ndarray: """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F"""Embedding dimension {embedding_dim} should be even""" a_ : int = float(embedding_dim // 2 ) a_ : str = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) a_ : Optional[int] = min_timescale * jnp.exp(jnp.arange(__A , dtype=jnp.floataa ) * -log_timescale_increment ) a_ : Optional[int] = jnp.expand_dims(__A , 1 ) * jnp.expand_dims(__A , 0 ) # scale embeddings a_ : str = scale * emb if flip_sin_to_cos: a_ : str = jnp.concatenate([jnp.cos(__A ), jnp.sin(__A )] , axis=1 ) else: a_ : Any = jnp.concatenate([jnp.sin(__A ), jnp.cos(__A )] , axis=1 ) a_ : Optional[int] = jnp.reshape(__A , [jnp.shape(__A )[0], embedding_dim] ) return signal class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Optional[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_1' )(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = nn.silu(SCREAMING_SNAKE_CASE__ ) a_ : str = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_2' )(SCREAMING_SNAKE_CASE__ ) return temb class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : bool = False snake_case__ : float = 1 @nn.compact def __call__( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Tuple: return get_sinusoidal_embeddings( SCREAMING_SNAKE_CASE__ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
32
0
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 a_ = logging.get_logger(__name__) class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ ='AutoTokenizer' lowerCamelCase__ =['tokenizer'] lowerCamelCase__ ={ 'semantic_prompt': 1, 'coarse_prompt': 2, 'fine_prompt': 2, } def __init__( self : Any , a : int , a : Any=None ) -> List[Any]: """simple docstring""" super().__init__(a ) SCREAMING_SNAKE_CASE : Tuple = speaker_embeddings @classmethod def __UpperCamelCase ( cls : Optional[int] , a : Optional[Any] , a : Any="speaker_embeddings_path.json" , **a : List[str] ) -> List[str]: """simple docstring""" if speaker_embeddings_dict_path is not None: SCREAMING_SNAKE_CASE : List[Any] = 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\n , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json\n dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`." ) SCREAMING_SNAKE_CASE : Union[str, Any] = None else: with open(a ) as speaker_embeddings_json: SCREAMING_SNAKE_CASE : str = json.load(a ) else: SCREAMING_SNAKE_CASE : List[str] = None SCREAMING_SNAKE_CASE : Union[str, Any] = AutoTokenizer.from_pretrained(a , **a ) return cls(tokenizer=a , speaker_embeddings=a ) def __UpperCamelCase ( self : Optional[Any] , a : Tuple , a : Tuple="speaker_embeddings_path.json" , a : Union[str, Any]="speaker_embeddings" , a : bool = False , **a : List[str] , ) -> List[Any]: """simple docstring""" if self.speaker_embeddings is not None: os.makedirs(os.path.join(a , a , "v2" ) , exist_ok=a ) SCREAMING_SNAKE_CASE : Any = {} SCREAMING_SNAKE_CASE : int = save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": SCREAMING_SNAKE_CASE : Tuple = self._load_voice_preset(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = {} 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 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(a , F"{prompt_key}_{key}.npy" ) SCREAMING_SNAKE_CASE : int = tmp_dict with open(os.path.join(a , a ) , "w" ) as fp: json.dump(a , a ) super().save_pretrained(a , a , **a ) def __UpperCamelCase ( self : List[str] , a : str = None , **a : str ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.speaker_embeddings[voice_preset] SCREAMING_SNAKE_CASE : 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}]." ) SCREAMING_SNAKE_CASE : Optional[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\n , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}\n embeddings." ) SCREAMING_SNAKE_CASE : Optional[int] = np.load(a ) return voice_preset_dict def __UpperCamelCase ( self : Dict , a : Optional[dict] = None ) -> List[Any]: """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 : Union[str, Any] , a : Dict=None , a : Dict=None , a : Tuple="pt" , a : List[Any]=256 , a : Optional[Any]=False , a : Tuple=True , a : str=False , **a : List[str] , ) -> Tuple: """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 ): SCREAMING_SNAKE_CASE : str = self._load_voice_preset(a ) else: if isinstance(a , a ) and not voice_preset.endswith(".npz" ): SCREAMING_SNAKE_CASE : List[str] = voice_preset + ".npz" SCREAMING_SNAKE_CASE : Dict = np.load(a ) if voice_preset is not None: self._validate_voice_preset_dict(a , **a ) SCREAMING_SNAKE_CASE : Dict = BatchFeature(data=a , tensor_type=a ) SCREAMING_SNAKE_CASE : str = 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: SCREAMING_SNAKE_CASE : Optional[int] = voice_preset return encoded_text
76
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) UpperCAmelCase_ : str = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCAmelCase_ : Optional[Any] = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) UpperCAmelCase_ : int = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) UpperCAmelCase_ : Union[str, Any] = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) UpperCAmelCase_ : Union[str, Any] = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) UpperCAmelCase_ : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase_ : Dict = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase_ : Dict = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase_ : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase_ : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase_ : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[Any] = FLAX_MODEL_MAPPING UpperCAmelCase_ : Tuple = auto_class_update(FlaxAutoModel) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Any = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[Any] = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase_ : Union[str, Any] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase_ : Optional[int] = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase_ : str = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[str] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase_ : Tuple = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Dict = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase_ : int = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[int] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase_ : Dict = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase_ : str = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[Any] = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase_ : Tuple = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[int] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase_ : Union[str, Any] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
32
0
"""simple docstring""" import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand _UpperCamelCase : List[Any] = ( "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) ) _UpperCamelCase : Tuple = ( ("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"), ) _UpperCamelCase : List[str] = ( ("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), ) _UpperCamelCase : 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), ) _UpperCamelCase : List[Any] = ( ("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]), ) _UpperCamelCase : 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), ) _UpperCamelCase : 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 a_ ( ): '''simple docstring''' lowercase__ , lowercase__ : Dict = randrange(len(_lowerCAmelCase ) ), randrange(len(_lowerCAmelCase ) ) lowercase__ : str = ['Loss', 'Tie', 'Win'][(play >= oppo) + (play > oppo)] lowercase__ , lowercase__ : Dict = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def a_ ( _lowerCAmelCase : int = 100 ): '''simple docstring''' return (generate_random_hand() for _ in range(_lowerCAmelCase )) @pytest.mark.parametrize('hand, expected' , _lowerCAmelCase ) def a_ ( _lowerCAmelCase : List[str] , _lowerCAmelCase : List[str] ): '''simple docstring''' assert PokerHand(_lowerCAmelCase )._is_flush() == expected @pytest.mark.parametrize('hand, expected' , _lowerCAmelCase ) def a_ ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Union[str, Any] ): '''simple docstring''' assert PokerHand(_lowerCAmelCase )._is_straight() == expected @pytest.mark.parametrize('hand, expected, card_values' , _lowerCAmelCase ) def a_ ( _lowerCAmelCase : int , _lowerCAmelCase : List[str] , _lowerCAmelCase : Any ): '''simple docstring''' lowercase__ : Any = PokerHand(_lowerCAmelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('hand, expected' , _lowerCAmelCase ) def a_ ( _lowerCAmelCase : Any , _lowerCAmelCase : Tuple ): '''simple docstring''' assert PokerHand(_lowerCAmelCase )._is_same_kind() == expected @pytest.mark.parametrize('hand, expected' , _lowerCAmelCase ) def a_ ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Optional[Any] ): '''simple docstring''' assert PokerHand(_lowerCAmelCase )._hand_type == expected @pytest.mark.parametrize('hand, other, expected' , _lowerCAmelCase ) def a_ ( _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : Optional[Any] ): '''simple docstring''' assert PokerHand(_lowerCAmelCase ).compare_with(PokerHand(_lowerCAmelCase ) ) == expected @pytest.mark.parametrize('hand, other, expected' , generate_random_hands() ) def a_ ( _lowerCAmelCase : Dict , _lowerCAmelCase : Tuple , _lowerCAmelCase : List[str] ): '''simple docstring''' assert PokerHand(_lowerCAmelCase ).compare_with(PokerHand(_lowerCAmelCase ) ) == expected def a_ ( ): '''simple docstring''' lowercase__ : List[str] = [PokerHand(_lowerCAmelCase ) for hand in SORTED_HANDS] lowercase__ : int = poker_hands.copy() shuffle(_lowerCAmelCase ) lowercase__ : Optional[int] = chain(sorted(_lowerCAmelCase ) ) for index, hand in enumerate(_lowerCAmelCase ): assert hand == poker_hands[index] def a_ ( ): '''simple docstring''' lowercase__ : List[str] = [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 a_ ( ): '''simple docstring''' lowercase__ : int = PokerHand('2C 4S AS 3D 5C' ) lowercase__ : Optional[Any] = True lowercase__ : Optional[int] = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def a_ ( ): '''simple docstring''' lowercase__ : Tuple = 0 lowercase__ : Tuple = os.path.abspath(os.path.dirname(_lowerCAmelCase ) ) lowercase__ : Any = os.path.join(_lowerCAmelCase , 'poker_hands.txt' ) with open(_lowerCAmelCase ) as file_hand: for line in file_hand: lowercase__ : List[str] = line[:14].strip() lowercase__ : Tuple = line[15:].strip() lowercase__ , lowercase__ : List[Any] = PokerHand(_lowerCAmelCase ), PokerHand(_lowerCAmelCase ) lowercase__ : Optional[int] = player.compare_with(_lowerCAmelCase ) if output == "Win": answer += 1 assert answer == 376
77
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): snake_case__ : Any = GPTSanJapaneseTokenizer snake_case__ : Tuple = False snake_case__ : str = {'''do_clean_text''': False, '''add_prefix_space''': False} def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: super().setUp() # fmt: off a_ : Union[str, Any] = ['ใ“ใ‚“', 'ใ“ใ‚“ใซ', 'ใซใกใฏ', 'ใฐใ‚“ใฏ', 'ไธ–็•Œ,ใ”บ็•Œ', 'ใ€', 'ใ€‚', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on a_ : int = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # ๐Ÿ˜€ a_ : List[Any] = {'unk_token': '<unk>'} a_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) a_ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE__ ) ) def SCREAMING_SNAKE_CASE ( self : List[str] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> int: kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> int: a_ : Optional[int] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : List[str] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Dict: a_ , a_ : Union[str, Any] = self.get_input_output_texts(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) a_ : Dict = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) return text, ids def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: a_ : List[str] = self.get_tokenizer() # Testing tokenization a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ€€ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚' a_ : Optional[int] = ['ใ“ใ‚“', 'ใซใกใฏ', 'ใ€', 'ไธ–็•Œ', 'ใ€‚', '<SP>', 'ใ“ใ‚“', 'ใฐใ‚“ใฏ', 'ใ€', 'ใ”บ็•Œ', 'ใ€‚'] a_ : Dict = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids without special tokens a_ : Tuple = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] a_ : List[Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids with special tokens a_ : int = tokens + [tokenizer.unk_token] a_ : int = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9] a_ : Tuple = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: a_ : Union[str, Any] = self.get_tokenizer() # Testing tokenization a_ : Dict = 'ใ“ใ‚“ใซใกใฏใ€<|bagoftoken|>ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€<|bagoftoken|>ใ”บ็•Œใ€‚' a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚' a_ : Any = tokenizer.encode(SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : str ) -> Dict: a_ : Tuple = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' a_ : int = 'ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : Dict = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' a_ : Optional[int] = tokenizer.encode(prefix_text + input_text ) a_ : Any = tokenizer.encode('' , prefix_text=prefix_text + input_text ) a_ : Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) a_ : str = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: a_ : Tuple = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization a_ : str = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' a_ : List[str] = 'ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : str = len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 a_ : Tuple = len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 a_ : Optional[Any] = [1] + [0] * (len_prefix + len_text + 1) a_ : Optional[Any] = [1] * (len_prefix + len_text + 1) + [0] a_ : Tuple = [1] + [1] * (len_prefix) + [0] * (len_text + 1) a_ : List[str] = tokenizer(prefix_text + input_text ).token_type_ids a_ : Union[str, Any] = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids a_ : Any = tokenizer(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: a_ : str = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) a_ : Optional[int] = tokenizer.encode('ใ‚ใƒณใ„ใƒฏ' ) a_ : Dict = tokenizer.encode('' , prefix_text='ใ‚ใƒณใ„ใƒฏ' ) a_ : Dict = tokenizer.encode('ใ„ใƒฏ' , prefix_text='ใ‚ใƒณ' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: a_ : List[str] = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) a_ : Optional[Any] = [['ๆญฆ็”ฐไฟก็Ž„', 'ใฏใ€'], ['็น”็”ฐไฟก้•ท', 'ใฎ้…ไธ‹ใฎใ€']] a_ : List[str] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) a_ : Dict = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) # fmt: off a_ : List[Any] = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]] a_ : Any = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] a_ : List[Any] = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: # tokenizer has no padding token pass
32
0
"""simple docstring""" from collections.abc import Callable import numpy as np def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ): UpperCAmelCase = int(np.ceil((x_end - xa) / step_size ) ) UpperCAmelCase = np.zeros((n + 1,) ) UpperCAmelCase = ya UpperCAmelCase = xa for k in range(lowercase_ ): UpperCAmelCase = y[k] + step_size * ode_func(lowercase_ , y[k] ) UpperCAmelCase = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
78
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, logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Union[str, Any] = ['''pixel_values'''] def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, int]] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 2_5_5 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) a_ : str = size if size is not None else {'shortest_edge': 2_5_6} a_ : Any = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) a_ : Dict = crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4} a_ : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE__ ) a_ : List[str] = do_resize a_ : Dict = size a_ : Optional[Any] = resample a_ : Optional[int] = do_center_crop a_ : Dict = crop_size a_ : int = do_rescale a_ : int = rescale_factor a_ : Tuple = do_normalize a_ : int = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN a_ : Tuple = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> np.ndarray: a_ : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) a_ : Tuple = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=size['shortest_edge'] , default_to_square=SCREAMING_SNAKE_CASE__ ) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> np.ndarray: a_ : str = get_size_dict(SCREAMING_SNAKE_CASE__ ) return center_crop(SCREAMING_SNAKE_CASE__ , size=(size['height'], size['width']) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> np.ndarray: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[float] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> Union[str, Any]: a_ : List[str] = do_resize if do_resize is not None else self.do_resize a_ : Dict = size if size is not None else self.size a_ : Dict = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = resample if resample is not None else self.resample a_ : List[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop a_ : int = crop_size if crop_size is not None else self.crop_size a_ : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE__ ) a_ : Dict = do_rescale if do_rescale is not None else self.do_rescale a_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor a_ : Any = do_normalize if do_normalize is not None else self.do_normalize a_ : str = image_mean if image_mean is not None else self.image_mean a_ : Dict = image_std if image_std is not None else self.image_std a_ : Optional[int] = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. a_ : Any = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: a_ : str = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_center_crop: a_ : int = [self.center_crop(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: a_ : Optional[Any] = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: a_ : List[Any] = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] a_ : Dict = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] a_ : Tuple = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
32
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 lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = {'''vocab_file''': '''vocab.txt'''} lowerCamelCase_ = { '''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''', } } lowerCamelCase_ = { '''YituTech/conv-bert-base''': 5_12, '''YituTech/conv-bert-medium-small''': 5_12, '''YituTech/conv-bert-small''': 5_12, } lowerCamelCase_ = { '''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 _UpperCAmelCase ( snake_case_ ): """simple docstring""" snake_case = VOCAB_FILES_NAMES snake_case = PRETRAINED_VOCAB_FILES_MAP snake_case = PRETRAINED_INIT_CONFIGURATION snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case = ConvBertTokenizer def __init__( self : Union[str, Any] , __UpperCAmelCase : Tuple=None , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : int=True , __UpperCAmelCase : str="[UNK]" , __UpperCAmelCase : Optional[Any]="[SEP]" , __UpperCAmelCase : List[Any]="[PAD]" , __UpperCAmelCase : Optional[int]="[CLS]" , __UpperCAmelCase : Optional[Any]="[MASK]" , __UpperCAmelCase : Any=True , __UpperCAmelCase : Dict=None , **__UpperCAmelCase : List[str] , ): '''simple docstring''' super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) _A = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , __UpperCAmelCase ) != do_lower_case or normalizer_state.get("strip_accents" , __UpperCAmelCase ) != strip_accents or normalizer_state.get("handle_chinese_chars" , __UpperCAmelCase ) != tokenize_chinese_chars ): _A = getattr(__UpperCAmelCase , normalizer_state.pop("type" ) ) _A = do_lower_case _A = strip_accents _A = tokenize_chinese_chars _A = normalizer_class(**__UpperCAmelCase ) _A = do_lower_case def lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Any=None ): '''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 lowerCAmelCase ( self : int , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ): '''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 lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ): '''simple docstring''' _A = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
79
def SCREAMING_SNAKE_CASE_ ( __A : list[int] , __A : str ) -> list[int]: """simple docstring""" a_ : Any = int(__A ) # Initialize Result a_ : Tuple = [] # Traverse through all denomination for denomination in reversed(__A ): # Find denominations while int(__A ) >= int(__A ): total_value -= int(__A ) answer.append(__A ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = [] UpperCAmelCase_ : Union[str, Any] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase_ : List[Any] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(F'Denomination {i}: ').strip())) UpperCAmelCase_ : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase_ : List[Any] = [1, 2, 5, 10, 20, 50, 100, 500, 2000] UpperCAmelCase_ : str = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(F'Following is minimal change for {value}: ') UpperCAmelCase_ : Optional[Any] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
32
0
'''simple docstring''' import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers a__ : Dict = 'python tqdm regex requests packaging filelock numpy tokenizers'.split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append('dataclasses') if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append('importlib_metadata') for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(F"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""") def _UpperCamelCase ( __A , __A=None ) -> Any: '''simple docstring''' require_version(deps[pkg] , __A )
80
import flax.linen as nn import jax import jax.numpy as jnp class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : str ) -> int: a_ : Dict = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: a_ , a_ , a_ , a_ : Union[str, Any] = hidden_states.shape a_ : List[str] = jax.image.resize( SCREAMING_SNAKE_CASE__ , shape=(batch, height * 2, width * 2, channels) , method='nearest' , ) a_ : Any = self.conv(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: a_ : Optional[int] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]: # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim # hidden_states = jnp.pad(hidden_states, pad_width=pad) a_ : str = self.conv(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int snake_case__ : int = None snake_case__ : float = 0.0 snake_case__ : bool = None snake_case__ : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: a_ : List[str] = self.in_channels if self.out_channels is None else self.out_channels a_ : Optional[int] = nn.GroupNorm(num_groups=3_2 , epsilon=1E-5 ) a_ : Any = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) a_ : Optional[int] = nn.Dense(SCREAMING_SNAKE_CASE__ , dtype=self.dtype ) a_ : Union[str, Any] = nn.GroupNorm(num_groups=3_2 , epsilon=1E-5 ) a_ : int = nn.Dropout(self.dropout_prob ) a_ : Optional[Any] = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) a_ : List[str] = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut a_ : List[Any] = None if use_nin_shortcut: a_ : Union[str, Any] = nn.Conv( SCREAMING_SNAKE_CASE__ , kernel_size=(1, 1) , strides=(1, 1) , padding='VALID' , dtype=self.dtype , ) def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any]=True ) -> int: a_ : List[Any] = hidden_states a_ : Any = self.norma(SCREAMING_SNAKE_CASE__ ) a_ : Any = nn.swish(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = self.conva(SCREAMING_SNAKE_CASE__ ) a_ : int = self.time_emb_proj(nn.swish(SCREAMING_SNAKE_CASE__ ) ) a_ : List[str] = jnp.expand_dims(jnp.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , 1 ) a_ : Optional[int] = hidden_states + temb a_ : List[str] = self.norma(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = nn.swish(SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.dropout(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = self.conva(SCREAMING_SNAKE_CASE__ ) if self.conv_shortcut is not None: a_ : List[str] = self.conv_shortcut(SCREAMING_SNAKE_CASE__ ) return hidden_states + residual
32
0
"""simple docstring""" import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() lowerCamelCase_ : int = { """bart""": ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), """bert""": ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-large-uncased-whole-word-masking-finetuned-squad""": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-large-cased-whole-word-masking-finetuned-squad""": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """bert-base-cased-finetuned-mrpc""": ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """dpr""": ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), """gpt2""": ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlnet""": ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlm""": ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """xlm-roberta""": ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """transfo-xl""": ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """openai-gpt""": ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """roberta""": ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """layoutlm""": ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), """roberta-large-mnli""": ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """camembert""": ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """flaubert""": ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """distilbert""": ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """distilbert-base-distilled-squad""": ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """lxmert""": ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """lxmert-visual-feature-encoder""": ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """ctrl""": ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """albert""": ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """t5""": ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """electra""": ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), """wav2vec2""": ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def _A ( lowercase , lowercase , lowercase , lowercase , lowercase=False , lowercase=True ): """simple docstring""" if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.''' ) a , a , a , a =MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: a =cached_file(lowercase , lowercase , force_download=not use_cached_models ) a =config_class.from_json_file(lowercase ) a =True a =True print(f'''Building TensorFlow model from configuration: {config}''' ) a =model_class(lowercase ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): a =cached_file( lowercase , lowercase , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: a =load_pytorch_checkpoint_in_tfa_model(lowercase , lowercase ) if compare_with_pt_model: a =tf_model(tf_model.dummy_inputs , training=lowercase ) # build the network a =torch.load(lowercase , map_location='''cpu''' ) a =pt_model_class.from_pretrained( pretrained_model_name_or_path=lowercase , config=lowercase , state_dict=lowercase ) with torch.no_grad(): a =pt_model(**pt_model.dummy_inputs ) a =pto[0].numpy() a =tfo[0].numpy() a =np.amax(np.abs(np_pt - np_tf ) ) print(f'''Max absolute difference between models outputs {diff}''' ) assert diff <= 2E-2, f'''Error, model absolute difference is >2e-2: {diff}''' # Save pytorch-model print(f'''Save TensorFlow model to {tf_dump_path}''' ) tf_model.save_weights(lowercase , save_format='''h5''' ) def _A ( lowercase , lowercase , lowercase=None , lowercase=None , lowercase=False , lowercase=False , lowercase=False , lowercase=False , ): """simple docstring""" if args_model_type is None: a =list(MODEL_CLASSES.keys() ) else: a =[args_model_type] for j, model_type in enumerate(lowercase , start=1 ): print('''=''' * 1_00 ) print(f''' Converting model type {j}/{len(lowercase )}: {model_type}''' ) print('''=''' * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(f'''Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.''' ) a , a , a , a , a =MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: a =list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: a =model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(lowercase , lowercase ) , start=1 ): print('''-''' * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(f''' Skipping finetuned checkpoint {model_shortcut_name}''' ) continue a =model_shortcut_name elif only_convert_finetuned_models: print(f''' Skipping not finetuned checkpoint {model_shortcut_name}''' ) continue print( f''' Converting checkpoint {i}/{len(lowercase )}: {model_shortcut_name} - model_type {model_type}''' ) print('''-''' * 1_00 ) if config_shortcut_name in aws_config_map: a =cached_file(lowercase , lowercase , force_download=not use_cached_models ) else: a =config_shortcut_name if model_shortcut_name in aws_model_maps: a =cached_file(lowercase , lowercase , force_download=not use_cached_models ) else: a =model_shortcut_name if os.path.isfile(lowercase ): a ='''converted_model''' convert_pt_checkpoint_to_tf( model_type=lowercase , pytorch_checkpoint_path=lowercase , config_file=lowercase , tf_dump_path=os.path.join(lowercase , model_shortcut_name + '''-tf_model.h5''' ) , compare_with_pt_model=lowercase , ) if remove_cached_files: os.remove(lowercase ) os.remove(lowercase ) if __name__ == "__main__": lowerCamelCase_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_dump_path""", default=None, type=str, required=True, help="""Path to the output Tensorflow dump file.""" ) parser.add_argument( """--model_type""", default=None, type=str, help=( F'Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and ' """convert all the models from AWS.""" ), ) parser.add_argument( """--pytorch_checkpoint_path""", default=None, type=str, help=( """Path to the PyTorch checkpoint path or shortcut name to download from AWS. """ """If not given, will download and convert all the checkpoints from AWS.""" ), ) parser.add_argument( """--config_file""", default=None, type=str, help=( """The config json file corresponding to the pre-trained model. \n""" """This specifies the model architecture. If not given and """ """--pytorch_checkpoint_path is not given or is a shortcut name """ """use the configuration associated to the shortcut name on the AWS""" ), ) parser.add_argument( """--compare_with_pt_model""", action="""store_true""", help="""Compare Tensorflow and PyTorch model predictions.""" ) parser.add_argument( """--use_cached_models""", action="""store_true""", help="""Use cached models if possible instead of updating to latest checkpoint versions.""", ) parser.add_argument( """--remove_cached_files""", action="""store_true""", help="""Remove pytorch models after conversion (save memory when converting in batches).""", ) parser.add_argument("""--only_convert_finetuned_models""", action="""store_true""", help="""Only convert finetuned models.""") lowerCamelCase_ : List[Any] = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
81
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. UpperCAmelCase_ : Dict = {'LayoutLMv2Config', 'LayoutLMv3Config'} @is_pipeline_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): snake_case__ : List[str] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING snake_case__ : Optional[Any] = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: snake_case__ : str = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: snake_case__ : List[Any] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: a_ : List[Any] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' ) a_ : int = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) a_ : Tuple = text_classifier('This is great !' , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}] ) a_ : List[str] = text_classifier(['This is great !', 'This is bad'] , top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], ] , ) a_ : Tuple = text_classifier('This is great !' , top_k=1 ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) # Legacy behavior a_ : Union[str, Any] = text_classifier('This is great !' , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) a_ : List[str] = text_classifier('This is great !' , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}]] ) a_ : int = text_classifier(['This is great !', 'Something else'] , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}], ] , ) a_ : str = text_classifier(['This is great !', 'Something else'] , return_all_scores=SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [ {'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_0', 'score': 0.504}, ] , ) @require_torch def SCREAMING_SNAKE_CASE ( self : int ) -> Dict: import torch a_ : List[Any] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='pt' , device=torch.device('cpu' ) , ) a_ : Any = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) @require_tf def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: a_ : List[str] = pipeline( task='text-classification' , model='hf-internal-testing/tiny-random-distilbert' , framework='tf' ) a_ : Optional[int] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'LABEL_0', 'score': 0.504}] ) @slow @require_torch def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: a_ : List[str] = pipeline('text-classification' ) a_ : Dict = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 1.0}] ) a_ : Union[str, Any] = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'NEGATIVE', 'score': 1.0}] ) a_ : Tuple = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 0.988}] ) @slow @require_tf def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: a_ : Dict = pipeline('text-classification' , framework='tf' ) a_ : Optional[Any] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 1.0}] ) a_ : int = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'NEGATIVE', 'score': 1.0}] ) a_ : Optional[int] = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': 'POSITIVE', 'score': 0.988}] ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: a_ : Optional[Any] = TextClassificationPipeline(model=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ ) return text_classifier, ["HuggingFace is in", "This is another test"] def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: a_ : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 a_ : Union[str, Any] = 'HuggingFace is in' a_ : int = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) a_ : Union[str, Any] = ['HuggingFace is in ', 'Paris is in France'] a_ : int = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}, {'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) self.assertTrue(outputs[1]['label'] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format a_ : List[Any] = text_classifier(SCREAMING_SNAKE_CASE__ , top_k=SCREAMING_SNAKE_CASE__ ) a_ : Dict = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [[{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] * N, [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] * N] , ) a_ : int = {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'} a_ : Optional[int] = text_classifier(SCREAMING_SNAKE_CASE__ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , {'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )} , ) self.assertTrue(outputs['label'] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. a_ : Any = [['HuggingFace is in ', 'Paris is in France']] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): text_classifier(SCREAMING_SNAKE_CASE__ ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility a_ : Tuple = text_classifier([[['HuggingFace is in ', 'Paris is in France']]] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , [{'label': ANY(SCREAMING_SNAKE_CASE__ ), 'score': ANY(SCREAMING_SNAKE_CASE__ )}] , ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )
32
0
import inspect import unittest from transformers import ConvNextConfig 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_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __lowerCAmelCase : def __init__( self , _snake_case , _snake_case=13 , _snake_case=32 , _snake_case=3 , _snake_case=4 , _snake_case=[10, 20, 30, 40] , _snake_case=[2, 2, 3, 2] , _snake_case=True , _snake_case=True , _snake_case=37 , _snake_case="gelu" , _snake_case=10 , _snake_case=0.02 , _snake_case=["stage2", "stage3", "stage4"] , _snake_case=[2, 3, 4] , _snake_case=None , ): """simple docstring""" _lowerCAmelCase = parent _lowerCAmelCase = batch_size _lowerCAmelCase = image_size _lowerCAmelCase = num_channels _lowerCAmelCase = num_stages _lowerCAmelCase = hidden_sizes _lowerCAmelCase = depths _lowerCAmelCase = is_training _lowerCAmelCase = use_labels _lowerCAmelCase = intermediate_size _lowerCAmelCase = hidden_act _lowerCAmelCase = num_labels _lowerCAmelCase = initializer_range _lowerCAmelCase = out_features _lowerCAmelCase = out_indices _lowerCAmelCase = scope def snake_case ( self ): """simple docstring""" _lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase = None if self.use_labels: _lowerCAmelCase = ids_tensor([self.batch_size] , self.num_labels ) _lowerCAmelCase = self.get_config() return config, pixel_values, labels def snake_case ( self ): """simple docstring""" return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_snake_case , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def snake_case ( self , _snake_case , _snake_case , _snake_case ): """simple docstring""" _lowerCAmelCase = ConvNextModel(config=_snake_case ) model.to(_snake_case ) model.eval() _lowerCAmelCase = model(_snake_case ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def snake_case ( self , _snake_case , _snake_case , _snake_case ): """simple docstring""" _lowerCAmelCase = ConvNextForImageClassification(_snake_case ) model.to(_snake_case ) model.eval() _lowerCAmelCase = model(_snake_case , labels=_snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def snake_case ( self , _snake_case , _snake_case , _snake_case ): """simple docstring""" _lowerCAmelCase = ConvNextBackbone(config=_snake_case ) model.to(_snake_case ) model.eval() _lowerCAmelCase = model(_snake_case ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _lowerCAmelCase = None _lowerCAmelCase = ConvNextBackbone(config=_snake_case ) model.to(_snake_case ) model.eval() _lowerCAmelCase = model(_snake_case ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = config_and_inputs _lowerCAmelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) __lowerCamelCase = ( {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification} if is_torch_available() else {} ) __lowerCamelCase = True __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def snake_case ( self ): """simple docstring""" _lowerCAmelCase = ConvNextModelTester(self ) _lowerCAmelCase = ConfigTester(self , config_class=_snake_case , has_text_modality=_snake_case , hidden_size=37 ) def snake_case ( self ): """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def snake_case ( self ): """simple docstring""" return @unittest.skip(reason="""ConvNext does not use inputs_embeds""" ) def snake_case ( self ): """simple docstring""" pass @unittest.skip(reason="""ConvNext does not support input and output embeddings""" ) def snake_case ( self ): """simple docstring""" pass @unittest.skip(reason="""ConvNext does not use feedforward chunking""" ) def snake_case ( self ): """simple docstring""" pass def snake_case ( self ): """simple docstring""" _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase = model_class(_snake_case ) _lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase = [*signature.parameters.keys()] _lowerCAmelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _snake_case ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_snake_case ) def snake_case ( self ): """simple docstring""" def check_hidden_states_output(_snake_case , _snake_case , _snake_case ): _lowerCAmelCase = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): _lowerCAmelCase = model(**self._prepare_for_class(_snake_case , _snake_case ) ) _lowerCAmelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _lowerCAmelCase = self.model_tester.num_stages self.assertEqual(len(_snake_case ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase = True check_hidden_states_output(_snake_case , _snake_case , _snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCAmelCase = True check_hidden_states_output(_snake_case , _snake_case , _snake_case ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_snake_case ) @slow def snake_case ( self ): """simple docstring""" for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase = ConvNextModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) def _UpperCAmelCase ( ): """simple docstring""" _lowerCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase ): @cached_property def snake_case ( self ): """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224""" ) if is_vision_available() else None @slow def snake_case ( self ): """simple docstring""" _lowerCAmelCase = ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224""" ).to(_snake_case ) _lowerCAmelCase = self.default_image_processor _lowerCAmelCase = prepare_img() _lowerCAmelCase = image_processor(images=_snake_case , return_tensors="""pt""" ).to(_snake_case ) # forward pass with torch.no_grad(): _lowerCAmelCase = model(**_snake_case ) # verify the logits _lowerCAmelCase = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _snake_case ) _lowerCAmelCase = torch.tensor([-0.0260, -0.4739, 0.1911] ).to(_snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _snake_case , atol=1e-4 ) ) @require_torch class __lowerCAmelCase ( unittest.TestCase , lowerCamelCase__ ): __lowerCamelCase = (ConvNextBackbone,) if is_torch_available() else () __lowerCamelCase = ConvNextConfig __lowerCamelCase = False def snake_case ( self ): """simple docstring""" _lowerCAmelCase = ConvNextModelTester(self )
82
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : str = 'T5Config' def SCREAMING_SNAKE_CASE_ ( __A : jnp.array , __A : int , __A : int ) -> jnp.ndarray: """simple docstring""" a_ : Dict = jnp.zeros_like(__A ) a_ : Dict = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) a_ : str = shifted_input_ids.at[:, 0].set(__A ) a_ : int = jnp.where(shifted_input_ids == -1_00 , __A , __A ) return shifted_input_ids class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[Any] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[str] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = '''mt5''' snake_case__ : Union[str, Any] = MTaConfig
32
0
'''simple docstring''' from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def A__ ( UpperCAmelCase_ ): return {key.lstrip('-' ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def A__ ( ): _UpperCamelCase : Tuple = ArgumentParser( 'HuggingFace Datasets CLI tool' , usage='datasets-cli <command> [<args>]' , allow_abbrev=UpperCAmelCase_ ) _UpperCamelCase : Dict = parser.add_subparsers(help='datasets-cli command helpers' ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(UpperCAmelCase_ ) EnvironmentCommand.register_subcommand(UpperCAmelCase_ ) TestCommand.register_subcommand(UpperCAmelCase_ ) RunBeamCommand.register_subcommand(UpperCAmelCase_ ) DummyDataCommand.register_subcommand(UpperCAmelCase_ ) # Parse args _UpperCamelCase , _UpperCamelCase : List[Any] = parser.parse_known_args() if not hasattr(UpperCAmelCase_ , 'func' ): parser.print_help() exit(1 ) _UpperCamelCase : List[str] = parse_unknown_args(UpperCAmelCase_ ) # Run _UpperCamelCase : Tuple = args.func(UpperCAmelCase_ , **UpperCAmelCase_ ) service.run() if __name__ == "__main__": main()
83
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent UpperCAmelCase_ : Any = {'UserAgent': UserAgent().random} def SCREAMING_SNAKE_CASE_ ( __A : Optional[int] ) -> dict: """simple docstring""" a_ : Tuple = script.contents[0] a_ : int = json.loads(data[data.find('{"config"' ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: a_ : Tuple = F"""https://www.instagram.com/{username}/""" a_ : Optional[Any] = self.get_json() def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> dict: a_ : Any = requests.get(self.url , headers=SCREAMING_SNAKE_CASE__ ).text a_ : Dict = BeautifulSoup(SCREAMING_SNAKE_CASE__ , 'html.parser' ).find_all('script' ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Union[str, Any] ) -> str: return F"""{self.__class__.__name__}('{self.username}')""" def __str__( self : Optional[int] ) -> str: return F"""{self.fullname} ({self.username}) is {self.biography}""" @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: return self.user_data["username"] @property def SCREAMING_SNAKE_CASE ( self : str ) -> str: return self.user_data["full_name"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> str: return self.user_data["biography"] @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: return self.user_data["business_email"] @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: return self.user_data["external_url"] @property def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return self.user_data["edge_followed_by"]["count"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> int: return self.user_data["edge_follow"]["count"] @property def SCREAMING_SNAKE_CASE ( self : str ) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: return self.user_data["profile_pic_url_hd"] @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> bool: return self.user_data["is_verified"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.user_data["is_private"] def SCREAMING_SNAKE_CASE_ ( __A : str = "github" ) -> None: """simple docstring""" import os if os.environ.get('CI' ): return # test failing on GitHub Actions a_ : int = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 1_50 assert instagram_user.number_of_followers > 12_00_00 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith('https://instagram.' ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase_ : Union[str, Any] = InstagramUser('github') print(instagram_user) print(F'{instagram_user.number_of_posts = }') print(F'{instagram_user.number_of_followers = }') print(F'{instagram_user.number_of_followings = }') print(F'{instagram_user.email = }') print(F'{instagram_user.website = }') print(F'{instagram_user.profile_picture_url = }') print(F'{instagram_user.is_verified = }') print(F'{instagram_user.is_private = }')
32
0
"""simple docstring""" import argparse import collections import json import os import re import string import sys import numpy as np __UpperCAmelCase = re.compile(R'\b(a|an|the)\b', re.UNICODE) __UpperCAmelCase = None def _snake_case ( ) -> List[str]: '''simple docstring''' lowerCAmelCase_ :Optional[int] = argparse.ArgumentParser("""Official evaluation script for SQuAD version 2.0.""" ) parser.add_argument("""data_file""" , metavar="""data.json""" , help="""Input data JSON file.""" ) parser.add_argument("""pred_file""" , metavar="""pred.json""" , help="""Model predictions.""" ) parser.add_argument( """--out-file""" , """-o""" , metavar="""eval.json""" , help="""Write accuracy metrics to file (default is stdout).""" ) parser.add_argument( """--na-prob-file""" , """-n""" , metavar="""na_prob.json""" , help="""Model estimates of probability of no answer.""" ) parser.add_argument( """--na-prob-thresh""" , """-t""" , type=lowercase__ , default=1.0 , help="""Predict \"\" if no-answer probability exceeds this (default = 1.0).""" , ) parser.add_argument( """--out-image-dir""" , """-p""" , metavar="""out_images""" , default=lowercase__ , help="""Save precision-recall curves to directory.""" ) parser.add_argument("""--verbose""" , """-v""" , action="""store_true""" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _snake_case ( lowercase__ : int ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase_ :Tuple = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: lowerCAmelCase_ :Any = bool(qa["""answers"""]["""text"""] ) return qid_to_has_ans def _snake_case ( lowercase__ : Optional[Any] ) -> Any: '''simple docstring''' def remove_articles(lowercase__ : int ): return ARTICLES_REGEX.sub(""" """ , lowercase__ ) def white_space_fix(lowercase__ : List[str] ): return " ".join(text.split() ) def remove_punc(lowercase__ : Union[str, Any] ): lowerCAmelCase_ :List[Any] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase__ : List[str] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase__ ) ) ) ) def _snake_case ( lowercase__ : Optional[Any] ) -> Dict: '''simple docstring''' if not s: return [] return normalize_answer(lowercase__ ).split() def _snake_case ( lowercase__ : Any , lowercase__ : Any ) -> Optional[int]: '''simple docstring''' return int(normalize_answer(lowercase__ ) == normalize_answer(lowercase__ ) ) def _snake_case ( lowercase__ : List[str] , lowercase__ : int ) -> Optional[int]: '''simple docstring''' lowerCAmelCase_ :Any = get_tokens(lowercase__ ) lowerCAmelCase_ :str = get_tokens(lowercase__ ) lowerCAmelCase_ :Optional[Any] = collections.Counter(lowercase__ ) & collections.Counter(lowercase__ ) lowerCAmelCase_ :Optional[int] = sum(common.values() ) if len(lowercase__ ) == 0 or len(lowercase__ ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 lowerCAmelCase_ :Dict = 1.0 * num_same / len(lowercase__ ) lowerCAmelCase_ :str = 1.0 * num_same / len(lowercase__ ) lowerCAmelCase_ :List[Any] = (2 * precision * recall) / (precision + recall) return fa def _snake_case ( lowercase__ : Tuple , lowercase__ : str ) -> Optional[int]: '''simple docstring''' lowerCAmelCase_ :int = {} lowerCAmelCase_ :Dict = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: lowerCAmelCase_ :Tuple = qa["""id"""] lowerCAmelCase_ :Union[str, Any] = [t for t in qa["""answers"""]["""text"""] if normalize_answer(lowercase__ )] if not gold_answers: # For unanswerable questions, only correct answer is empty string lowerCAmelCase_ :Any = [""""""] if qid not in preds: print(f"""Missing prediction for {qid}""" ) continue lowerCAmelCase_ :List[str] = preds[qid] # Take max over all gold answers lowerCAmelCase_ :Any = max(compute_exact(lowercase__ , lowercase__ ) for a in gold_answers ) lowerCAmelCase_ :List[str] = max(compute_fa(lowercase__ , lowercase__ ) for a in gold_answers ) return exact_scores, fa_scores def _snake_case ( lowercase__ : Any , lowercase__ : Dict , lowercase__ : Tuple , lowercase__ : List[str] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase_ :Any = {} for qid, s in scores.items(): lowerCAmelCase_ :str = na_probs[qid] > na_prob_thresh if pred_na: lowerCAmelCase_ :List[str] = float(not qid_to_has_ans[qid] ) else: lowerCAmelCase_ :Optional[Any] = s return new_scores def _snake_case ( lowercase__ : List[str] , lowercase__ : Dict , lowercase__ : str=None ) -> Dict: '''simple docstring''' if not qid_list: lowerCAmelCase_ :Dict = len(lowercase__ ) return collections.OrderedDict( [ ("""exact""", 100.0 * sum(exact_scores.values() ) / total), ("""f1""", 100.0 * sum(fa_scores.values() ) / total), ("""total""", total), ] ) else: lowerCAmelCase_ :int = len(lowercase__ ) return collections.OrderedDict( [ ("""exact""", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("""f1""", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("""total""", total), ] ) def _snake_case ( lowercase__ : Dict , lowercase__ : List[Any] , lowercase__ : List[str] ) -> Tuple: '''simple docstring''' for k in new_eval: lowerCAmelCase_ :int = new_eval[k] def _snake_case ( lowercase__ : Optional[Any] , lowercase__ : Any , lowercase__ : str , lowercase__ : str ) -> Dict: '''simple docstring''' plt.step(lowercase__ , lowercase__ , color="""b""" , alpha=0.2 , where="""post""" ) plt.fill_between(lowercase__ , lowercase__ , step="""post""" , alpha=0.2 , color="""b""" ) plt.xlabel("""Recall""" ) plt.ylabel("""Precision""" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(lowercase__ ) plt.savefig(lowercase__ ) plt.clf() def _snake_case ( lowercase__ : int , lowercase__ : int , lowercase__ : Tuple , lowercase__ : List[str] , lowercase__ : Union[str, Any]=None , lowercase__ : List[Any]=None ) -> int: '''simple docstring''' lowerCAmelCase_ :int = sorted(lowercase__ , key=lambda lowercase__ : na_probs[k] ) lowerCAmelCase_ :Tuple = 0.0 lowerCAmelCase_ :List[str] = 1.0 lowerCAmelCase_ :Optional[Any] = 0.0 lowerCAmelCase_ :List[str] = [1.0] lowerCAmelCase_ :Dict = [0.0] lowerCAmelCase_ :str = 0.0 for i, qid in enumerate(lowercase__ ): if qid_to_has_ans[qid]: true_pos += scores[qid] lowerCAmelCase_ :List[Any] = true_pos / float(i + 1 ) lowerCAmelCase_ :List[Any] = true_pos / float(lowercase__ ) if i == len(lowercase__ ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(lowercase__ ) recalls.append(lowercase__ ) if out_image: plot_pr_curve(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) return {"ap": 100.0 * avg_prec} def _snake_case ( lowercase__ : str , lowercase__ : Tuple , lowercase__ : int , lowercase__ : Any , lowercase__ : str , lowercase__ : int ) -> Union[str, Any]: '''simple docstring''' if out_image_dir and not os.path.exists(lowercase__ ): os.makedirs(lowercase__ ) lowerCAmelCase_ :Dict = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return lowerCAmelCase_ :Optional[int] = make_precision_recall_eval( lowercase__ , lowercase__ , lowercase__ , lowercase__ , out_image=os.path.join(lowercase__ , """pr_exact.png""" ) , title="""Precision-Recall curve for Exact Match score""" , ) lowerCAmelCase_ :int = make_precision_recall_eval( lowercase__ , lowercase__ , lowercase__ , lowercase__ , out_image=os.path.join(lowercase__ , """pr_f1.png""" ) , title="""Precision-Recall curve for F1 score""" , ) lowerCAmelCase_ :List[str] = {k: float(lowercase__ ) for k, v in qid_to_has_ans.items()} lowerCAmelCase_ :str = make_precision_recall_eval( lowercase__ , lowercase__ , lowercase__ , lowercase__ , out_image=os.path.join(lowercase__ , """pr_oracle.png""" ) , title="""Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)""" , ) merge_eval(lowercase__ , lowercase__ , """pr_exact""" ) merge_eval(lowercase__ , lowercase__ , """pr_f1""" ) merge_eval(lowercase__ , lowercase__ , """pr_oracle""" ) def _snake_case ( lowercase__ : Tuple , lowercase__ : List[Any] , lowercase__ : Dict , lowercase__ : int ) -> List[Any]: '''simple docstring''' if not qid_list: return lowerCAmelCase_ :str = [na_probs[k] for k in qid_list] lowerCAmelCase_ :Tuple = np.ones_like(lowercase__ ) / float(len(lowercase__ ) ) plt.hist(lowercase__ , weights=lowercase__ , bins=2_0 , range=(0.0, 1.0) ) plt.xlabel("""Model probability of no-answer""" ) plt.ylabel("""Proportion of dataset""" ) plt.title(f"""Histogram of no-answer probability: {name}""" ) plt.savefig(os.path.join(lowercase__ , f"""na_prob_hist_{name}.png""" ) ) plt.clf() def _snake_case ( lowercase__ : Tuple , lowercase__ : Optional[int] , lowercase__ : Tuple , lowercase__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase_ :int = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) lowerCAmelCase_ :List[Any] = num_no_ans lowerCAmelCase_ :int = cur_score lowerCAmelCase_ :Optional[Any] = 0.0 lowerCAmelCase_ :Union[str, Any] = sorted(lowercase__ , key=lambda lowercase__ : na_probs[k] ) for i, qid in enumerate(lowercase__ ): if qid not in scores: continue if qid_to_has_ans[qid]: lowerCAmelCase_ :Optional[int] = scores[qid] else: if preds[qid]: lowerCAmelCase_ :Optional[int] = -1 else: lowerCAmelCase_ :Union[str, Any] = 0 cur_score += diff if cur_score > best_score: lowerCAmelCase_ :Dict = cur_score lowerCAmelCase_ :Tuple = na_probs[qid] return 100.0 * best_score / len(lowercase__ ), best_thresh def _snake_case ( lowercase__ : Dict , lowercase__ : List[str] , lowercase__ : Optional[int] , lowercase__ : Optional[Any] , lowercase__ : Any , lowercase__ : Union[str, Any] ) -> List[Any]: '''simple docstring''' lowerCAmelCase_ , lowerCAmelCase_ :Any = find_best_thresh(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) lowerCAmelCase_ , lowerCAmelCase_ :Union[str, Any] = find_best_thresh(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) lowerCAmelCase_ :Optional[Any] = best_exact lowerCAmelCase_ :List[Any] = exact_thresh lowerCAmelCase_ :Tuple = best_fa lowerCAmelCase_ :str = fa_thresh def _snake_case ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: lowerCAmelCase_ :Union[str, Any] = json.load(lowercase__ ) lowerCAmelCase_ :Optional[Any] = dataset_json["""data"""] with open(OPTS.pred_file ) as f: lowerCAmelCase_ :Dict = json.load(lowercase__ ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: lowerCAmelCase_ :Tuple = json.load(lowercase__ ) else: lowerCAmelCase_ :str = {k: 0.0 for k in preds} lowerCAmelCase_ :List[str] = make_qid_to_has_ans(lowercase__ ) # maps qid to True/False lowerCAmelCase_ :List[str] = [k for k, v in qid_to_has_ans.items() if v] lowerCAmelCase_ :int = [k for k, v in qid_to_has_ans.items() if not v] lowerCAmelCase_ , lowerCAmelCase_ :str = get_raw_scores(lowercase__ , lowercase__ ) lowerCAmelCase_ :Optional[Any] = apply_no_ans_threshold(lowercase__ , lowercase__ , lowercase__ , OPTS.na_prob_thresh ) lowerCAmelCase_ :Union[str, Any] = apply_no_ans_threshold(lowercase__ , lowercase__ , lowercase__ , OPTS.na_prob_thresh ) lowerCAmelCase_ :Any = make_eval_dict(lowercase__ , lowercase__ ) if has_ans_qids: lowerCAmelCase_ :Dict = make_eval_dict(lowercase__ , lowercase__ , qid_list=lowercase__ ) merge_eval(lowercase__ , lowercase__ , """HasAns""" ) if no_ans_qids: lowerCAmelCase_ :List[Any] = make_eval_dict(lowercase__ , lowercase__ , qid_list=lowercase__ ) merge_eval(lowercase__ , lowercase__ , """NoAns""" ) if OPTS.na_prob_file: find_all_best_thresh(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , OPTS.out_image_dir ) histogram_na_prob(lowercase__ , lowercase__ , OPTS.out_image_dir , """hasAns""" ) histogram_na_prob(lowercase__ , lowercase__ , OPTS.out_image_dir , """noAns""" ) if OPTS.out_file: with open(OPTS.out_file , """w""" ) as f: json.dump(lowercase__ , lowercase__ ) else: print(json.dumps(lowercase__ , indent=2 ) ) if __name__ == "__main__": __UpperCAmelCase = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
84
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Tuple = ['''image_processor''', '''tokenizer'''] snake_case__ : Union[str, Any] = '''CLIPImageProcessor''' snake_case__ : Dict = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : int ) -> Any: a_ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , SCREAMING_SNAKE_CASE__ , ) a_ : Tuple = kwargs.pop('feature_extractor' ) a_ : Tuple = 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 : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE__ : str ) -> Optional[Any]: if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: a_ : List[str] = self.tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if images is not None: a_ : Dict = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None and images is not None: a_ : Dict = 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 SCREAMING_SNAKE_CASE ( self : Any , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[Any]: return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: a_ : str = self.tokenizer.model_input_names a_ : Tuple = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def SCREAMING_SNAKE_CASE ( self : str ) -> str: warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , SCREAMING_SNAKE_CASE__ , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , SCREAMING_SNAKE_CASE__ , ) return self.image_processor
32
0
'''simple docstring''' import argparse import os import re _SCREAMING_SNAKE_CASE : List[Any] = "src/transformers/models/auto" # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict _SCREAMING_SNAKE_CASE : Union[str, Any] = re.compile(r"[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict") # re pattern that matches identifiers in mappings _SCREAMING_SNAKE_CASE : Optional[Any] = re.compile(r"\s*\(\s*\"(\S[^\"]+)\"") def UpperCamelCase_( snake_case : str , snake_case : bool = False ): '''simple docstring''' with open(snake_case , "r" , encoding="utf-8" ) as f: snake_case_ = f.read() snake_case_ = content.split("\n" ) snake_case_ = [] snake_case_ = 0 while line_idx < len(snake_case ): if _re_intro_mapping.search(lines[line_idx] ) is not None: snake_case_ = 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 snake_case_ = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": snake_case_ = 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 snake_case_ = sorted(snake_case , key=lambda snake_case : _re_identifier.search(snake_case ).groups()[0] ) new_lines += blocks else: new_lines.append(lines[line_idx] ) line_idx += 1 if overwrite: with open(snake_case , "w" , encoding="utf-8" ) as f: f.write("\n".join(snake_case ) ) elif "\n".join(snake_case ) != content: return True def UpperCamelCase_( snake_case : bool = False ): '''simple docstring''' snake_case_ = [os.path.join(snake_case , snake_case ) for f in os.listdir(snake_case ) if f.endswith(".py" )] snake_case_ = [sort_auto_mapping(snake_case , overwrite=snake_case ) for fname in fnames] if not overwrite and any(snake_case ): snake_case_ = [f for f, d in zip(snake_case , snake_case ) if d] raise ValueError( f'The following files have auto mappings that need sorting: {", ".join(snake_case )}. Run `make style` to fix' " this." ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : Optional[Any] = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") _SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() sort_all_auto_mappings(not args.check_only)
85
from __future__ import annotations UpperCAmelCase_ : Tuple = [] def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] , __A : int , __A : int ) -> bool: """simple docstring""" for i in range(len(__A ) ): if board[row][i] == 1: return False for i in range(len(__A ) ): if board[i][column] == 1: return False for i, j in zip(range(__A , -1 , -1 ) , range(__A , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(__A , -1 , -1 ) , range(__A , len(__A ) ) ): if board[i][j] == 1: return False return True def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] , __A : int ) -> bool: """simple docstring""" if row >= len(__A ): solution.append(__A ) printboard(__A ) print() return True for i in range(len(__A ) ): if is_safe(__A , __A , __A ): a_ : Any = 1 solve(__A , row + 1 ) a_ : Tuple = 0 return False def SCREAMING_SNAKE_CASE_ ( __A : list[list[int]] ) -> None: """simple docstring""" for i in range(len(__A ) ): for j in range(len(__A ) ): if board[i][j] == 1: print('Q' , end=' ' ) else: print('.' , end=' ' ) print() # n=int(input("The no. of queens")) UpperCAmelCase_ : List[str] = 8 UpperCAmelCase_ : str = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
32
0
"""simple docstring""" from __future__ import annotations from typing import Any def __lowerCAmelCase (_UpperCamelCase ): create_state_space_tree(_UpperCamelCase , [] , 0 ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): if index == len(_UpperCamelCase ): print(_UpperCamelCase ) return create_state_space_tree(_UpperCamelCase , _UpperCamelCase , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(_UpperCamelCase , _UpperCamelCase , index + 1 ) current_subsequence.pop() if __name__ == "__main__": lowerCamelCase__ = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["""A""", """B""", """C"""]) generate_all_subsequences(seq)
86
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def SCREAMING_SNAKE_CASE_ ( ) -> Any: """simple docstring""" a_ : Optional[Any] = HfArgumentParser(__A ) a_ : Optional[int] = parser.parse_args_into_dataclasses()[0] a_ : List[Any] = TensorFlowBenchmark(args=__A ) try: a_ : List[str] = parser.parse_args_into_dataclasses()[0] except ValueError as e: a_ : Dict = 'Arg --no_{0} is no longer used, please use --no-{0} instead.' a_ : Dict = ' '.join(str(__A ).split(' ' )[:-1] ) a_ : int = '' a_ : int = eval(str(__A ).split(' ' )[-1] ) a_ : Any = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__A ) if len(__A ) > 0: a_ : str = full_error_msg + begin_error_msg + str(__A ) raise ValueError(__A ) benchmark.run() if __name__ == "__main__": main()
32
0
from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCamelCase = logging.get_logger(__name__) @add_end_docstrings(__A ) class snake_case_ ( __A ): def __init__( self : str , *lowercase_ : Any , **lowercase_ : Optional[Any] ) -> Dict: super().__init__(*lowercase_ , **lowercase_ ) requires_backends(self , "vision" ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def __UpperCamelCase ( self : int , lowercase_ : List[Any]=None ) -> List[Any]: lowercase__ : Optional[int] = {} if top_k is not None: lowercase__ : Tuple = top_k return {}, {}, postprocess_params def __call__( self : Optional[Any] , lowercase_ : Union[str, List[str], "Image.Image", List["Image.Image"]] , **lowercase_ : Optional[int] ) -> Optional[int]: return super().__call__(lowercase_ , **lowercase_ ) def __UpperCamelCase ( self : Any , lowercase_ : Union[str, Any] ) -> Any: lowercase__ : str = load_image(lowercase_ ) lowercase__ : str = self.image_processor(images=lowercase_ , return_tensors=self.framework ) return model_inputs def __UpperCamelCase ( self : int , lowercase_ : Any ) -> List[str]: lowercase__ : Optional[Any] = self.model(**lowercase_ ) return model_outputs def __UpperCamelCase ( self : List[Any] , lowercase_ : List[Any] , lowercase_ : List[Any]=5 ) -> Optional[Any]: if top_k > self.model.config.num_labels: lowercase__ : Optional[Any] = self.model.config.num_labels if self.framework == "pt": lowercase__ : int = model_outputs.logits.softmax(-1 )[0] lowercase__ , lowercase__ : Optional[Any] = probs.topk(lowercase_ ) elif self.framework == "tf": lowercase__ : Optional[int] = stable_softmax(model_outputs.logits , axis=-1 )[0] lowercase__ : int = tf.math.top_k(lowercase_ , k=lowercase_ ) lowercase__ , lowercase__ : Any = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(F'''Unsupported framework: {self.framework}''' ) lowercase__ : Any = scores.tolist() lowercase__ : List[Any] = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(lowercase_ , lowercase_ )]
87
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): snake_case__ : Optional[Any] = TextToVideoSDPipeline snake_case__ : Optional[int] = TEXT_TO_IMAGE_PARAMS snake_case__ : str = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. snake_case__ : Optional[Any] = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: torch.manual_seed(0 ) a_ : Optional[int] = UNetaDConditionModel( block_out_channels=(3_2, 6_4, 6_4, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D') , up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D') , cross_attention_dim=3_2 , attention_head_dim=4 , ) a_ : int = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) a_ : int = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) a_ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='gelu' , projection_dim=5_1_2 , ) a_ : Dict = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) a_ : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> List[str]: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): a_ : Dict = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: a_ : Optional[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) a_ : int = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'pt', } return inputs def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator a_ : Dict = self.get_dummy_components() a_ : str = TextToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) a_ : Dict = 'np' a_ : Dict = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames a_ : int = frames[0][-3:, -3:, -1] assert frames[0].shape == (6_4, 6_4, 3) a_ : Union[str, Any] = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=3E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def SCREAMING_SNAKE_CASE ( self : Any ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=1E-2 ) @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: pass @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: pass @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.' ) def SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: pass def SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: return super().test_progress_bar() @slow @skip_mps class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: a_ : str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy' ) a_ : Any = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) a_ : Optional[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) a_ : Optional[Any] = pipe.to('cuda' ) a_ : Any = 'Spiderman is surfing' a_ : List[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) a_ : Optional[Any] = pipe(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2_5 , output_type='pt' ).frames a_ : str = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2 def SCREAMING_SNAKE_CASE ( self : Any ) -> Any: a_ : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy' ) a_ : Tuple = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) a_ : Tuple = pipe.to('cuda' ) a_ : Any = 'Spiderman is surfing' a_ : List[str] = torch.Generator(device='cpu' ).manual_seed(0 ) a_ : List[Any] = pipe(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type='pt' ).frames a_ : List[str] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2
32
0
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin __lowerCAmelCase : Dict = '\nHugging Face was founded in 2016 by French entrepreneurs Clรฉment Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n' class UpperCAmelCase_ ( unittest.TestCase , _A ): '''simple docstring''' def _lowercase ( self : Union[str, Any] ) -> Any: """simple docstring""" __magic_name__ = load_tool("""text-question-answering""" ) self.tool.setup() __magic_name__ = load_tool("""text-question-answering""" , remote=UpperCamelCase__ ) def _lowercase ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = self.tool(UpperCamelCase__ , """What did Hugging Face do in April 2021?""" ) self.assertEqual(UpperCamelCase__ , """launched the BigScience Research Workshop""" ) def _lowercase ( self : List[str] ) -> int: """simple docstring""" __magic_name__ = self.remote_tool(UpperCamelCase__ , """What did Hugging Face do in April 2021?""" ) self.assertEqual(UpperCamelCase__ , """launched the BigScience Research Workshop""" ) def _lowercase ( self : Any ) -> Optional[Any]: """simple docstring""" __magic_name__ = self.tool(text=UpperCamelCase__ , question="""What did Hugging Face do in April 2021?""" ) self.assertEqual(UpperCamelCase__ , """launched the BigScience Research Workshop""" ) def _lowercase ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = self.remote_tool(text=UpperCamelCase__ , question="""What did Hugging Face do in April 2021?""" ) self.assertEqual(UpperCamelCase__ , """launched the BigScience Research Workshop""" )
88
import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): # TODO: is there an appropriate internal test set? snake_case__ : Any = '''ssube/stable-diffusion-x4-upscaler-onnx''' def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : int=0 ) -> Tuple: a_ : Union[str, Any] = floats_tensor((1, 3, 1_2_8, 1_2_8) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ) a_ : Dict = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: a_ : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.get_dummy_inputs() a_ : int = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : Tuple = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : List[Any] = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: a_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : int = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : List[str] = self.get_dummy_inputs() a_ : List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : str = np.array( [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: a_ : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : Optional[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.get_dummy_inputs() a_ : Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : Optional[Any] = np.array( [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: a_ : List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : int = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = self.get_dummy_inputs() a_ : Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : int = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: a_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) a_ : Optional[int] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = self.get_dummy_inputs() a_ : List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images a_ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a_ : Union[str, Any] = np.array( [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: a_ : List[str] = ort.SessionOptions() a_ : int = False return options def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: a_ : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) a_ : int = init_image.resize((1_2_8, 1_2_8) ) # using the PNDM scheduler by default a_ : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Tuple = 'A fantasy landscape, trending on artstation' a_ : str = torch.manual_seed(0 ) a_ : List[str] = pipe( prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=1_0 , generator=SCREAMING_SNAKE_CASE__ , output_type='np' , ) a_ : Dict = output.images a_ : Any = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) a_ : str = np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: a_ : Dict = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) a_ : List[str] = init_image.resize((1_2_8, 1_2_8) ) a_ : Dict = LMSDiscreteScheduler.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , subfolder='scheduler' ) a_ : Union[str, Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained( 'ssube/stable-diffusion-x4-upscaler-onnx' , scheduler=SCREAMING_SNAKE_CASE__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) a_ : Any = 'A fantasy landscape, trending on artstation' a_ : Tuple = torch.manual_seed(0 ) a_ : Optional[Any] = pipe( prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=2_0 , generator=SCREAMING_SNAKE_CASE__ , output_type='np' , ) a_ : str = output.images a_ : List[Any] = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) a_ : Tuple = np.array( [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
32
0
'''simple docstring''' import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __magic_name__ ( _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : str = LayoutLMTokenizer lowerCAmelCase : Tuple = LayoutLMTokenizerFast lowerCAmelCase : List[Any] = True lowerCAmelCase : int = True def __lowercase ( self : Dict ): super().setUp() _a : int = [ '[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] _a : List[str] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase ( self : Dict ,**_UpperCAmelCase : List[str] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,**_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ,_UpperCAmelCase : Tuple ): _a : Optional[int] = 'UNwant\u00E9d,running' _a : List[Any] = 'unwanted, running' return input_text, output_text def __lowercase ( self : Optional[int] ): _a : Optional[Any] = self.tokenizer_class(self.vocab_file ) _a : Optional[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_UpperCAmelCase ,['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) ,[7, 4, 5, 10, 8, 9] ) def __lowercase ( self : Optional[int] ): pass
89
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> str: """simple docstring""" a_ : Tuple = [] for line in lines: a_ : Any = re.sub(R'#.*' , '' , __A ) # remove comments if line: filtered_lines.append(__A ) a_ : Tuple = '\n'.join(__A ) # Make a hash from all this code a_ : Tuple = full_str.encode('utf-8' ) return shaaaa(__A ).hexdigest() # get importable module names and hash for caching UpperCAmelCase_ : List[Any] = { 'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), 'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), 'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), 'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), 'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), 'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), 'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), 'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions UpperCAmelCase_ : Dict = { '.csv': ('csv', {}), '.tsv': ('csv', {'sep': '\t'}), '.json': ('json', {}), '.jsonl': ('json', {}), '.parquet': ('parquet', {}), '.arrow': ('arrow', {}), '.txt': ('text', {}), } _EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) UpperCAmelCase_ : Optional[int] = {'imagefolder', 'audiofolder'} # Used to filter data files based on extensions given a module name UpperCAmelCase_ : Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('.zip') _MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')
32
0
import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser __A = logging.getLogger(__name__) torch.set_grad_enabled(False) __A = "cuda" if torch.cuda.is_available() else "cpu" def lowerCamelCase_ ( UpperCamelCase__ : str , UpperCamelCase__ : Optional[Any]=100 , UpperCamelCase__ : List[str]=" " ) -> List[str]: """simple docstring""" __lowerCamelCase = text.split(UpperCamelCase__ ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(UpperCamelCase__ ) , UpperCamelCase__ )] def lowerCamelCase_ ( UpperCamelCase__ : dict ) -> dict: """simple docstring""" __lowerCamelCase , __lowerCamelCase = [], [] for title, text in zip(documents['title'] , documents['text'] ): if text is not None: for passage in split_text(UpperCamelCase__ ): titles.append(title if title is not None else '' ) texts.append(UpperCamelCase__ ) return {"title": titles, "text": texts} def lowerCamelCase_ ( UpperCamelCase__ : dict , UpperCamelCase__ : DPRContextEncoder , UpperCamelCase__ : DPRContextEncoderTokenizerFast ) -> dict: """simple docstring""" __lowerCamelCase = ctx_tokenizer( documents['title'] , documents['text'] , truncation=UpperCamelCase__ , padding='longest' , return_tensors='pt' )['input_ids'] __lowerCamelCase = ctx_encoder(input_ids.to(device=UpperCamelCase__ ) , return_dict=UpperCamelCase__ ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def lowerCamelCase_ ( UpperCamelCase__ : "RagExampleArguments" , UpperCamelCase__ : "ProcessingArguments" , UpperCamelCase__ : "IndexHnswArguments" , ) -> Union[str, Any]: """simple docstring""" logger.info('Step 1 - Create the dataset' ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way __lowerCamelCase = load_dataset( 'csv' , data_files=[rag_example_args.csv_path] , split='train' , delimiter='\t' , column_names=['title', 'text'] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words __lowerCamelCase = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , num_proc=processing_args.num_proc ) # And compute the embeddings __lowerCamelCase = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=UpperCamelCase__ ) __lowerCamelCase = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) __lowerCamelCase = Features( {'text': Value('string' ), 'title': Value('string' ), 'embeddings': Sequence(Value('float32' ) )} ) # optional, save as float32 instead of float64 to save space __lowerCamelCase = dataset.map( partial(UpperCamelCase__ , ctx_encoder=UpperCamelCase__ , ctx_tokenizer=UpperCamelCase__ ) , batched=UpperCamelCase__ , batch_size=processing_args.batch_size , features=UpperCamelCase__ , ) # And finally save your dataset __lowerCamelCase = os.path.join(rag_example_args.output_dir , 'my_knowledge_dataset' ) dataset.save_to_disk(UpperCamelCase__ ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info('Step 2 - Index the dataset' ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search __lowerCamelCase = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index('embeddings' , custom_index=UpperCamelCase__ ) # And save the index __lowerCamelCase = os.path.join(rag_example_args.output_dir , 'my_knowledge_dataset_hnsw_index.faiss' ) dataset.get_index('embeddings' ).save(UpperCamelCase__ ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class __lowerCAmelCase : """simple docstring""" snake_case_ = field( default=str(Path(__magic_name__ ).parent / '''test_run''' / '''dummy-kb''' / '''my_knowledge_dataset.csv''' ) , metadata={'''help''': '''Path to a tab-separated csv file with columns \'title\' and \'text\''''} , ) snake_case_ = field( default=__magic_name__ , metadata={'''help''': '''Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'.'''} , ) snake_case_ = field( default='''facebook/rag-sequence-nq''' , metadata={'''help''': '''The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\''''} , ) snake_case_ = field( default='''facebook/dpr-ctx_encoder-multiset-base''' , metadata={ '''help''': ( '''The DPR context encoder model to use. Either \'facebook/dpr-ctx_encoder-single-nq-base\' or''' ''' \'facebook/dpr-ctx_encoder-multiset-base\'''' ) } , ) snake_case_ = field( default=str(Path(__magic_name__ ).parent / '''test_run''' / '''dummy-kb''' ) , metadata={'''help''': '''Path to a directory where the dataset passages and the index will be saved'''} , ) @dataclass class __lowerCAmelCase : """simple docstring""" snake_case_ = field( default=__magic_name__ , metadata={ '''help''': '''The number of processes to use to split the documents into passages. Default is single process.''' } , ) snake_case_ = field( default=16 , metadata={ '''help''': '''The batch size to use when computing the passages embeddings using the DPR context encoder.''' } , ) @dataclass class __lowerCAmelCase : """simple docstring""" snake_case_ = field( default=7_68 , metadata={'''help''': '''The dimension of the embeddings to pass to the HNSW Faiss index.'''} , ) snake_case_ = field( default=1_28 , metadata={ '''help''': ( '''The number of bi-directional links created for every new element during the HNSW index construction.''' ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) __A = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) __A , __A , __A = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: __A = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
90
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Optional[int] = '''convbert''' def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=3_0_5_2_2 , SCREAMING_SNAKE_CASE__ : Dict=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[int]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3_0_7_2 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : Any=1E-12 , SCREAMING_SNAKE_CASE__ : int=1 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=9 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : Dict=None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> Any: super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) a_ : Tuple = vocab_size a_ : List[str] = hidden_size a_ : List[str] = num_hidden_layers a_ : Dict = num_attention_heads a_ : Optional[int] = intermediate_size a_ : int = hidden_act a_ : Dict = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : str = max_position_embeddings a_ : List[str] = type_vocab_size a_ : List[str] = initializer_range a_ : Tuple = layer_norm_eps a_ : Optional[int] = embedding_size a_ : List[Any] = head_ratio a_ : List[Any] = conv_kernel_size a_ : Tuple = num_groups a_ : Tuple = classifier_dropout class SCREAMING_SNAKE_CASE__ ( lowercase__ ): @property def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": a_ : Tuple = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a_ : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
32
0
"""simple docstring""" from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .modules import *
91
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE__ : def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str=1_3 , SCREAMING_SNAKE_CASE__ : Optional[int]=7 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=9_9 , SCREAMING_SNAKE_CASE__ : str=2_4 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6 , SCREAMING_SNAKE_CASE__ : Optional[int]=3_7 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_1_2 , SCREAMING_SNAKE_CASE__ : List[str]=1_6 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Tuple=1_0_0_0 , ) -> str: a_ : Optional[Any] = parent a_ : List[str] = batch_size a_ : List[str] = seq_length a_ : str = is_training a_ : str = use_input_mask a_ : int = use_token_type_ids a_ : List[str] = use_labels a_ : Optional[int] = vocab_size a_ : Any = hidden_size a_ : int = num_hidden_layers a_ : List[str] = num_attention_heads a_ : str = intermediate_size a_ : Union[str, Any] = hidden_act a_ : List[str] = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : int = max_position_embeddings a_ : Tuple = type_vocab_size a_ : Optional[Any] = type_sequence_label_size a_ : Tuple = initializer_range a_ : Dict = num_labels a_ : str = scope a_ : Optional[int] = range_bbox def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: a_ : int = bbox[i, j, 3] a_ : str = bbox[i, j, 1] a_ : List[str] = t if bbox[i, j, 2] < bbox[i, j, 0]: a_ : Tuple = bbox[i, j, 2] a_ : List[str] = bbox[i, j, 0] a_ : Union[str, Any] = t a_ : List[Any] = None if self.use_input_mask: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) a_ : List[Any] = None if self.use_token_type_ids: a_ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : int = None a_ : Tuple = None if self.use_labels: a_ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : Optional[int] = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> str: a_ : Any = LiltModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Any = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = model(SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> int: a_ : Any = self.num_labels a_ : str = LiltForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> str: a_ : Union[str, Any] = LiltForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : List[str] = model( SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , start_positions=SCREAMING_SNAKE_CASE__ , end_positions=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: a_ : int = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : List[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'bbox': bbox, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Union[str, Any] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) snake_case__ : str = ( { '''feature-extraction''': LiltModel, '''question-answering''': LiltForQuestionAnswering, '''text-classification''': LiltForSequenceClassification, '''token-classification''': LiltForTokenClassification, '''zero-shot''': LiltForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : List[str] = False snake_case__ : str = False def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int ) -> int: return True def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: a_ : str = LiltModelTester(self ) a_ : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: a_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a_ : List[str] = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: a_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: a_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]: for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : List[Any] = LiltModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]: a_ : List[str] = LiltModel.from_pretrained('SCUT-DLVCLab/lilt-roberta-en-base' ).to(SCREAMING_SNAKE_CASE__ ) a_ : str = torch.tensor([[1, 2]] , device=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): a_ : str = model(input_ids=SCREAMING_SNAKE_CASE__ , bbox=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = torch.Size([1, 2, 7_6_8] ) a_ : int = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=SCREAMING_SNAKE_CASE__ , ) self.assertTrue(outputs.last_hidden_state.shape , SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) )
32
0
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process UpperCamelCase__ = logging.getLogger(__name__) UpperCamelCase__ = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) UpperCamelCase__ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class a__ : _a : Optional[str] = field( default=snake_case__ , metadata={ """help""": ( """The model checkpoint for weights initialization.Don't set if you want to train a model from scratch.""" ) } , ) _a : Optional[str] = field( default=snake_case__ , metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(snake_case__ )} , ) _a : Optional[str] = field( default=snake_case__ , metadata={ """help""": ( """Override some existing default config settings when a model is trained from scratch. Example: """ """n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index""" ) } , ) _a : Optional[str] = field( default=snake_case__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) _a : Optional[str] = field( default=snake_case__ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) _a : Optional[str] = field( default=snake_case__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) _a : bool = field( default=snake_case__ , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) _a : str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) _a : bool = field( default=snake_case__ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( "--config_overrides can't be used in combination with --config_name or --model_name_or_path" ) @dataclass class a__ : _a : Optional[str] = field( default=snake_case__ , metadata={"""help""": """The name of the dataset to use (via the datasets library)."""} ) _a : Optional[str] = field( default=snake_case__ , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} ) _a : Optional[str] = field(default=snake_case__ , metadata={"""help""": """The input training data file (a text file)."""} ) _a : Optional[str] = field( default=snake_case__ , metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""} , ) _a : Optional[str] = field( default=snake_case__ , metadata={"""help""": """An optional input train ref data file for whole word masking in Chinese."""} , ) _a : Optional[str] = field( default=snake_case__ , metadata={"""help""": """An optional input validation ref data file for whole word masking in Chinese."""} , ) _a : bool = field( default=snake_case__ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) _a : Optional[int] = field( default=5 , metadata={ """help""": """The percentage of the train set used as validation set in case there's no validation split""" } , ) _a : Optional[int] = field( default=snake_case__ , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated. Default to the max input length of the model.""" ) } , ) _a : Optional[int] = field( default=snake_case__ , metadata={"""help""": """The number of processes to use for the preprocessing."""} , ) _a : float = field( default=0.15 , metadata={"""help""": """Ratio of tokens to mask for masked language modeling loss"""} ) _a : bool = field( default=snake_case__ , metadata={ """help""": ( """Whether to pad all samples to `max_seq_length`. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch.""" ) } , ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if self.train_file is not None: __lowerCAmelCase = self.train_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: __lowerCAmelCase = self.validation_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ): with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" ) as f: __lowerCAmelCase = [json.loads(SCREAMING_SNAKE_CASE_ ) for line in f.read().splitlines() if (len(SCREAMING_SNAKE_CASE_ ) > 0 and not line.isspace())] assert len(SCREAMING_SNAKE_CASE_ ) == len(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = {c: dataset[c] for c in dataset.column_names} __lowerCAmelCase = refs return Dataset.from_dict(SCREAMING_SNAKE_CASE_ ) def _a ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __lowerCAmelCase = 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. __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = parser.parse_args_into_dataclasses() # Detecting last checkpoint. __lowerCAmelCase = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __lowerCAmelCase = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) # 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" , SCREAMING_SNAKE_CASE_ ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. __lowerCAmelCase = load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): __lowerCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""train[:{data_args.validation_split_percentage}%]""" , ) __lowerCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""train[{data_args.validation_split_percentage}%:]""" , ) else: __lowerCAmelCase = {} if data_args.train_file is not None: __lowerCAmelCase = data_args.train_file if data_args.validation_file is not None: __lowerCAmelCase = data_args.validation_file __lowerCAmelCase = data_args.train_file.split("." )[-1] if extension == "txt": __lowerCAmelCase = "text" __lowerCAmelCase = load_dataset(SCREAMING_SNAKE_CASE_ , data_files=SCREAMING_SNAKE_CASE_ ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __lowerCAmelCase = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name: __lowerCAmelCase = AutoConfig.from_pretrained(model_args.config_name , **SCREAMING_SNAKE_CASE_ ) elif model_args.model_name_or_path: __lowerCAmelCase = AutoConfig.from_pretrained(model_args.model_name_or_path , **SCREAMING_SNAKE_CASE_ ) else: __lowerCAmelCase = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch." ) if model_args.config_overrides is not None: logger.info(F"""Overriding config: {model_args.config_overrides}""" ) config.update_from_string(model_args.config_overrides ) logger.info(F"""New config: {config}""" ) __lowerCAmelCase = { "cache_dir": model_args.cache_dir, "use_fast": model_args.use_fast_tokenizer, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: __lowerCAmelCase = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **SCREAMING_SNAKE_CASE_ ) elif model_args.model_name_or_path: __lowerCAmelCase = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **SCREAMING_SNAKE_CASE_ ) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name." ) if model_args.model_name_or_path: __lowerCAmelCase = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("Training new model from scratch" ) __lowerCAmelCase = AutoModelForMaskedLM.from_config(SCREAMING_SNAKE_CASE_ ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE_ ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: __lowerCAmelCase = datasets["train"].column_names else: __lowerCAmelCase = datasets["validation"].column_names __lowerCAmelCase = "text" if "text" in column_names else column_names[0] __lowerCAmelCase = "max_length" if data_args.pad_to_max_length else False def tokenize_function(SCREAMING_SNAKE_CASE_ : Union[str, Any] ): # Remove empty lines __lowerCAmelCase = [line for line in examples["text"] if len(SCREAMING_SNAKE_CASE_ ) > 0 and not line.isspace()] return tokenizer(examples["text"] , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=data_args.max_seq_length ) __lowerCAmelCase = datasets.map( SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: __lowerCAmelCase = add_chinese_references(tokenized_datasets["train"] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: __lowerCAmelCase = add_chinese_references( tokenized_datasets["validation"] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer __lowerCAmelCase = data_args.train_ref_file or data_args.validation_ref_file if has_ref: __lowerCAmelCase = False # Data collator # This one will take care of randomly masking the tokens. __lowerCAmelCase = DataCollatorForWholeWordMask(tokenizer=SCREAMING_SNAKE_CASE_ , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer __lowerCAmelCase = Trainer( model=SCREAMING_SNAKE_CASE_ , args=SCREAMING_SNAKE_CASE_ , train_dataset=tokenized_datasets["train"] if training_args.do_train else None , eval_dataset=tokenized_datasets["validation"] if training_args.do_eval else None , tokenizer=SCREAMING_SNAKE_CASE_ , data_collator=SCREAMING_SNAKE_CASE_ , ) # Training if training_args.do_train: if last_checkpoint is not None: __lowerCAmelCase = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): __lowerCAmelCase = model_args.model_name_or_path else: __lowerCAmelCase = None __lowerCAmelCase = trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE_ ) trainer.save_model() # Saves the tokenizer too for easy upload __lowerCAmelCase = os.path.join(training_args.output_dir , "train_results.txt" ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE_ , "w" ) as writer: logger.info("***** Train results *****" ) for key, value in sorted(train_result.metrics.items() ): logger.info(F""" {key} = {value}""" ) writer.write(F"""{key} = {value}\n""" ) # 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" ) ) # Evaluation __lowerCAmelCase = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) __lowerCAmelCase = trainer.evaluate() __lowerCAmelCase = math.exp(eval_output["eval_loss"] ) __lowerCAmelCase = perplexity __lowerCAmelCase = os.path.join(training_args.output_dir , "eval_results_mlm_wwm.txt" ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in sorted(results.items() ): logger.info(F""" {key} = {value}""" ) writer.write(F"""{key} = {value}\n""" ) return results def _a ( SCREAMING_SNAKE_CASE_ : Any ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
92
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple=1_3 , SCREAMING_SNAKE_CASE__ : str=7 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=9_9 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_2 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Tuple=3_7 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=5_1_2 , SCREAMING_SNAKE_CASE__ : int=1_6 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> Any: a_ : Tuple = parent a_ : int = batch_size a_ : Tuple = seq_length a_ : List[Any] = is_training a_ : List[str] = use_token_type_ids a_ : Dict = use_labels a_ : Any = vocab_size a_ : List[str] = hidden_size a_ : Tuple = num_hidden_layers a_ : List[Any] = num_attention_heads a_ : Dict = intermediate_size a_ : Any = hidden_act a_ : List[str] = hidden_dropout_prob a_ : Tuple = attention_probs_dropout_prob a_ : Optional[Any] = max_position_embeddings a_ : List[Any] = type_vocab_size a_ : int = type_sequence_label_size a_ : List[Any] = initializer_range a_ : List[str] = num_labels a_ : Union[str, Any] = num_choices a_ : str = scope a_ : Tuple = self.vocab_size - 1 def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: a_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = None if self.use_token_type_ids: a_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : List[Any] = None a_ : Union[str, Any] = None a_ : List[Any] = None if self.use_labels: a_ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) a_ : Union[str, Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) a_ : List[str] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: a_ : Dict = OpenAIGPTModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , head_mask=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: a_ : str = OpenAIGPTLMHeadModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: a_ : int = OpenAIGPTDoubleHeadsModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Any = self.num_labels a_ : Dict = OpenAIGPTForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : Optional[Any] = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : Optional[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Tuple = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) snake_case__ : List[str] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly snake_case__ : Dict = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any=False ) -> List[str]: a_ : str = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": a_ : Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : str = inputs_dict['labels'] a_ : Optional[int] = inputs_dict['labels'] a_ : Optional[int] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: a_ : str = OpenAIGPTModelTester(self ) a_ : int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , n_embd=3_7 ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: a_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: a_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: a_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : str = OpenAIGPTModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: a_ : Dict = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt' ) model.to(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) # the president is a_ : Tuple = [ 4_8_1, 4_7_3_5, 5_4_4, 2_4_6, 9_6_3, 8_7_0, 7_6_2, 2_3_9, 2_4_4, 4_0_4_7_7, 2_4_4, 2_4_9, 7_1_9, 8_8_1, 4_8_7, 5_4_4, 2_4_0, 2_4_4, 6_0_3, 4_8_1, ] # the president is a very good man. " \n " i\'m sure he is, " said the a_ : Dict = model.generate(SCREAMING_SNAKE_CASE__ , do_sample=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(output_ids[0].tolist() , SCREAMING_SNAKE_CASE__ )
32
0
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def snake_case_ ( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : int=1 ): """simple docstring""" if n_shave_prefix_segments >= 0: return ".".join(path.split('''.''' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('''.''' )[:n_shave_prefix_segments] ) def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : int=0 ): """simple docstring""" lowercase_ : Union[str, Any] = [] for old_item in old_list: lowercase_ : Optional[Any] = old_item.replace('''in_layers.0''' , '''norm1''' ) lowercase_ : Dict = new_item.replace('''in_layers.2''' , '''conv1''' ) lowercase_ : int = new_item.replace('''out_layers.0''' , '''norm2''' ) lowercase_ : Union[str, Any] = new_item.replace('''out_layers.3''' , '''conv2''' ) lowercase_ : List[Any] = new_item.replace('''emb_layers.1''' , '''time_emb_proj''' ) lowercase_ : int = new_item.replace('''skip_connection''' , '''conv_shortcut''' ) lowercase_ : Union[str, Any] = shave_segments(__SCREAMING_SNAKE_CASE , n_shave_prefix_segments=__SCREAMING_SNAKE_CASE ) mapping.append({'''old''': old_item, '''new''': new_item} ) return mapping def snake_case_ ( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[Any]=0 ): """simple docstring""" lowercase_ : List[Any] = [] for old_item in old_list: lowercase_ : Union[str, Any] = old_item lowercase_ : Optional[Any] = new_item.replace('''norm.weight''' , '''group_norm.weight''' ) lowercase_ : List[str] = new_item.replace('''norm.bias''' , '''group_norm.bias''' ) lowercase_ : Tuple = new_item.replace('''proj_out.weight''' , '''proj_attn.weight''' ) lowercase_ : List[Any] = new_item.replace('''proj_out.bias''' , '''proj_attn.bias''' ) lowercase_ : Tuple = shave_segments(__SCREAMING_SNAKE_CASE , n_shave_prefix_segments=__SCREAMING_SNAKE_CASE ) mapping.append({'''old''': old_item, '''new''': new_item} ) return mapping def snake_case_ ( __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str=None , __SCREAMING_SNAKE_CASE : Dict=None , __SCREAMING_SNAKE_CASE : Dict=None ): """simple docstring""" assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): lowercase_ : Tuple = old_checkpoint[path] lowercase_ : str = old_tensor.shape[0] // 3 lowercase_ : List[str] = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) lowercase_ : List[Any] = old_tensor.shape[0] // config['''num_head_channels'''] // 3 lowercase_ : int = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) lowercase_ , lowercase_ , lowercase_ : Optional[int] = old_tensor.split(channels // num_heads , dim=1 ) lowercase_ : Tuple = query.reshape(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = key.reshape(__SCREAMING_SNAKE_CASE ) lowercase_ : int = value.reshape(__SCREAMING_SNAKE_CASE ) for path in paths: lowercase_ : List[str] = path['''new'''] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here lowercase_ : str = new_path.replace('''middle_block.0''' , '''mid_block.resnets.0''' ) lowercase_ : List[Any] = new_path.replace('''middle_block.1''' , '''mid_block.attentions.0''' ) lowercase_ : Dict = new_path.replace('''middle_block.2''' , '''mid_block.resnets.1''' ) if additional_replacements is not None: for replacement in additional_replacements: lowercase_ : Dict = new_path.replace(replacement['''old'''] , replacement['''new'''] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: lowercase_ : Optional[Any] = old_checkpoint[path['''old''']][:, :, 0] else: lowercase_ : Optional[Any] = old_checkpoint[path['''old''']] def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" lowercase_ : List[Any] = {} lowercase_ : Optional[int] = checkpoint['''time_embed.0.weight'''] lowercase_ : Optional[Any] = checkpoint['''time_embed.0.bias'''] lowercase_ : Optional[Any] = checkpoint['''time_embed.2.weight'''] lowercase_ : int = checkpoint['''time_embed.2.bias'''] lowercase_ : Optional[Any] = checkpoint['''input_blocks.0.0.weight'''] lowercase_ : List[str] = checkpoint['''input_blocks.0.0.bias'''] lowercase_ : int = checkpoint['''out.0.weight'''] lowercase_ : Tuple = checkpoint['''out.0.bias'''] lowercase_ : Dict = checkpoint['''out.2.weight'''] lowercase_ : Any = checkpoint['''out.2.bias'''] # Retrieves the keys for the input blocks only lowercase_ : int = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''input_blocks''' in layer} ) lowercase_ : Union[str, Any] = { layer_id: [key for key in checkpoint if F'''input_blocks.{layer_id}''' in key] for layer_id in range(__SCREAMING_SNAKE_CASE ) } # Retrieves the keys for the middle blocks only lowercase_ : int = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''middle_block''' in layer} ) lowercase_ : str = { layer_id: [key for key in checkpoint if F'''middle_block.{layer_id}''' in key] for layer_id in range(__SCREAMING_SNAKE_CASE ) } # Retrieves the keys for the output blocks only lowercase_ : List[Any] = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''output_blocks''' in layer} ) lowercase_ : str = { layer_id: [key for key in checkpoint if F'''output_blocks.{layer_id}''' in key] for layer_id in range(__SCREAMING_SNAKE_CASE ) } for i in range(1 , __SCREAMING_SNAKE_CASE ): lowercase_ : Any = (i - 1) // (config['''num_res_blocks'''] + 1) lowercase_ : Any = (i - 1) % (config['''num_res_blocks'''] + 1) lowercase_ : List[str] = [key for key in input_blocks[i] if F'''input_blocks.{i}.0''' in key] lowercase_ : List[Any] = [key for key in input_blocks[i] if F'''input_blocks.{i}.1''' in key] if F'''input_blocks.{i}.0.op.weight''' in checkpoint: lowercase_ : List[Any] = checkpoint[ F'''input_blocks.{i}.0.op.weight''' ] lowercase_ : List[str] = checkpoint[ F'''input_blocks.{i}.0.op.bias''' ] continue lowercase_ : Union[str, Any] = renew_resnet_paths(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = {'''old''': F'''input_blocks.{i}.0''', '''new''': F'''down_blocks.{block_id}.resnets.{layer_in_block_id}'''} lowercase_ : List[Any] = {'''old''': '''resnets.2.op''', '''new''': '''downsamplers.0.op'''} assign_to_checkpoint( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , additional_replacements=[meta_path, resnet_op] , config=__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ): lowercase_ : Optional[Any] = renew_attention_paths(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = { '''old''': F'''input_blocks.{i}.1''', '''new''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}''', } lowercase_ : Dict = { F'''input_blocks.{i}.1.qkv.bias''': { '''key''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias''', '''query''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias''', '''value''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias''', }, F'''input_blocks.{i}.1.qkv.weight''': { '''key''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight''', '''query''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight''', '''value''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight''', }, } assign_to_checkpoint( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , additional_replacements=[meta_path] , attention_paths_to_split=__SCREAMING_SNAKE_CASE , config=__SCREAMING_SNAKE_CASE , ) lowercase_ : int = middle_blocks[0] lowercase_ : Union[str, Any] = middle_blocks[1] lowercase_ : Optional[Any] = middle_blocks[2] lowercase_ : Dict = renew_resnet_paths(__SCREAMING_SNAKE_CASE ) assign_to_checkpoint(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , config=__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = renew_resnet_paths(__SCREAMING_SNAKE_CASE ) assign_to_checkpoint(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , config=__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = renew_attention_paths(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = { '''middle_block.1.qkv.bias''': { '''key''': '''mid_block.attentions.0.key.bias''', '''query''': '''mid_block.attentions.0.query.bias''', '''value''': '''mid_block.attentions.0.value.bias''', }, '''middle_block.1.qkv.weight''': { '''key''': '''mid_block.attentions.0.key.weight''', '''query''': '''mid_block.attentions.0.query.weight''', '''value''': '''mid_block.attentions.0.value.weight''', }, } assign_to_checkpoint( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , attention_paths_to_split=__SCREAMING_SNAKE_CASE , config=__SCREAMING_SNAKE_CASE ) for i in range(__SCREAMING_SNAKE_CASE ): lowercase_ : List[Any] = i // (config['''num_res_blocks'''] + 1) lowercase_ : int = i % (config['''num_res_blocks'''] + 1) lowercase_ : Optional[Any] = [shave_segments(__SCREAMING_SNAKE_CASE , 2 ) for name in output_blocks[i]] lowercase_ : Any = {} for layer in output_block_layers: lowercase_ , lowercase_ : Any = layer.split('''.''' )[0], shave_segments(__SCREAMING_SNAKE_CASE , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(__SCREAMING_SNAKE_CASE ) else: lowercase_ : Optional[Any] = [layer_name] if len(__SCREAMING_SNAKE_CASE ) > 1: lowercase_ : List[Any] = [key for key in output_blocks[i] if F'''output_blocks.{i}.0''' in key] lowercase_ : Union[str, Any] = [key for key in output_blocks[i] if F'''output_blocks.{i}.1''' in key] lowercase_ : Optional[Any] = renew_resnet_paths(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = renew_resnet_paths(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = {'''old''': F'''output_blocks.{i}.0''', '''new''': F'''up_blocks.{block_id}.resnets.{layer_in_block_id}'''} assign_to_checkpoint(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , additional_replacements=[meta_path] , config=__SCREAMING_SNAKE_CASE ) if ["conv.weight", "conv.bias"] in output_block_list.values(): lowercase_ : Any = list(output_block_list.values() ).index(['''conv.weight''', '''conv.bias'''] ) lowercase_ : str = checkpoint[ F'''output_blocks.{i}.{index}.conv.weight''' ] lowercase_ : Union[str, Any] = checkpoint[ F'''output_blocks.{i}.{index}.conv.bias''' ] # Clear attentions as they have been attributed above. if len(__SCREAMING_SNAKE_CASE ) == 2: lowercase_ : Tuple = [] if len(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = renew_attention_paths(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = { '''old''': F'''output_blocks.{i}.1''', '''new''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}''', } lowercase_ : List[str] = { F'''output_blocks.{i}.1.qkv.bias''': { '''key''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias''', '''query''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias''', '''value''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias''', }, F'''output_blocks.{i}.1.qkv.weight''': { '''key''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight''', '''query''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight''', '''value''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight''', }, } assign_to_checkpoint( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('''qkv''' in key for key in attentions ) else None , config=__SCREAMING_SNAKE_CASE , ) else: lowercase_ : int = renew_resnet_paths(__SCREAMING_SNAKE_CASE , n_shave_prefix_segments=1 ) for path in resnet_0_paths: lowercase_ : Optional[int] = '''.'''.join(['''output_blocks''', str(__SCREAMING_SNAKE_CASE ), path['''old''']] ) lowercase_ : Union[str, Any] = '''.'''.join(['''up_blocks''', str(__SCREAMING_SNAKE_CASE ), '''resnets''', str(__SCREAMING_SNAKE_CASE ), path['''new''']] ) lowercase_ : Optional[Any] = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": _lowercase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the architecture.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") _lowercase : int = parser.parse_args() _lowercase : Dict = torch.load(args.checkpoint_path) with open(args.config_file) as f: _lowercase : str = json.loads(f.read()) _lowercase : Union[str, Any] = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] _lowercase : Any = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: _lowercase : str = DDPMScheduler.from_config("/".join(args.checkpoint_path.split("/")[:-1])) _lowercase : List[str] = VQModel.from_pretrained("/".join(args.checkpoint_path.split("/")[:-1])) _lowercase : Optional[Any] = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
93
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase_ : Optional[int] = { 'facebook/mask2former-swin-small-coco-instance': ( 'https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase_ : List[str] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = '''mask2former''' snake_case__ : Any = ['''swin'''] snake_case__ : str = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 2_5_6 , SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 1_0 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_5_5 , SCREAMING_SNAKE_CASE__ : int = 1_0_0 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : int , ) -> List[Any]: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) a_ : Dict = CONFIG_MAPPING['swin']( image_size=2_2_4 , in_channels=3 , patch_size=4 , embed_dim=9_6 , depths=[2, 2, 1_8, 2] , num_heads=[3, 6, 1_2, 2_4] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): a_ : Any = backbone_config.pop('model_type' ) a_ : Optional[Any] = CONFIG_MAPPING[backbone_model_type] a_ : List[str] = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # 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 Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) a_ : Dict = backbone_config a_ : List[str] = feature_size a_ : List[str] = mask_feature_size a_ : int = hidden_dim a_ : Dict = encoder_feedforward_dim a_ : str = activation_function a_ : List[str] = encoder_layers a_ : List[str] = decoder_layers a_ : Dict = num_attention_heads a_ : str = dropout a_ : Tuple = dim_feedforward a_ : List[str] = pre_norm a_ : Optional[int] = enforce_input_projection a_ : Any = common_stride a_ : Optional[int] = ignore_value a_ : int = num_queries a_ : Tuple = no_object_weight a_ : Dict = class_weight a_ : Optional[int] = mask_weight a_ : Optional[int] = dice_weight a_ : str = train_num_points a_ : List[str] = oversample_ratio a_ : List[Any] = importance_sample_ratio a_ : Any = init_std a_ : Union[str, Any] = init_xavier_std a_ : Union[str, Any] = use_auxiliary_loss a_ : Dict = feature_strides a_ : List[str] = output_auxiliary_logits a_ : Dict = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def SCREAMING_SNAKE_CASE ( cls : str , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict[str, any]: a_ : Optional[int] = copy.deepcopy(self.__dict__ ) a_ : List[Any] = self.backbone_config.to_dict() a_ : Optional[Any] = self.__class__.model_type return output
32
0
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class _snake_case : SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None def SCREAMING_SNAKE_CASE__ ( self ): return self.__class__(**{k: copy.deepcopy(_lowerCamelCase ) for k, v in self.__dict__.items()} )
94
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Union[str, Any] = { 'google/switch-base-8': 'https://huggingface.co/google/switch-base-8/blob/main/config.json', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : List[str] = '''switch_transformers''' snake_case__ : Optional[int] = ['''past_key_values'''] snake_case__ : Optional[Any] = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int]=3_2_1_2_8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7_6_8 , SCREAMING_SNAKE_CASE__ : Optional[Any]=6_4 , SCREAMING_SNAKE_CASE__ : List[str]=2_0_4_8 , SCREAMING_SNAKE_CASE__ : Dict=6_4 , SCREAMING_SNAKE_CASE__ : List[Any]=1_2 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE__ : str=3 , SCREAMING_SNAKE_CASE__ : Tuple=1_2 , SCREAMING_SNAKE_CASE__ : Tuple=8 , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.01 , SCREAMING_SNAKE_CASE__ : str="float32" , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_2 , SCREAMING_SNAKE_CASE__ : Dict=1_2_8 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=1E-6 , SCREAMING_SNAKE_CASE__ : Dict=0.001 , SCREAMING_SNAKE_CASE__ : Any=0.001 , SCREAMING_SNAKE_CASE__ : Optional[int]=1.0 , SCREAMING_SNAKE_CASE__ : Any="relu" , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : Optional[int]=1 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: a_ : Optional[int] = vocab_size a_ : List[str] = d_model a_ : Tuple = d_kv a_ : Optional[Any] = d_ff a_ : List[Any] = num_sparse_encoder_layers a_ : Any = num_layers a_ : str = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a_ : List[Any] = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: a_ : Optional[int] = self.num_layers // self.num_sparse_encoder_layers else: a_ : List[Any] = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: a_ : Union[str, Any] = self.num_decoder_layers // self.num_sparse_decoder_layers else: a_ : List[str] = self.num_decoder_layers # HACK: this will create 0 sparse layers a_ : Dict = num_heads a_ : str = num_experts a_ : Any = expert_capacity a_ : List[Any] = router_bias a_ : str = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""" ) a_ : Optional[int] = router_dtype a_ : int = router_ignore_padding_tokens a_ : Any = relative_attention_num_buckets a_ : List[str] = relative_attention_max_distance a_ : Optional[Any] = dropout_rate a_ : Tuple = layer_norm_epsilon a_ : Dict = initializer_factor a_ : Any = feed_forward_proj a_ : Tuple = use_cache a_ : str = add_router_probs a_ : Optional[int] = router_z_loss_coef a_ : List[str] = router_aux_loss_coef a_ : int = self.feed_forward_proj.split('-' ) a_ : int = act_info[-1] a_ : Optional[int] = act_info[0] == 'gated' if len(SCREAMING_SNAKE_CASE__ ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE__ ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a_ : Any = 'gelu_new' super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , is_encoder_decoder=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
32
0
def _A ( SCREAMING_SNAKE_CASE : float ): """simple docstring""" if edge <= 0 or not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def _A ( SCREAMING_SNAKE_CASE : float ): """simple docstring""" if edge <= 0 or not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Length must be a positive." ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
95
# 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. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase_ : Tuple = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyรจ': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmรฅl': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''facebook/nllb-200-distilled-600M''' snake_case__ : Union[str, Any] = ( '''This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ''' '''be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ''' '''which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ''' '''plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.''' ) snake_case__ : Optional[Any] = '''translator''' snake_case__ : Tuple = AutoTokenizer snake_case__ : Union[str, Any] = AutoModelForSeqaSeqLM snake_case__ : Dict = LANGUAGE_CODES snake_case__ : str = ['''text''', '''text''', '''text'''] snake_case__ : Tuple = ['''text'''] def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: if src_lang not in self.lang_to_code: raise ValueError(F"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(F"""{tgt_lang} is not a supported language.""" ) a_ : str = self.lang_to_code[src_lang] a_ : Any = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors='pt' , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Tuple ) -> Any: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
32
0
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow lowercase__ = logging.getLogger() @unittest.skip("""Temporarily disable the doc tests.""" ) @require_torch @require_tf @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def A_ ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = True , ): _lowerCamelCase : Union[str, Any] = [file for file in os.listdir(lowercase ) if os.path.isfile(os.path.join(lowercase , lowercase ) )] if identifier is not None: _lowerCamelCase : str = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(lowercase , lowercase ): for n_ in n_identifier: _lowerCamelCase : str = [file for file in files if n_ not in file] else: _lowerCamelCase : Dict = [file for file in files if n_identifier not in file] _lowerCamelCase : str = ignore_files or [] ignore_files.append('__init__.py' ) _lowerCamelCase : Union[str, Any] = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' , lowercase ) if only_modules: _lowerCamelCase : List[str] = file.split('.' )[0] try: _lowerCamelCase : Tuple = getattr(lowercase , lowercase ) _lowerCamelCase : List[Any] = doctest.DocTestSuite(lowercase ) _lowerCamelCase : Optional[int] = unittest.TextTestRunner().run(lowercase ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'''{module_identifier} is not a module.''' ) else: _lowerCamelCase : Any = doctest.testfile(str('..' / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def A_ ( self ): _lowerCamelCase : int = Path('src/transformers' ) _lowerCamelCase : List[Any] = 'modeling' _lowerCamelCase : Dict = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(lowercase , identifier=lowercase , ignore_files=lowercase ) def A_ ( self ): _lowerCamelCase : int = Path('src/transformers' ) _lowerCamelCase : Tuple = 'tokenization' self.analyze_directory(lowercase , identifier=lowercase ) def A_ ( self ): _lowerCamelCase : Optional[Any] = Path('src/transformers' ) _lowerCamelCase : int = 'configuration' self.analyze_directory(lowercase , identifier=lowercase ) def A_ ( self ): _lowerCamelCase : int = Path('src/transformers' ) _lowerCamelCase : Any = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(lowercase , n_identifier=lowercase ) def A_ ( self ): _lowerCamelCase : int = Path('docs/source' ) _lowerCamelCase : List[str] = ['favicon.ico'] self.analyze_directory(lowercase , ignore_files=lowercase , only_modules=lowercase )
96
UpperCAmelCase_ : Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def SCREAMING_SNAKE_CASE_ ( __A : int , __A : int , __A : int ) -> str: """simple docstring""" assert len(str(__A ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: a_ : List[str] = year // 1_00 a_ : Optional[int] = (5 * (century % 4) + 2) % 7 a_ : List[str] = year % 1_00 a_ : str = centurian % 12 a_ : List[str] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 a_ : Any = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) a_ : Any = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
32
0
'''simple docstring''' from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING __snake_case = logging.get_logger(__name__) @add_end_docstrings(A__ ) class lowercase ( A__ ): """simple docstring""" def __init__( self , **UpperCamelCase_ ): '''simple docstring''' super().__init__(**UpperCamelCase_ ) if self.framework == "tf": raise ValueError(F'''The {self.__class__} is only available in PyTorch.''' ) requires_backends(self , '''vision''' ) self.check_model_type(UpperCamelCase_ ) def __call__( self , UpperCamelCase_ , UpperCamelCase_ = None , **UpperCamelCase_ , ): '''simple docstring''' if "text_queries" in kwargs: UpperCamelCase__ :str = kwargs.pop('''text_queries''' ) if isinstance(UpperCamelCase_ , (str, Image.Image) ): UpperCamelCase__ :List[Any] = {'''image''': image, '''candidate_labels''': candidate_labels} else: UpperCamelCase__ :Any = image UpperCamelCase__ :Optional[int] = super().__call__(UpperCamelCase_ , **UpperCamelCase_ ) return results def lowerCAmelCase__ ( self , **UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Any = {} if "threshold" in kwargs: UpperCamelCase__ :List[Any] = kwargs['''threshold'''] if "top_k" in kwargs: UpperCamelCase__ :Optional[Any] = kwargs['''top_k'''] return {}, {}, postprocess_params def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :str = load_image(inputs['''image'''] ) UpperCamelCase__ :Dict = inputs['''candidate_labels'''] if isinstance(UpperCamelCase_ , UpperCamelCase_ ): UpperCamelCase__ :Optional[Any] = candidate_labels.split(''',''' ) UpperCamelCase__ :Union[str, Any] = torch.tensor([[image.height, image.width]] , dtype=torch.intaa ) for i, candidate_label in enumerate(UpperCamelCase_ ): UpperCamelCase__ :List[str] = self.tokenizer(UpperCamelCase_ , return_tensors=self.framework ) UpperCamelCase__ :Optional[int] = self.image_processor(UpperCamelCase_ , return_tensors=self.framework ) yield { "is_last": i == len(UpperCamelCase_ ) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :int = model_inputs.pop('''target_size''' ) UpperCamelCase__ :Optional[int] = model_inputs.pop('''candidate_label''' ) UpperCamelCase__ :List[Any] = model_inputs.pop('''is_last''' ) UpperCamelCase__ :str = self.model(**UpperCamelCase_ ) UpperCamelCase__ :str = {'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs} return model_outputs def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_=0.1 , UpperCamelCase_=None ): '''simple docstring''' UpperCamelCase__ :str = [] for model_output in model_outputs: UpperCamelCase__ :Optional[int] = model_output['''candidate_label'''] UpperCamelCase__ :Union[str, Any] = BaseModelOutput(UpperCamelCase_ ) UpperCamelCase__ :Tuple = self.image_processor.post_process_object_detection( outputs=UpperCamelCase_ , threshold=UpperCamelCase_ , target_sizes=model_output['''target_size'''] )[0] for index in outputs["scores"].nonzero(): UpperCamelCase__ :Dict = outputs['''scores'''][index].item() UpperCamelCase__ :int = self._get_bounding_box(outputs['''boxes'''][index][0] ) UpperCamelCase__ :Optional[int] = {'''score''': score, '''label''': label, '''box''': box} results.append(UpperCamelCase_ ) UpperCamelCase__ :Optional[int] = sorted(UpperCamelCase_ , key=lambda UpperCamelCase_ : x["score"] , reverse=UpperCamelCase_ ) if top_k: UpperCamelCase__ :Tuple = results[:top_k] return results def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' if self.framework != "pt": raise ValueError('''The ZeroShotObjectDetectionPipeline is only available in PyTorch.''' ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ :List[str] = box.int().tolist() UpperCamelCase__ :Union[str, Any] = { '''xmin''': xmin, '''ymin''': ymin, '''xmax''': xmax, '''ymax''': ymax, } return bbox
97
import math import flax.linen as nn import jax.numpy as jnp def SCREAMING_SNAKE_CASE_ ( __A : jnp.ndarray , __A : int , __A : float = 1 , __A : float = 1 , __A : float = 1.0e4 , __A : bool = False , __A : float = 1.0 , ) -> jnp.ndarray: """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F"""Embedding dimension {embedding_dim} should be even""" a_ : int = float(embedding_dim // 2 ) a_ : str = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) a_ : Optional[int] = min_timescale * jnp.exp(jnp.arange(__A , dtype=jnp.floataa ) * -log_timescale_increment ) a_ : Optional[int] = jnp.expand_dims(__A , 1 ) * jnp.expand_dims(__A , 0 ) # scale embeddings a_ : str = scale * emb if flip_sin_to_cos: a_ : str = jnp.concatenate([jnp.cos(__A ), jnp.sin(__A )] , axis=1 ) else: a_ : Any = jnp.concatenate([jnp.sin(__A ), jnp.cos(__A )] , axis=1 ) a_ : Optional[int] = jnp.reshape(__A , [jnp.shape(__A )[0], embedding_dim] ) return signal class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Optional[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_1' )(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = nn.silu(SCREAMING_SNAKE_CASE__ ) a_ : str = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_2' )(SCREAMING_SNAKE_CASE__ ) return temb class SCREAMING_SNAKE_CASE__ ( nn.Module ): snake_case__ : int = 32 snake_case__ : bool = False snake_case__ : float = 1 @nn.compact def __call__( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Tuple: return get_sinusoidal_embeddings( SCREAMING_SNAKE_CASE__ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
32
0
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_torch_available(): import torch if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm lowerCAmelCase__ : str = logging.get_logger(__name__) @dataclass class snake_case ( __UpperCAmelCase ): """simple docstring""" snake_case__ = [ "no_inference", "no_cuda", "no_tpu", "no_speed", "no_memory", "no_env_print", "no_multi_process", ] def __init__( self : Union[str, Any] ,**lowerCamelCase__ : Optional[Any] ): for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: UpperCAmelCase__ = deprecated_arg[3:] setattr(self ,lowerCamelCase__ ,not kwargs.pop(lowerCamelCase__ ) ) logger.warning( f'''{deprecated_arg} is depreciated. Please use --no_{positive_arg} or''' f''' {positive_arg}={kwargs[positive_arg]}''' ) UpperCAmelCase__ = kwargs.pop('torchscript' ,self.torchscript ) UpperCAmelCase__ = kwargs.pop('torch_xla_tpu_print_metrics' ,self.torch_xla_tpu_print_metrics ) UpperCAmelCase__ = kwargs.pop('fp16_opt_level' ,self.fpaa_opt_level ) super().__init__(**lowerCamelCase__ ) snake_case__ = field(default=__UpperCAmelCase , metadata={"help": "Trace the models using torchscript"} ) snake_case__ = field(default=__UpperCAmelCase , metadata={"help": "Print Xla/PyTorch tpu metrics"} ) snake_case__ = field( default="O1" , metadata={ "help": ( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. " "See details at https://nvidia.github.io/apex/amp.html" ) } , ) @cached_property def __lowerCAmelCase ( self : Optional[int] ): requires_backends(self ,['torch'] ) logger.info('PyTorch: setting up devices' ) if not self.cuda: UpperCAmelCase__ = torch.device('cpu' ) UpperCAmelCase__ = 0 elif is_torch_tpu_available(): UpperCAmelCase__ = xm.xla_device() UpperCAmelCase__ = 0 else: UpperCAmelCase__ = torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) UpperCAmelCase__ = torch.cuda.device_count() return device, n_gpu @property def __lowerCAmelCase ( self : Tuple ): return is_torch_tpu_available() and self.tpu @property def __lowerCAmelCase ( self : Any ): requires_backends(self ,['torch'] ) # TODO(PVP): currently only single GPU is supported return torch.cuda.current_device() @property def __lowerCAmelCase ( self : Dict ): requires_backends(self ,['torch'] ) return self._setup_devices[0] @property def __lowerCAmelCase ( self : int ): requires_backends(self ,['torch'] ) return self._setup_devices[1] @property def __lowerCAmelCase ( self : List[str] ): return self.n_gpu > 0
98
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) UpperCAmelCase_ : str = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) UpperCAmelCase_ : Optional[Any] = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) UpperCAmelCase_ : int = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) UpperCAmelCase_ : Union[str, Any] = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) UpperCAmelCase_ : List[str] = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) UpperCAmelCase_ : Dict = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) UpperCAmelCase_ : Union[str, Any] = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) UpperCAmelCase_ : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase_ : Dict = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase_ : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase_ : Dict = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase_ : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase_ : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase_ : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[Any] = FLAX_MODEL_MAPPING UpperCAmelCase_ : Tuple = auto_class_update(FlaxAutoModel) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Any = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[Any] = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase_ : Union[str, Any] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase_ : Optional[int] = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase_ : Optional[Any] = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Tuple = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase_ : str = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : List[str] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase_ : Tuple = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Dict = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase_ : int = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[int] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase_ : Dict = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase_ : str = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[Any] = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase_ : Tuple = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class SCREAMING_SNAKE_CASE__ ( _BaseAutoModelClass ): snake_case__ : Optional[int] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase_ : Union[str, Any] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
32
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase : List[str] = { """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Any = ["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : List[str] = [ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[int] = [ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : List[Any] = [ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys lowercase : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
99
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE__ ( lowercase__ , unittest.TestCase ): snake_case__ : Any = GPTSanJapaneseTokenizer snake_case__ : Tuple = False snake_case__ : str = {'''do_clean_text''': False, '''add_prefix_space''': False} def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: super().setUp() # fmt: off a_ : Union[str, Any] = ['ใ“ใ‚“', 'ใ“ใ‚“ใซ', 'ใซใกใฏ', 'ใฐใ‚“ใฏ', 'ไธ–็•Œ,ใ”บ็•Œ', 'ใ€', 'ใ€‚', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on a_ : int = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # ๐Ÿ˜€ a_ : List[Any] = {'unk_token': '<unk>'} a_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) a_ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE__ ) ) def SCREAMING_SNAKE_CASE ( self : List[str] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> int: kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> int: a_ : Optional[int] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : List[str] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' return input_text, output_text def SCREAMING_SNAKE_CASE ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Dict: a_ , a_ : Union[str, Any] = self.get_input_output_texts(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) a_ : Dict = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) return text, ids def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: pass # TODO add if relevant def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: a_ : List[str] = self.get_tokenizer() # Testing tokenization a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ€€ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚' a_ : Optional[int] = ['ใ“ใ‚“', 'ใซใกใฏ', 'ใ€', 'ไธ–็•Œ', 'ใ€‚', '<SP>', 'ใ“ใ‚“', 'ใฐใ‚“ใฏ', 'ใ€', 'ใ”บ็•Œ', 'ใ€‚'] a_ : Dict = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids without special tokens a_ : Tuple = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] a_ : List[Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids with special tokens a_ : int = tokens + [tokenizer.unk_token] a_ : int = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9] a_ : Tuple = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: a_ : Union[str, Any] = self.get_tokenizer() # Testing tokenization a_ : Dict = 'ใ“ใ‚“ใซใกใฏใ€<|bagoftoken|>ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€<|bagoftoken|>ใ”บ็•Œใ€‚' a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚' a_ : Any = tokenizer.encode(SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : str ) -> Dict: a_ : Tuple = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization a_ : List[Any] = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' a_ : int = 'ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : Dict = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' a_ : Optional[int] = tokenizer.encode(prefix_text + input_text ) a_ : Any = tokenizer.encode('' , prefix_text=prefix_text + input_text ) a_ : Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) a_ : str = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: a_ : Tuple = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization a_ : str = 'ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' a_ : List[str] = 'ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' a_ : str = len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 a_ : Tuple = len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 a_ : Optional[Any] = [1] + [0] * (len_prefix + len_text + 1) a_ : Optional[Any] = [1] * (len_prefix + len_text + 1) + [0] a_ : Tuple = [1] + [1] * (len_prefix) + [0] * (len_text + 1) a_ : List[str] = tokenizer(prefix_text + input_text ).token_type_ids a_ : Union[str, Any] = tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids a_ : Any = tokenizer(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: a_ : str = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) a_ : Optional[int] = tokenizer.encode('ใ‚ใƒณใ„ใƒฏ' ) a_ : Dict = tokenizer.encode('' , prefix_text='ใ‚ใƒณใ„ใƒฏ' ) a_ : Dict = tokenizer.encode('ใ„ใƒฏ' , prefix_text='ใ‚ใƒณ' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: a_ : List[str] = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) a_ : Optional[Any] = [['ๆญฆ็”ฐไฟก็Ž„', 'ใฏใ€'], ['็น”็”ฐไฟก้•ท', 'ใฎ้…ไธ‹ใฎใ€']] a_ : List[str] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) a_ : Dict = tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) # fmt: off a_ : List[Any] = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]] a_ : Any = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] a_ : List[Any] = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: # tokenizer has no padding token pass
32
0
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING __magic_name__ = logging.get_logger(__name__) __magic_name__ = Dict[str, Any] __magic_name__ = List[Prediction] @add_end_docstrings(__a ) class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" def __init__( self , *lowerCAmelCase__ , **lowerCAmelCase__): super().__init__(*lowerCAmelCase__ , **lowerCAmelCase__) if self.framework == "tf": raise ValueError(f"The {self.__class__} is only available in PyTorch.") requires_backends(self , """vision""") self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items())) def snake_case_ ( self , **lowerCAmelCase__): __SCREAMING_SNAKE_CASE = {} if "threshold" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self , *lowerCAmelCase__ , **lowerCAmelCase__): return super().__call__(*lowerCAmelCase__ , **lowerCAmelCase__) def snake_case_ ( self , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = load_image(lowerCAmelCase__) __SCREAMING_SNAKE_CASE = torch.IntTensor([[image.height, image.width]]) __SCREAMING_SNAKE_CASE = self.image_processor(images=[image] , return_tensors="""pt""") if self.tokenizer is not None: __SCREAMING_SNAKE_CASE = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""") __SCREAMING_SNAKE_CASE = target_size return inputs def snake_case_ ( self , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = model_inputs.pop("""target_size""") __SCREAMING_SNAKE_CASE = self.model(**lowerCAmelCase__) __SCREAMING_SNAKE_CASE = outputs.__class__({"""target_size""": target_size, **outputs}) if self.tokenizer is not None: __SCREAMING_SNAKE_CASE = model_inputs["""bbox"""] return model_outputs def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__=0.9): __SCREAMING_SNAKE_CASE = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = target_size[0].tolist() def unnormalize(lowerCAmelCase__): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1_0_0_0), (height * bbox[1] / 1_0_0_0), (width * bbox[2] / 1_0_0_0), (height * bbox[3] / 1_0_0_0), ])) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = model_outputs["""logits"""].squeeze(0).softmax(dim=-1).max(dim=-1) __SCREAMING_SNAKE_CASE = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] __SCREAMING_SNAKE_CASE = [unnormalize(lowerCAmelCase__) for bbox in model_outputs["""bbox"""].squeeze(0)] __SCREAMING_SNAKE_CASE = ["""score""", """label""", """box"""] __SCREAMING_SNAKE_CASE = [dict(zip(lowerCAmelCase__ , lowerCAmelCase__)) for vals in zip(scores.tolist() , lowerCAmelCase__ , lowerCAmelCase__) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel __SCREAMING_SNAKE_CASE = self.image_processor.post_process_object_detection(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__) __SCREAMING_SNAKE_CASE = raw_annotations[0] __SCREAMING_SNAKE_CASE = raw_annotation["""scores"""] __SCREAMING_SNAKE_CASE = raw_annotation["""labels"""] __SCREAMING_SNAKE_CASE = raw_annotation["""boxes"""] __SCREAMING_SNAKE_CASE = scores.tolist() __SCREAMING_SNAKE_CASE = [self.model.config.idalabel[label.item()] for label in labels] __SCREAMING_SNAKE_CASE = [self._get_bounding_box(lowerCAmelCase__) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] __SCREAMING_SNAKE_CASE = ["""score""", """label""", """box"""] __SCREAMING_SNAKE_CASE = [ dict(zip(lowerCAmelCase__ , lowerCAmelCase__)) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""]) ] return annotation def snake_case_ ( self , lowerCAmelCase__): if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""") __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = box.int().tolist() __SCREAMING_SNAKE_CASE = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
100
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, logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Union[str, Any] = ['''pixel_values'''] def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, int]] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 2_5_5 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) a_ : str = size if size is not None else {'shortest_edge': 2_5_6} a_ : Any = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) a_ : Dict = crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4} a_ : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE__ ) a_ : List[str] = do_resize a_ : Dict = size a_ : Optional[Any] = resample a_ : Optional[int] = do_center_crop a_ : Dict = crop_size a_ : int = do_rescale a_ : int = rescale_factor a_ : Tuple = do_normalize a_ : int = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN a_ : Tuple = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> np.ndarray: a_ : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) a_ : Tuple = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=size['shortest_edge'] , default_to_square=SCREAMING_SNAKE_CASE__ ) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> np.ndarray: a_ : str = get_size_dict(SCREAMING_SNAKE_CASE__ ) return center_crop(SCREAMING_SNAKE_CASE__ , size=(size['height'], size['width']) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> np.ndarray: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Dict , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[float] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> Union[str, Any]: a_ : List[str] = do_resize if do_resize is not None else self.do_resize a_ : Dict = size if size is not None else self.size a_ : Dict = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = resample if resample is not None else self.resample a_ : List[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop a_ : int = crop_size if crop_size is not None else self.crop_size a_ : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE__ ) a_ : Dict = do_rescale if do_rescale is not None else self.do_rescale a_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor a_ : Any = do_normalize if do_normalize is not None else self.do_normalize a_ : str = image_mean if image_mean is not None else self.image_mean a_ : Dict = image_std if image_std is not None else self.image_std a_ : Optional[int] = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. a_ : Any = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: a_ : str = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_center_crop: a_ : int = [self.center_crop(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: a_ : Optional[Any] = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: a_ : List[Any] = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] a_ : Dict = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] a_ : Tuple = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
32
0