code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _A : Union[str, Any] = logging.getLogger(__name__) def __snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Tuple: return (preds == labels).mean() @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ : str = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) lowerCamelCase__ : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) lowerCamelCase__ : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) lowerCamelCase__ : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ : str = field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(processors.keys() )} ) lowerCamelCase__ : str = field(metadata={"""help""": """Should contain the data files for the task."""} ) lowerCamelCase__ : int = field( default=1_2_8 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) lowerCamelCase__ : bool = field( default=__SCREAMING_SNAKE_CASE , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def __snake_case ( ) -> Tuple: # 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. SCREAMING_SNAKE_CASE__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) try: SCREAMING_SNAKE_CASE__ = processors[data_args.task_name]() SCREAMING_SNAKE_CASE__ = processor.get_labels() SCREAMING_SNAKE_CASE__ = len(lowerCAmelCase_ ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) SCREAMING_SNAKE_CASE__ = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets SCREAMING_SNAKE_CASE__ = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) SCREAMING_SNAKE_CASE__ = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(lowerCAmelCase_ ) -> Dict: SCREAMING_SNAKE_CASE__ = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(lowerCAmelCase_ , p.label_ids )} # Data collator SCREAMING_SNAKE_CASE__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer SCREAMING_SNAKE_CASE__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation SCREAMING_SNAKE_CASE__ = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) SCREAMING_SNAKE_CASE__ = trainer.evaluate() SCREAMING_SNAKE_CASE__ = os.path.join(training_args.output_dir , '''eval_results.txt''' ) if trainer.is_world_master(): with open(lowerCAmelCase_ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''' , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write('''%s = %s\n''' % (key, value) ) results.update(lowerCAmelCase_ ) return results def __snake_case ( lowerCAmelCase_ ) -> Any: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
100
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" return 10 - x * x def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) >= 0: raise ValueError("Wrong space!" ) _UpperCAmelCase = a while (b - a) >= 0.01: # Find middle point _UpperCAmelCase = (a + b) / 2 # Check if middle point is root if equation(UpperCamelCase__ ) == 0.0: break # Decide the side to repeat the steps if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) < 0: _UpperCAmelCase = c else: _UpperCAmelCase = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
657
0
def a__ ( A__, A__ ): if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = str(bin(A__ ) )[2:] # remove the leading "0b" SCREAMING_SNAKE_CASE_ : Dict = str(bin(A__ ) )[2:] # remove the leading "0b" SCREAMING_SNAKE_CASE_ : List[Any] = max(len(A__ ), len(A__ ) ) return "0b" + "".join( str(int(char_a == '1' and char_b == '1' ) ) for char_a, char_b in zip(a_binary.zfill(A__ ), b_binary.zfill(A__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
101
"""simple docstring""" from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): lowercase_ : Tuple = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self , a_ , a_ , a_ = None , a_ = 50257 , a_ = 1024 , a_ = 768 , a_ = 12 , a_ = 12 , a_ = None , a_ = "gelu_new" , a_ = 0.1 , a_ = 0.1 , a_ = 0.1 , a_ = 1e-5 , a_ = 0.02 , a_ = True , a_ = True , a_ = False , a_ = False , ) -> List[str]: super().__init__() _UpperCAmelCase = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f"`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and" f" `n_embd`: {n_embd} are not equal." ) _UpperCAmelCase = prefix_inner_dim _UpperCAmelCase = prefix_hidden_dim _UpperCAmelCase = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) _UpperCAmelCase = ( nn.Linear(self.prefix_hidden_dim , a_ ) if self.prefix_hidden_dim is not None else nn.Identity() ) _UpperCAmelCase = GPTaConfig( vocab_size=a_ , n_positions=a_ , n_embd=a_ , n_layer=a_ , n_head=a_ , n_inner=a_ , activation_function=a_ , resid_pdrop=a_ , embd_pdrop=a_ , attn_pdrop=a_ , layer_norm_epsilon=a_ , initializer_range=a_ , scale_attn_weights=a_ , use_cache=a_ , scale_attn_by_inverse_layer_idx=a_ , reorder_and_upcast_attn=a_ , ) _UpperCAmelCase = GPTaLMHeadModel(a_ ) def _a ( self , a_ , a_ , a_ = None , a_ = None , ) -> Tuple: _UpperCAmelCase = self.transformer.transformer.wte(a_ ) _UpperCAmelCase = self.encode_prefix(a_ ) _UpperCAmelCase = self.decode_prefix(a_ ) _UpperCAmelCase = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: _UpperCAmelCase = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) _UpperCAmelCase = torch.cat((dummy_token, input_ids) , dim=1 ) _UpperCAmelCase = self.transformer(inputs_embeds=a_ , labels=a_ , attention_mask=a_ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def _a ( self , a_ , a_ ) -> torch.Tensor: return torch.zeros(a_ , self.prefix_length , dtype=torch.intaa , device=a_ ) def _a ( self , a_ ) -> Union[str, Any]: return self.encode_prefix(a_ ) @torch.no_grad() def _a ( self , a_ , a_ , a_ ) -> Union[str, Any]: _UpperCAmelCase = torch.split(a_ , 1 , dim=0 ) _UpperCAmelCase = [] _UpperCAmelCase = [] for feature in features: _UpperCAmelCase = self.decode_prefix(feature.to(a_ ) ) # back to the clip feature # Only support beam search for now _UpperCAmelCase , _UpperCAmelCase = self.generate_beam( input_embeds=a_ , device=a_ , eos_token_id=a_ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) _UpperCAmelCase = torch.stack(a_ ) _UpperCAmelCase = torch.stack(a_ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def _a ( self , a_=None , a_=None , a_=None , a_ = 5 , a_ = 67 , a_ = 1.0 , a_ = None , ) -> Optional[Any]: _UpperCAmelCase = eos_token_id _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = torch.ones(a_ , device=a_ , dtype=torch.int ) _UpperCAmelCase = torch.zeros(a_ , device=a_ , dtype=torch.bool ) if input_embeds is not None: _UpperCAmelCase = input_embeds else: _UpperCAmelCase = self.transformer.transformer.wte(a_ ) for i in range(a_ ): _UpperCAmelCase = self.transformer(inputs_embeds=a_ ) _UpperCAmelCase = outputs.logits _UpperCAmelCase = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) _UpperCAmelCase = logits.softmax(-1 ).log() if scores is None: _UpperCAmelCase , _UpperCAmelCase = logits.topk(a_ , -1 ) _UpperCAmelCase = generated.expand(a_ , *generated.shape[1:] ) _UpperCAmelCase , _UpperCAmelCase = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: _UpperCAmelCase = next_tokens else: _UpperCAmelCase = tokens.expand(a_ , *tokens.shape[1:] ) _UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) else: _UpperCAmelCase = -float(np.inf ) _UpperCAmelCase = 0 _UpperCAmelCase = scores[:, None] + logits seq_lengths[~is_stopped] += 1 _UpperCAmelCase = scores_sum / seq_lengths[:, None] _UpperCAmelCase , _UpperCAmelCase = scores_sum_average.view(-1 ).topk(a_ , -1 ) _UpperCAmelCase = next_tokens // scores_sum.shape[1] _UpperCAmelCase = seq_lengths[next_tokens_source] _UpperCAmelCase = next_tokens % scores_sum.shape[1] _UpperCAmelCase = next_tokens.unsqueeze(1 ) _UpperCAmelCase = tokens[next_tokens_source] _UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) _UpperCAmelCase = generated[next_tokens_source] _UpperCAmelCase = scores_sum_average * seq_lengths _UpperCAmelCase = is_stopped[next_tokens_source] _UpperCAmelCase = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) _UpperCAmelCase = torch.cat((generated, next_token_embed) , dim=1 ) _UpperCAmelCase = is_stopped + next_tokens.eq(a_ ).squeeze() if is_stopped.all(): break _UpperCAmelCase = scores / seq_lengths _UpperCAmelCase = scores.argsort(descending=a_ ) # tokens tensors are already padded to max_seq_length _UpperCAmelCase = [tokens[i] for i in order] _UpperCAmelCase = torch.stack(a_ , dim=0 ) _UpperCAmelCase = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
657
0
"""simple docstring""" from __future__ import annotations def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # Checks if the entire collection has been sorted if len(SCREAMING_SNAKE_CASE ) <= 1 or n <= 1: return insert_next(SCREAMING_SNAKE_CASE , n - 1 ) rec_insertion_sort(SCREAMING_SNAKE_CASE , n - 1 ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # Checks order between adjacent elements if index >= len(SCREAMING_SNAKE_CASE ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order UpperCamelCase , UpperCamelCase : Dict = ( collection[index], collection[index - 1], ) insert_next(SCREAMING_SNAKE_CASE , index + 1 ) if __name__ == "__main__": __magic_name__ : Union[str, Any] = input("""Enter integers separated by spaces: """) __magic_name__ : list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
102
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable __magic_name__ = {'''configuration_gpt_neox''': ['''GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXConfig''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''GPTNeoXTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXForCausalLM''', '''GPTNeoXForQuestionAnswering''', '''GPTNeoXForSequenceClassification''', '''GPTNeoXForTokenClassification''', '''GPTNeoXLayer''', '''GPTNeoXModel''', '''GPTNeoXPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
657
0
"""simple docstring""" import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): snake_case = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right snake_case = 1_2_8_0_2_2 snake_case = 1_2_8_0_2_8 @require_sentencepiece class UpperCAmelCase ( __SCREAMING_SNAKE_CASE,unittest.TestCase ): A__ : Optional[Any] = MaMaaaTokenizer A__ : List[Any] = False A__ : Any = False A__ : str = True def __UpperCAmelCase ( self : str ): """simple docstring""" super().setUp() _snake_case = ['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] _snake_case = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) _snake_case = Path(self.tmpdirname ) save_json(__lowerCamelCase , save_dir / VOCAB_FILES_NAMES['''vocab_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(__lowerCamelCase , save_dir / VOCAB_FILES_NAMES['''spm_file'''] ) _snake_case = MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self : Optional[int] , **__lowerCamelCase : Union[str, Any] ): """simple docstring""" return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def __UpperCAmelCase ( self : List[Any] , __lowerCamelCase : Optional[Any] ): """simple docstring""" return ( "This is a test", "This is a test", ) def __UpperCAmelCase ( self : int ): """simple docstring""" _snake_case = '''</s>''' _snake_case = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowerCamelCase ) , __lowerCamelCase ) def __UpperCAmelCase ( self : List[str] ): """simple docstring""" _snake_case = self.get_tokenizer() _snake_case = list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''</s>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''<s>''' ) self.assertEqual(len(__lowerCamelCase ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip('''Skip this test while all models are still to be uploaded.''' ) def __UpperCAmelCase ( self : List[Any] ): """simple docstring""" pass def __UpperCAmelCase ( self : Any ): """simple docstring""" _snake_case = self.get_tokenizer() _snake_case = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__lowerCamelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [2, 3, 4, 5, 6] , ) _snake_case = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(__lowerCamelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) _snake_case = tokenizer.convert_tokens_to_string(__lowerCamelCase ) self.assertEqual(__lowerCamelCase , '''This is a test''' ) @slow def __UpperCAmelCase ( self : Tuple ): """simple docstring""" # fmt: off _snake_case = {'''input_ids''': [[1_2_8_0_2_2, 1_1_0_1_0_8, 3_9_7, 1_1, 3_8_2_7_2, 2_2_4_7, 1_2_4_8_1_1, 2_8_5, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 3_9_5_3_4, 4_4_2_8, 3_9_7, 1_0_1_9, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 4_1_3_3_7, 1_6_7_8_6, 2_4_1, 7, 2_0_2_1_4, 1_7, 1_2_5_6_9_0, 1_0_3_9_8, 7, 4_4_3_7_8, 5_8_0_6_9, 6_8_3_4_2, 7_7_9_8, 7_3_4_3, 1_1, 2_9_9, 3_3_3_1_0, 4, 1_5_8, 3_7_3_5_0, 9_4_0_7_7, 4_5_6_9, 2_9_9, 3_3_3_1_0, 9_0, 4, 5_2_8_4_0, 2_9_0, 4, 3_1_2_7_0, 1_1_2, 2_9_9, 6_8_2, 4, 5_2_8_4_0, 3_9_9_5_3, 1_4_0_7_9, 1_9_3, 5_2_5_1_9, 9_0_8_9_4, 1_7_8_9_4, 1_2_0_6_9_7, 1_1, 4_0_4_4_5, 5_5_1, 1_7, 1_0_1_9, 5_2_5_1_9, 9_0_8_9_4, 1_7_7_5_6, 9_6_3, 1_1, 4_0_4_4_5, 4_8_0, 1_7, 9_7_9_2, 1_1_2_0, 5_1_7_3, 1_3_9_3, 6_2_4_0, 1_6_7_8_6, 2_4_1, 1_2_0_9_9_6, 2_8, 1_2_4_5, 1_3_9_3, 1_1_8_2_4_0, 1_1_1_2_3, 1_0_1_9, 9_3_6_1_2, 2_6_9_1, 1_0_6_1_8, 9_8_0_5_8, 1_2_0_4_0_9, 1_9_2_8, 2_7_9, 4, 4_0_6_8_3, 3_6_7, 1_7_8, 2_0_7, 1_0_1_9, 1_0_3, 1_0_3_1_2_1, 5_0_6, 6_5_2_9_6, 5, 2], [1_2_8_0_2_2, 2_1_2_1_7, 3_6_7, 1_1_7, 1_2_5_4_5_0, 1_2_8, 7_1_9, 7, 7_3_0_8, 4_0, 9_3_6_1_2, 1_2_6_6_9, 1_1_1_6, 1_6_7_0_4, 7_1, 1_7_7_8_5, 3_6_9_9, 1_5_5_9_2, 3_5, 1_4_4, 9_5_8_4, 2_4_1, 1_1_9_4_3, 7_1_3, 9_5_0, 7_9_9, 2_2_4_7, 8_8_4_2_7, 1_5_0, 1_4_9, 1_1_8_8_1_3, 1_2_0_7_0_6, 1_0_1_9, 1_0_6_9_0_6, 8_1_5_1_8, 2_8, 1_2_2_4, 2_2_7_9_9, 3_9_7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1_2_8_0_2_2, 1_6_5_8, 1_2_3_3_1_1, 5_1_5_5, 5_5_7_8, 4_7_2_2, 2_7_9, 1_4_9_4_7, 2_3_6_6, 1_1_2_0, 1_1_9_7, 1_4, 1_3_4_8, 9_2_3_2, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowerCamelCase , model_name='''facebook/m2m100_418M''' , revision='''c168bae485c864188cf9aa0e4108b0b6934dc91e''' , ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase ( unittest.TestCase ): A__ : Tuple = '''facebook/m2m100_418M''' A__ : str = [ '''In my opinion, there are two levels of response from the French government.''', '''NSA Affair Emphasizes Complete Lack of Debate on Intelligence''', ] A__ : Union[str, Any] = [ '''Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.''', '''L\'affaire NSA souligne l\'absence totale de débat sur le renseignement''', ] # fmt: off A__ : Any = [EN_CODE, 593, 1949, 115781, 4, 71586, 4234, 60633, 126233, 432, 123808, 15592, 1197, 117132, 120618, 5, 2] @classmethod def __UpperCAmelCase ( cls : Optional[int] ): """simple docstring""" _snake_case = MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''en''' , tgt_lang='''fr''' ) _snake_case = 1 return cls def __UpperCAmelCase ( self : str ): """simple docstring""" self.assertEqual(self.tokenizer.get_lang_id('''ar''' ) , 1_2_8_0_0_6 ) self.assertEqual(self.tokenizer.get_lang_id('''en''' ) , 1_2_8_0_2_2 ) self.assertEqual(self.tokenizer.get_lang_id('''ro''' ) , 1_2_8_0_7_6 ) self.assertEqual(self.tokenizer.get_lang_id('''mr''' ) , 1_2_8_0_6_3 ) def __UpperCAmelCase ( self : List[Any] ): """simple docstring""" _snake_case = self.tokenizer.get_vocab() self.assertEqual(len(__lowerCamelCase ) , self.tokenizer.vocab_size ) self.assertEqual(vocab['''<unk>'''] , 3 ) self.assertIn(self.tokenizer.get_lang_token('''en''' ) , __lowerCamelCase ) def __UpperCAmelCase ( self : Dict ): """simple docstring""" _snake_case = '''en''' _snake_case = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __lowerCamelCase ) def __UpperCAmelCase ( self : Union[str, Any] ): """simple docstring""" self.assertIn(__lowerCamelCase , self.tokenizer.all_special_ids ) # fmt: off _snake_case = [FR_CODE, 5_3_6_4, 8_2, 8_6_4_2, 4, 2_9_4, 4_7, 8, 1_4_0_2_8, 1_3_6, 3_2_8_6, 9_7_0_6, 6, 9_0_7_9_7, 6, 1_4_4_0_1_2, 1_6_2, 8_8_1_2_8, 3_0_0_6_1, 5, 2] # fmt: on _snake_case = self.tokenizer.decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) _snake_case = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertNotIn(self.tokenizer.eos_token , __lowerCamelCase ) def __UpperCAmelCase ( self : str ): """simple docstring""" _snake_case = tempfile.mkdtemp() _snake_case = self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(__lowerCamelCase ) _snake_case = MaMaaaTokenizer.from_pretrained(__lowerCamelCase ) self.assertDictEqual(new_tok.lang_token_to_id , __lowerCamelCase ) @require_torch def __UpperCAmelCase ( self : Union[str, Any] ): """simple docstring""" _snake_case = '''en''' _snake_case = '''fr''' _snake_case = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__lowerCamelCase , return_tensors='''pt''' ) _snake_case = shift_tokens_right( batch['''labels'''] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: _snake_case = batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def __UpperCAmelCase ( self : int ): """simple docstring""" _snake_case = '''mr''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) _snake_case = '''zh''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def __UpperCAmelCase ( self : Dict ): """simple docstring""" _snake_case = '''mr''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) _snake_case = '''zh''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def __UpperCAmelCase ( self : int ): """simple docstring""" _snake_case = self.tokenizer._build_translation_inputs('''A test''' , return_tensors='''pt''' , src_lang='''en''' , tgt_lang='''ar''' ) self.assertEqual( nested_simplify(__lowerCamelCase ) , { # en_XX, A, test, EOS '''input_ids''': [[1_2_8_0_2_2, 5_8, 4_1_8_3, 2]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 1_2_8_0_0_6, } , )
103
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''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 _lowerCAmelCase ( lowerCamelCase ): lowercase_ : Union[str, Any] = '''convbert''' def __init__( self , a_=30522 , 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_=768 , a_=2 , a_=9 , a_=1 , a_=None , **a_ , ) -> Tuple: super().__init__( pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ , ) _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = embedding_size _UpperCAmelCase = head_ratio _UpperCAmelCase = conv_kernel_size _UpperCAmelCase = num_groups _UpperCAmelCase = classifier_dropout class _lowerCAmelCase ( lowerCamelCase ): @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _UpperCAmelCase = {0: "batch", 1: "choice", 2: "sequence"} else: _UpperCAmelCase = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
657
0
"""simple docstring""" def _lowerCamelCase ( UpperCAmelCase_ : int ) -> int: """simple docstring""" if not isinstance(UpperCAmelCase_, UpperCAmelCase_ ): raise ValueError("Input must be an integer" ) if input_num <= 0: raise ValueError("Input must be positive" ) return sum( divisor for divisor in range(1, input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
104
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" return "".join([hex(UpperCamelCase__ )[2:].zfill(2 ).upper() for byte in list(UpperCamelCase__ )] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if (len(UpperCamelCase__ ) % 2) != 0: raise ValueError( "Base16 encoded data is invalid:\nData does not have an even number of hex digits." ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(UpperCamelCase__ ) <= set("0123456789ABCDEF" ): raise ValueError( "Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters." ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(UpperCamelCase__ ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
657
0
from __future__ import annotations def __UpperCAmelCase ( lowerCamelCase_ : list[int] ) -> int: """simple docstring""" if not nums: return 0 SCREAMING_SNAKE_CASE_ : List[str] = nums[0] SCREAMING_SNAKE_CASE_ : Any = 0 for num in nums[1:]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = ( max_excluding + num, max(lowerCamelCase_ , lowerCamelCase_ ), ) return max(lowerCamelCase_ , lowerCamelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
105
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" try: _UpperCAmelCase = float(UpperCamelCase__ ) except ValueError: raise ValueError("Please enter a valid number" ) _UpperCAmelCase = decimal - int(UpperCamelCase__ ) if fractional_part == 0: return int(UpperCamelCase__ ), 1 else: _UpperCAmelCase = len(str(UpperCamelCase__ ).split("." )[1] ) _UpperCAmelCase = int(decimal * (10**number_of_frac_digits) ) _UpperCAmelCase = 10**number_of_frac_digits _UpperCAmelCase , _UpperCAmelCase = denominator, numerator while True: _UpperCAmelCase = dividend % divisor if remainder == 0: break _UpperCAmelCase , _UpperCAmelCase = divisor, remainder _UpperCAmelCase , _UpperCAmelCase = numerator / divisor, denominator / divisor return int(UpperCamelCase__ ), int(UpperCamelCase__ ) if __name__ == "__main__": print(f'''{decimal_to_fraction(2) = }''') print(f'''{decimal_to_fraction(89.0) = }''') print(f'''{decimal_to_fraction("67") = }''') print(f'''{decimal_to_fraction("45.0") = }''') print(f'''{decimal_to_fraction(1.5) = }''') print(f'''{decimal_to_fraction("6.25") = }''') print(f'''{decimal_to_fraction("78td") = }''')
657
0
from math import sqrt def lowerCamelCase_ ( lowerCAmelCase__ : int ) -> bool: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( number >= 0 ), "'number' must been an int and positive" A = True # 0 and 1 are none primes. if number <= 1: A = False for divisor in range(2 , int(round(sqrt(lowerCAmelCase__ ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: A = False break # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'status' must been from type bool" return status def lowerCamelCase_ ( lowerCAmelCase__ : Tuple ) -> str: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N A = list(range(2 , n + 1 ) ) A = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(lowerCAmelCase__ ) ): for j in range(i + 1 , len(lowerCAmelCase__ ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): A = 0 # filters actual prime numbers. A = [x for x in begin_list if x != 0] # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type list" return ans def lowerCamelCase_ ( lowerCAmelCase__ : str ) -> Dict: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n > 2), "'N' must been an int and > 2" A = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(lowerCAmelCase__ ): ans.append(lowerCAmelCase__ ) # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type list" return ans def lowerCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> Dict: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and number >= 0, "'number' must been an int and >= 0" A = [] # this list will be returns of the function. # potential prime number factors. A = 2 A = number if number == 0 or number == 1: ans.append(lowerCAmelCase__ ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(lowerCAmelCase__ ): while quotient != 1: if is_prime(lowerCAmelCase__ ) and (quotient % factor == 0): ans.append(lowerCAmelCase__ ) quotient /= factor else: factor += 1 else: ans.append(lowerCAmelCase__ ) # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type list" return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] ) -> Tuple: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( number >= 0 ), "'number' bust been an int and >= 0" A = 0 # prime factorization of 'number' A = prime_factorization(lowerCAmelCase__ ) A = max(lowerCAmelCase__ ) # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type int" return ans def lowerCamelCase_ ( lowerCAmelCase__ : int ) -> List[Any]: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( number >= 0 ), "'number' bust been an int and >= 0" A = 0 # prime factorization of 'number' A = prime_factorization(lowerCAmelCase__ ) A = min(lowerCAmelCase__ ) # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type int" return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] ) -> Optional[int]: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'number' must been an int" assert isinstance(number % 2 == 0 , lowerCAmelCase__ ), "compare bust been from type bool" return number % 2 == 0 def lowerCamelCase_ ( lowerCAmelCase__ : Tuple ) -> Any: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'number' must been an int" assert isinstance(number % 2 != 0 , lowerCAmelCase__ ), "compare bust been from type bool" return number % 2 != 0 def lowerCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> int: '''simple docstring''' assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (number > 2) and is_even(lowerCAmelCase__ ) ), "'number' must been an int, even and > 2" A = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' A = get_prime_numbers(lowerCAmelCase__ ) A = len(lowerCAmelCase__ ) # run variable for while-loops. A = 0 A = None # exit variable. for break up the loops A = True while i < len_pn and loop: A = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: A = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (len(lowerCAmelCase__ ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[int] ) -> List[Any]: '''simple docstring''' assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." A = 0 while numbera != 0: A = numbera % numbera A = numbera A = rest # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[Any] ) -> Union[str, Any]: '''simple docstring''' assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." A = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' A = prime_factorization(lowerCAmelCase__ ) A = prime_factorization(lowerCAmelCase__ ) elif numbera == 1 or numbera == 1: A = [] A = [] A = max(lowerCAmelCase__ , lowerCAmelCase__ ) A = 0 A = 0 A = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: A = prime_fac_a.count(lowerCAmelCase__ ) A = prime_fac_a.count(lowerCAmelCase__ ) for _ in range(max(lowerCAmelCase__ , lowerCAmelCase__ ) ): ans *= n else: A = prime_fac_a.count(lowerCAmelCase__ ) for _ in range(lowerCAmelCase__ ): ans *= n done.append(lowerCAmelCase__ ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: A = prime_fac_a.count(lowerCAmelCase__ ) for _ in range(lowerCAmelCase__ ): ans *= n done.append(lowerCAmelCase__ ) # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def lowerCamelCase_ ( lowerCAmelCase__ : Tuple ) -> Any: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 0), "'number' must been a positive int" A = 0 A = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(lowerCAmelCase__ ): ans += 1 # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and is_prime( lowerCAmelCase__ ), "'ans' must been a prime number and from type int" return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str ) -> Optional[int]: '''simple docstring''' assert ( is_prime(lowerCAmelCase__ ) and is_prime(lowerCAmelCase__ ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" A = p_number_a + 1 # jump to the next number A = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(lowerCAmelCase__ ): number += 1 while number < p_number_a: ans.append(lowerCAmelCase__ ) number += 1 # fetch the next prime number. while not is_prime(lowerCAmelCase__ ): number += 1 # precondition assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ans[0] != p_number_a and ans[len(lowerCAmelCase__ ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] ) -> List[str]: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 1), "'n' must been int and >= 1" A = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(lowerCAmelCase__ ) # precondition assert ans[0] == 1 and ans[len(lowerCAmelCase__ ) - 1] == n, "Error in function getDivisiors(...)" return ans def lowerCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> Optional[Any]: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( number > 1 ), "'number' must been an int and >= 1" A = get_divisors(lowerCAmelCase__ ) # precondition assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (divisors[0] == 1) and (divisors[len(lowerCAmelCase__ ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def lowerCamelCase_ ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any] ) -> str: '''simple docstring''' assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. A = gcd(abs(lowerCAmelCase__ ) , abs(lowerCAmelCase__ ) ) # precondition assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def lowerCamelCase_ ( lowerCAmelCase__ : Dict ) -> int: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 0), "'n' must been a int and >= 0" A = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[str] ) -> Union[str, Any]: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 0), "'n' must been an int and >= 0" A = 0 A = 1 A = 1 # this will be return for _ in range(n - 1 ): A = ans ans += fiba A = tmp return ans
106
"""simple docstring""" # Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, nicht wahr?", } # BLUE scores as follows: # "pair": [fairseq, transformers] _UpperCAmelCase = { "wmt16-en-de-dist-12-1": [28.3, 27.52], "wmt16-en-de-dist-6-1": [27.4, 27.11], "wmt16-en-de-12-1": [26.9, 25.75], } _UpperCAmelCase = f"{src_lang}-{tgt_lang}" _UpperCAmelCase = f"\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"allenai/{model_name}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel | fairseq | transformers\n-------|---------|----------\n{model_name} | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don't use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n year={{2020}},\n eprint={{2006.10369}},\n archivePrefix={{arXiv}},\n primaryClass={{cs.CL}}\n}}\n```\n\n" model_card_dir.mkdir(parents=UpperCamelCase__ , exist_ok=UpperCamelCase__ ) _UpperCAmelCase = os.path.join(UpperCamelCase__ , "README.md" ) print(f"Generating {path}" ) with open(UpperCamelCase__ , "w" , encoding="utf-8" ) as f: f.write(UpperCamelCase__ ) # make sure we are under the root of the project __magic_name__ = Path(__file__).resolve().parent.parent.parent __magic_name__ = repo_dir / '''model_cards''' for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: __magic_name__ = model_cards_dir / '''allenai''' / model_name write_model_card(model_card_dir, src_lang='''en''', tgt_lang='''de''', model_name=model_name)
657
0
'''simple docstring''' from sklearn.metrics import fa_score import datasets _UpperCAmelCase : Dict = ''' The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) ''' _UpperCAmelCase : str = ''' Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`. - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives. - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric("f1") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {\'f1\': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric("f1") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results[\'f1\'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric("f1") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results[\'f1\'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro") >>> print(round(results[\'f1\'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro") >>> print(round(results[\'f1\'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted") >>> print(round(results[\'f1\'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {\'f1\': array([0.8, 0. , 0. ])} ''' _UpperCAmelCase : str = ''' @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase_ ( datasets.Metric ): """simple docstring""" def __UpperCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ), reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'], ) def __UpperCAmelCase ( self : Dict, UpperCamelCase__ : int, UpperCamelCase__ : List[Any], UpperCamelCase__ : Dict=None, UpperCamelCase__ : Dict=1, UpperCamelCase__ : List[Any]="binary", UpperCamelCase__ : str=None ) -> Optional[int]: _A = fa_score( UpperCamelCase__, UpperCamelCase__, labels=UpperCamelCase__, pos_label=UpperCamelCase__, average=UpperCamelCase__, sample_weight=UpperCamelCase__ ) return {"f1": float(UpperCamelCase__ ) if score.size == 1 else score}
107
"""simple docstring""" from ..utils import DummyObject, requires_backends class _lowerCAmelCase ( metaclass=lowerCamelCase ): lowercase_ : Dict = ['''torch''', '''torchsde'''] def __init__( self , *a_ , **a_ ) -> Optional[int]: requires_backends(self , ["torch", "torchsde"] ) @classmethod def _a ( cls , *a_ , **a_ ) -> Optional[Any]: requires_backends(cls , ["torch", "torchsde"] ) @classmethod def _a ( cls , *a_ , **a_ ) -> List[Any]: requires_backends(cls , ["torch", "torchsde"] )
657
0
import inspect import unittest from transformers import YolosConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import YolosForObjectDetection, YolosModel from transformers.models.yolos.modeling_yolos import YOLOS_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 : Dict , lowerCamelCase : Dict , lowerCamelCase : Any=13 , lowerCamelCase : List[Any]=[30, 30] , lowerCamelCase : Optional[Any]=2 , lowerCamelCase : Tuple=3 , lowerCamelCase : int=True , lowerCamelCase : Dict=True , lowerCamelCase : Tuple=32 , lowerCamelCase : Optional[int]=5 , lowerCamelCase : Tuple=4 , lowerCamelCase : Dict=37 , lowerCamelCase : int="gelu" , lowerCamelCase : Dict=0.1 , lowerCamelCase : str=0.1 , lowerCamelCase : Dict=10 , lowerCamelCase : Any=0.02 , lowerCamelCase : str=3 , lowerCamelCase : int=None , lowerCamelCase : int=8 , lowerCamelCase : Any=10 , ) -> List[str]: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = num_channels _UpperCAmelCase = is_training _UpperCAmelCase = use_labels _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = num_labels _UpperCAmelCase = scope _UpperCAmelCase = n_targets _UpperCAmelCase = num_detection_tokens # we set the expected sequence length (which is used in several tests) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens _UpperCAmelCase = (image_size[1] // patch_size) * (image_size[0] // patch_size) _UpperCAmelCase = num_patches + 1 + self.num_detection_tokens def lowerCamelCase ( self : List[Any] ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]] ) _UpperCAmelCase = None if self.use_labels: # labels is a list of Dict (each Dict being the labels for a given example in the batch) _UpperCAmelCase = [] for i in range(self.batch_size ): _UpperCAmelCase = {} _UpperCAmelCase = torch.randint( high=self.num_labels , size=(self.n_targets,) , device=lowerCamelCase ) _UpperCAmelCase = torch.rand(self.n_targets , 4 , device=lowerCamelCase ) labels.append(lowerCamelCase ) _UpperCAmelCase = self.get_config() return config, pixel_values, labels def lowerCamelCase ( self : List[str] ) -> Dict: """simple docstring""" return YolosConfig( 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=lowerCamelCase , initializer_range=self.initializer_range , num_detection_tokens=self.num_detection_tokens , num_labels=self.num_labels , ) def lowerCamelCase ( self : Dict , lowerCamelCase : Union[str, Any] , lowerCamelCase : str , lowerCamelCase : str ) -> Tuple: """simple docstring""" _UpperCAmelCase = YolosModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() _UpperCAmelCase = model(lowerCamelCase ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.expected_seq_len, self.hidden_size) ) def lowerCamelCase ( self : List[Any] , lowerCamelCase : str , lowerCamelCase : Union[str, Any] , lowerCamelCase : Tuple ) -> str: """simple docstring""" _UpperCAmelCase = YolosForObjectDetection(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() _UpperCAmelCase = model(pixel_values=lowerCamelCase ) _UpperCAmelCase = model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) _UpperCAmelCase = model(pixel_values=lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) def lowerCamelCase ( self : Dict ) -> Optional[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__ ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): '''simple docstring''' _lowerCamelCase = (YolosModel, YolosForObjectDetection) if is_torch_available() else () _lowerCamelCase = ( {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {} ) _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False def lowerCamelCase ( self : Optional[Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : Tuple=False ) -> str: """simple docstring""" _UpperCAmelCase = super()._prepare_for_class(lowerCamelCase , lowerCamelCase , return_labels=lowerCamelCase ) if return_labels: if model_class.__name__ == "YolosForObjectDetection": _UpperCAmelCase = [] for i in range(self.model_tester.batch_size ): _UpperCAmelCase = {} _UpperCAmelCase = torch.ones( size=(self.model_tester.n_targets,) , device=lowerCamelCase , dtype=torch.long ) _UpperCAmelCase = torch.ones( self.model_tester.n_targets , 4 , device=lowerCamelCase , dtype=torch.float ) labels.append(lowerCamelCase ) _UpperCAmelCase = labels return inputs_dict def lowerCamelCase ( self : Dict ) -> int: """simple docstring""" _UpperCAmelCase = YolosModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase , hidden_size=37 ) def lowerCamelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCamelCase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" # YOLOS does not use inputs_embeds pass def lowerCamelCase ( self : List[Any] ) -> str: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase , nn.Linear ) ) def lowerCamelCase ( self : Optional[Any] ) -> Tuple: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(lowerCamelCase ) _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] , lowerCamelCase ) def lowerCamelCase ( self : Optional[int] ) -> Dict: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def lowerCamelCase ( self : str ) -> Any: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = True # in YOLOS, the seq_len is different _UpperCAmelCase = self.model_tester.expected_seq_len for model_class in self.all_model_classes: _UpperCAmelCase = True _UpperCAmelCase = False _UpperCAmelCase = True _UpperCAmelCase = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) _UpperCAmelCase = outputs.attentions self.assertEqual(len(lowerCamelCase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _UpperCAmelCase = True _UpperCAmelCase = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) _UpperCAmelCase = outputs.attentions self.assertEqual(len(lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) _UpperCAmelCase = len(lowerCamelCase ) # Check attention is always last and order is fine _UpperCAmelCase = True _UpperCAmelCase = True _UpperCAmelCase = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) _UpperCAmelCase = 1 self.assertEqual(out_len + added_hidden_states , len(lowerCamelCase ) ) _UpperCAmelCase = outputs.attentions self.assertEqual(len(lowerCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def lowerCamelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" def check_hidden_states_output(lowerCamelCase : Dict , lowerCamelCase : Optional[int] , lowerCamelCase : Dict ): _UpperCAmelCase = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) _UpperCAmelCase = outputs.hidden_states _UpperCAmelCase = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(lowerCamelCase ) , lowerCamelCase ) # YOLOS has a different seq_length _UpperCAmelCase = self.model_tester.expected_seq_len self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) _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(lowerCamelCase , lowerCamelCase , lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ) def lowerCamelCase ( self : Optional[int] ) -> List[Any]: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_object_detection(*lowerCamelCase ) @slow def lowerCamelCase ( self : str ) -> Dict: """simple docstring""" for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = YolosModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: _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 lowerCamelCase ( self : Optional[Any] ) -> Tuple: """simple docstring""" return AutoImageProcessor.from_pretrained("""hustvl/yolos-small""" ) if is_vision_available() else None @slow def lowerCamelCase ( self : Optional[Any] ) -> List[str]: """simple docstring""" _UpperCAmelCase = YolosForObjectDetection.from_pretrained("""hustvl/yolos-small""" ).to(lowerCamelCase ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=lowerCamelCase , return_tensors="""pt""" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): _UpperCAmelCase = model(inputs.pixel_values ) # verify outputs _UpperCAmelCase = torch.Size((1, 100, 92) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) _UpperCAmelCase = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] , device=lowerCamelCase , ) _UpperCAmelCase = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] , device=lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , lowerCamelCase , atol=1E-4 ) ) self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] , lowerCamelCase , atol=1E-4 ) ) # verify postprocessing _UpperCAmelCase = image_processor.post_process_object_detection( lowerCamelCase , threshold=0.3 , target_sizes=[image.size[::-1]] )[0] _UpperCAmelCase = torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861] ).to(lowerCamelCase ) _UpperCAmelCase = [75, 75, 17, 63, 17] _UpperCAmelCase = torch.tensor([335.0609, 79.3848, 375.4216, 187.2495] ).to(lowerCamelCase ) self.assertEqual(len(results["""scores"""] ) , 5 ) self.assertTrue(torch.allclose(results["""scores"""] , lowerCamelCase , atol=1E-4 ) ) self.assertSequenceEqual(results["""labels"""].tolist() , lowerCamelCase ) self.assertTrue(torch.allclose(results["""boxes"""][0, :] , lowerCamelCase ) )
108
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __magic_name__ = logging.get_logger(__name__) class _lowerCAmelCase ( lowerCamelCase ): lowercase_ : Optional[Any] = '''upernet''' def __init__( self , a_=None , a_=512 , a_=0.02 , a_=[1, 2, 3, 6] , a_=True , a_=0.4 , a_=384 , a_=256 , a_=1 , a_=False , a_=255 , **a_ , ) -> List[Any]: super().__init__(**a_ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) _UpperCAmelCase = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(a_ , a_ ): _UpperCAmelCase = backbone_config.get("model_type" ) _UpperCAmelCase = CONFIG_MAPPING[backbone_model_type] _UpperCAmelCase = config_class.from_dict(a_ ) _UpperCAmelCase = backbone_config _UpperCAmelCase = hidden_size _UpperCAmelCase = initializer_range _UpperCAmelCase = pool_scales _UpperCAmelCase = use_auxiliary_head _UpperCAmelCase = auxiliary_loss_weight _UpperCAmelCase = auxiliary_in_channels _UpperCAmelCase = auxiliary_channels _UpperCAmelCase = auxiliary_num_convs _UpperCAmelCase = auxiliary_concat_input _UpperCAmelCase = loss_ignore_index def _a ( self ) -> int: _UpperCAmelCase = copy.deepcopy(self.__dict__ ) _UpperCAmelCase = self.backbone_config.to_dict() _UpperCAmelCase = self.__class__.model_type return output
657
0
'''simple docstring''' def __magic_name__ ( __UpperCAmelCase ) -> int: '''simple docstring''' if not isinstance(__UpperCAmelCase , __UpperCAmelCase ): raise ValueError("""multiplicative_persistence() only accepts integral values""" ) if num < 0: raise ValueError("""multiplicative_persistence() does not accept negative values""" ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = str(__UpperCAmelCase ) while len(__UpperCAmelCase ) != 1: __SCREAMING_SNAKE_CASE = [int(__UpperCAmelCase ) for i in num_string] __SCREAMING_SNAKE_CASE = 1 for i in range(0 , len(__UpperCAmelCase ) ): total *= numbers[i] __SCREAMING_SNAKE_CASE = str(__UpperCAmelCase ) steps += 1 return steps def __magic_name__ ( __UpperCAmelCase ) -> int: '''simple docstring''' if not isinstance(__UpperCAmelCase , __UpperCAmelCase ): raise ValueError("""additive_persistence() only accepts integral values""" ) if num < 0: raise ValueError("""additive_persistence() does not accept negative values""" ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = str(__UpperCAmelCase ) while len(__UpperCAmelCase ) != 1: __SCREAMING_SNAKE_CASE = [int(__UpperCAmelCase ) for i in num_string] __SCREAMING_SNAKE_CASE = 0 for i in range(0 , len(__UpperCAmelCase ) ): total += numbers[i] __SCREAMING_SNAKE_CASE = str(__UpperCAmelCase ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
109
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import _LazyModule __magic_name__ = {'''tokenization_tapex''': ['''TapexTokenizer''']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
657
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase__ = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
620
"""simple docstring""" import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase : def __init__( self , a_ , a_=2 , a_=3 , a_=4 , a_=2 , a_=7 , a_=True , a_=True , a_=True , a_=True , a_=99 , a_=36 , a_=3 , a_=4 , a_=37 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=16 , a_=2 , a_=0.02 , a_=6 , a_=6 , a_=3 , a_=4 , a_=None , a_=1000 , ) -> Optional[Any]: _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = text_seq_length _UpperCAmelCase = is_training _UpperCAmelCase = use_input_mask _UpperCAmelCase = use_token_type_ids _UpperCAmelCase = use_labels _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = coordinate_size _UpperCAmelCase = shape_size _UpperCAmelCase = num_labels _UpperCAmelCase = num_choices _UpperCAmelCase = scope _UpperCAmelCase = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) _UpperCAmelCase = text_seq_length _UpperCAmelCase = (image_size // patch_size) ** 2 + 1 _UpperCAmelCase = self.text_seq_length + self.image_seq_length def _a ( self ) -> Dict: _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_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]: _UpperCAmelCase = bbox[i, j, 3] _UpperCAmelCase = bbox[i, j, 1] _UpperCAmelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: _UpperCAmelCase = bbox[i, j, 2] _UpperCAmelCase = bbox[i, j, 0] _UpperCAmelCase = t _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_input_mask: _UpperCAmelCase = random_attention_mask([self.batch_size, self.text_seq_length] ) _UpperCAmelCase = None if self.use_token_type_ids: _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) _UpperCAmelCase = None _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) _UpperCAmelCase = LayoutLMvaConfig( 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 , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Tuple: _UpperCAmelCase = LayoutLMvaModel(config=a_ ) model.to(a_ ) model.eval() # text + image _UpperCAmelCase = model(a_ , pixel_values=a_ ) _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ , bbox=a_ , pixel_values=a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ , bbox=a_ , pixel_values=a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only _UpperCAmelCase = model(a_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only _UpperCAmelCase = model(pixel_values=a_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Optional[Any]: _UpperCAmelCase = self.num_labels _UpperCAmelCase = LayoutLMvaForSequenceClassification(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Union[str, Any]: _UpperCAmelCase = self.num_labels _UpperCAmelCase = LayoutLMvaForTokenClassification(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Dict: _UpperCAmelCase = LayoutLMvaForQuestionAnswering(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , start_positions=a_ , end_positions=a_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _a ( self ) -> Optional[int]: _UpperCAmelCase = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = config_and_inputs _UpperCAmelCase = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase_ : Any = False lowercase_ : Dict = False lowercase_ : List[str] = False lowercase_ : str = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) lowercase_ : int = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def _a ( self , a_ , a_ , a_ , a_ , a_ ) -> List[str]: # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = LayoutLMvaModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=a_ , hidden_size=37 ) def _a ( self , a_ , a_ , a_=False ) -> List[str]: _UpperCAmelCase = copy.deepcopy(a_ ) if model_class in get_values(a_ ): _UpperCAmelCase = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(a_ , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a_ ): _UpperCAmelCase = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in get_values(a_ ): _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in [ *get_values(a_ ), ]: _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in [ *get_values(a_ ), ]: _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=a_ , ) return inputs_dict def _a ( self ) -> int: self.config_tester.run_common_tests() def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _UpperCAmelCase = type self.model_tester.create_and_check_model(*a_ ) def _a ( self ) -> int: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a_ ) def _a ( self ) -> Any: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) @slow def _a ( self ) -> List[str]: for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = LayoutLMvaModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class _lowerCAmelCase ( unittest.TestCase ): @cached_property def _a ( self ) -> List[Any]: return LayoutLMvaImageProcessor(apply_ocr=a_ ) if is_vision_available() else None @slow def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ).to(a_ ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=a_ , return_tensors="pt" ).pixel_values.to(a_ ) _UpperCAmelCase = torch.tensor([[1, 2]] ) _UpperCAmelCase = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass _UpperCAmelCase = model( input_ids=input_ids.to(a_ ) , bbox=bbox.to(a_ ) , pixel_values=pixel_values.to(a_ ) , ) # verify the logits _UpperCAmelCase = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , a_ ) _UpperCAmelCase = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(a_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , a_ , atol=1e-4 ) )
657
0
from ...configuration_utils import PretrainedConfig lowercase : Tuple = { """google/tapas-base-finetuned-sqa""": ( """https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json""" ), """google/tapas-base-finetuned-wtq""": ( """https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json""" ), """google/tapas-base-finetuned-wikisql-supervised""": ( """https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json""" ), """google/tapas-base-finetuned-tabfact""": ( """https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json""" ), } class A__ ( __UpperCAmelCase ): """simple docstring""" __A : Optional[Any] = '''tapas''' def __init__( self , lowercase=3_0522 , lowercase=768 , lowercase=12 , lowercase=12 , lowercase=3072 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=1024 , lowercase=[3, 256, 256, 2, 256, 256, 10] , lowercase=0.02 , lowercase=1e-12 , lowercase=0 , lowercase=10.0 , lowercase=0 , lowercase=1.0 , lowercase=None , lowercase=1.0 , lowercase=False , lowercase=None , lowercase=1.0 , lowercase=1.0 , lowercase=False , lowercase=False , lowercase="ratio" , lowercase=None , lowercase=None , lowercase=64 , lowercase=32 , lowercase=False , lowercase=True , lowercase=False , lowercase=False , lowercase=True , lowercase=False , lowercase=None , lowercase=None , **lowercase , ) -> str: '''simple docstring''' super().__init__(pad_token_id=a_ , **a_) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) a__ : Optional[Any] = vocab_size a__ : Optional[int] = hidden_size a__ : List[str] = num_hidden_layers a__ : Optional[Any] = num_attention_heads a__ : Union[str, Any] = hidden_act a__ : int = intermediate_size a__ : Union[str, Any] = hidden_dropout_prob a__ : List[Any] = attention_probs_dropout_prob a__ : Union[str, Any] = max_position_embeddings a__ : Union[str, Any] = type_vocab_sizes a__ : Optional[int] = initializer_range a__ : Optional[int] = layer_norm_eps # Fine-tuning task hyperparameters a__ : int = positive_label_weight a__ : Optional[Any] = num_aggregation_labels a__ : Optional[Any] = aggregation_loss_weight a__ : Dict = use_answer_as_supervision a__ : Tuple = answer_loss_importance a__ : Union[str, Any] = use_normalized_answer_loss a__ : Optional[Any] = huber_loss_delta a__ : str = temperature a__ : List[str] = aggregation_temperature a__ : Optional[int] = use_gumbel_for_cells a__ : Optional[int] = use_gumbel_for_aggregation a__ : Any = average_approximation_function a__ : Dict = cell_selection_preference a__ : Optional[Any] = answer_loss_cutoff a__ : Tuple = max_num_rows a__ : Optional[int] = max_num_columns a__ : Optional[int] = average_logits_per_cell a__ : Union[str, Any] = select_one_column a__ : int = allow_empty_column_selection a__ : Tuple = init_cell_selection_weights_to_zero a__ : Tuple = reset_position_index_per_cell a__ : str = disable_per_token_loss # Aggregation hyperparameters a__ : str = aggregation_labels a__ : Union[str, Any] = no_aggregation_label_index if isinstance(self.aggregation_labels , a_): a__ : List[Any] = {int(a_): v for k, v in aggregation_labels.items()}
302
"""simple docstring""" import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class _lowerCAmelCase ( unittest.TestCase ): lowercase_ : str = MODEL_FOR_MASKED_LM_MAPPING lowercase_ : List[str] = TF_MODEL_FOR_MASKED_LM_MAPPING def _a ( self ) -> Optional[Any]: super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def _a ( self ) -> str: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="tf" ) _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is grouped", "score": 2.1e-05, "token": 38015, "token_str": " grouped"}, {"sequence": "My name is accuser", "score": 2.1e-05, "token": 25506, "token_str": " accuser"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ { "sequence": "The largest city in France is grouped", "score": 2.1e-05, "token": 38015, "token_str": " grouped", }, { "sequence": "The largest city in France is accuser", "score": 2.1e-05, "token": 25506, "token_str": " accuser", }, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, {"sequence": "My name is Patrick", "score": 2e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 1.9e-05, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="pt" ) _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul"}, {"sequence": "My name isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ { "sequence": "The largest city in France is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul", }, {"sequence": "The largest city in France isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Patrick", "score": 2.1e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 2e-05, "token": 2941, "token_str": " Te"}, {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, ] , ) _UpperCAmelCase = unmasker("My name is <mask> <mask>" , top_k=2 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ [ { "score": 2.2e-05, "token": 35676, "token_str": " Maul", "sequence": "<s>My name is Maul<mask></s>", }, {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name isELS<mask></s>"}, ], [ { "score": 2.2e-05, "token": 35676, "token_str": " Maul", "sequence": "<s>My name is<mask> Maul</s>", }, {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name is<mask>ELS</s>"}, ], ] , ) @require_torch_gpu def _a ( self ) -> int: _UpperCAmelCase = pipeline("fill-mask" , model="hf-internal-testing/tiny-random-distilbert" , device=0 , framework="pt" ) # convert model to fp16 pipe.model.half() _UpperCAmelCase = pipe("Paris is the [MASK] of France." ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(a_ , a_ ) @slow @require_torch def _a ( self ) -> int: _UpperCAmelCase = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="pt" ) self.run_large_test(a_ ) @slow @require_tf def _a ( self ) -> int: _UpperCAmelCase = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="tf" ) self.run_large_test(a_ ) def _a ( self , a_ ) -> int: _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ ) , [ {"sequence": "My name is John", "score": 0.008, "token": 610, "token_str": " John"}, {"sequence": "My name is Chris", "score": 0.007, "token": 1573, "token_str": " Chris"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ ) , [ { "sequence": "The largest city in France is Paris", "score": 0.251, "token": 2201, "token_str": " Paris", }, { "sequence": "The largest city in France is Lyon", "score": 0.214, "token": 12790, "token_str": " Lyon", }, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ ) , [ {"sequence": "My name is Patrick", "score": 0.005, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Clara", "score": 0.000, "token": 13606, "token_str": " Clara"}, {"sequence": "My name is Te", "score": 0.000, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _a ( self ) -> Any: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="pt" ) _UpperCAmelCase = None _UpperCAmelCase = None self.run_pipeline_test(a_ , [] ) @require_tf def _a ( self ) -> List[Any]: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="tf" ) _UpperCAmelCase = None _UpperCAmelCase = None self.run_pipeline_test(a_ , [] ) def _a ( self , a_ , a_ , a_ ) -> Optional[Any]: if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("The provided tokenizer has no mask token, (probably reformer or wav2vec2)" ) _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = [ f"This is another {tokenizer.mask_token} test", ] return fill_masker, examples def _a ( self , a_ , a_ ) -> List[str]: _UpperCAmelCase = fill_masker.tokenizer _UpperCAmelCase = fill_masker.model _UpperCAmelCase = fill_masker( f"This is a {tokenizer.mask_token}" , ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = fill_masker([f"This is a {tokenizer.mask_token}"] ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = fill_masker([f"This is a {tokenizer.mask_token}", f"Another {tokenizer.mask_token} great test."] ) self.assertEqual( a_ , [ [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], ] , ) with self.assertRaises(a_ ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(a_ ): fill_masker("This is" ) self.run_test_top_k(a_ , a_ ) self.run_test_targets(a_ , a_ ) self.run_test_top_k_targets(a_ , a_ ) self.fill_mask_with_duplicate_targets_and_top_k(a_ , a_ ) self.fill_mask_with_multiple_masks(a_ , a_ ) def _a ( self , a_ , a_ ) -> Optional[int]: _UpperCAmelCase = tokenizer.get_vocab() _UpperCAmelCase = sorted(vocab.keys() )[:2] # Pipeline argument _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ , targets=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , a_ ) _UpperCAmelCase = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(a_ ) ) # Call argument _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , a_ ) _UpperCAmelCase = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(a_ ) ) # Score equivalence _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) _UpperCAmelCase = [top_mask["token_str"] for top_mask in outputs] _UpperCAmelCase = [top_mask["score"] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(a_ ) == set(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) _UpperCAmelCase = [top_mask["score"] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) # Raises with invalid with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=[""] ) with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets="" ) def _a ( self , a_ , a_ ) -> str: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ , top_k=2 ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=2 ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) def _a ( self , a_ , a_ ) -> List[Any]: _UpperCAmelCase = tokenizer.get_vocab() _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) # top_k=2, ntargets=3 _UpperCAmelCase = sorted(vocab.keys() )[:3] _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=2 , targets=a_ ) # If we use the most probably targets, and filter differently, we should still # have the same results _UpperCAmelCase = [el["token_str"] for el in sorted(a_ , key=lambda a_ : x["score"] , reverse=a_ )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(a_ ).issubset(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=3 , targets=a_ ) # They should yield exactly the same result self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) def _a ( self , a_ , a_ ) -> Optional[Any]: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = tokenizer.get_vocab() # String duplicates + id duplicates _UpperCAmelCase = sorted(vocab.keys() )[:3] _UpperCAmelCase = [targets[0], targets[1], targets[0], targets[2], targets[1]] _UpperCAmelCase = fill_masker(f"My name is {tokenizer.mask_token}" , targets=a_ , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(a_ ) , 3 ) def _a ( self , a_ , a_ ) -> Any: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker( f"This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}" , top_k=2 ) self.assertEqual( a_ , [ [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], ] , )
657
0
'''simple docstring''' UpperCAmelCase_ : Optional[Any] = '\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' UpperCAmelCase_ : Optional[int] = [{'type': 'code', 'content': INSTALL_CONTENT}] UpperCAmelCase_ : str = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
365
"""simple docstring""" import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class _lowerCAmelCase ( lowerCamelCase ): def _a ( self ) -> List[str]: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> Optional[int]: with self.assertRaises(a_ ): _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def _a ( self ) -> int: with self.assertRaises(a_ ): _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("bool" ) , type=Value("int64" ) ) ) def _a ( self ) -> Optional[Any]: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> int: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , type=Value("int64" ) ) ) def _a ( self ) -> Dict: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , try_type=Value("int64" ) ) ) self.assertEqual(arr.type , pa.string() ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def _a ( self ) -> Tuple: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , type=ArrayaD((1, 3) , "int64" ) ) ) def _a ( self ) -> str: _UpperCAmelCase = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def _a ( self ) -> Tuple: _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def _a ( self ) -> List[str]: import PIL.Image _UpperCAmelCase = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( "datasets.arrow_writer.cast_to_python_objects" , side_effect=a_ ) as mock_cast_to_python_objects: _UpperCAmelCase = pa.array(TypedSequence([{"path": None, "bytes": B"image_bytes"}, pil_image] , type=Image() ) ) _UpperCAmelCase , _UpperCAmelCase = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("optimize_list_casting" , a_ ) self.assertFalse(kwargs["optimize_list_casting"] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferReader(UpperCamelCase__ ) if isinstance(UpperCamelCase__ , pa.Buffer ) else pa.memory_map(UpperCamelCase__ ) _UpperCAmelCase = pa.ipc.open_stream(UpperCamelCase__ ) _UpperCAmelCase = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = Features({"labels": ClassLabel(names=["neg", "pos"] )} ) with ArrowWriter(stream=UpperCamelCase__ , features=UpperCamelCase__ ) as writer: writer.write({"labels": 0} ) writer.write({"labels": 1} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pa.ipc.open_stream(UpperCamelCase__ ) _UpperCAmelCase = f.read_all() _UpperCAmelCase = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(UpperCamelCase__ ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: with pytest.raises(UpperCamelCase__ ): writer.write({"col_1": "foo", "col_2": 1} , key=[1, 2] ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: with pytest.raises(UpperCamelCase__ ): writer.write({"col_1": "foo", "col_2": 1} , key=10 ) writer.write({"col_1": "bar", "col_2": 2} , key=10 ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: writer.write({"col_1": "foo", "col_2": 1} , key=1 ) writer.write({"col_1": "bar", "col_2": 2} , key=2 ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) writer.write_batch({"col_1": [], "col_2": []} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_table(pa.Table.from_pydict({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_row(pa.Table.from_pydict({"col_1": ["foo"], "col_2": [1]} ) ) writer.write_row(pa.Table.from_pydict({"col_1": ["bar"], "col_2": [2]} ) ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __lowerCamelCase ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} _UpperCAmelCase = os.path.join(UpperCamelCase__ , "test.arrow" ) with ArrowWriter(path=UpperCamelCase__ , schema=pa.schema(UpperCamelCase__ ) ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(UpperCamelCase__ , 1 ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if pa.types.is_list(UpperCamelCase__ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if isinstance(lst[0] , UpperCamelCase__ ): change_first_primitive_element_in_list(lst[0] , UpperCamelCase__ ) else: _UpperCAmelCase = value @pytest.mark.parametrize("optimized_int_type, expected_dtype" , [(None, pa.intaa()), (Value("int32" ), pa.intaa())] ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.array(TypedSequence(UpperCamelCase__ , optimized_int_type=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( "col, expected_dtype" , [ ("attention_mask", pa.inta()), ("special_tokens_mask", pa.inta()), ("token_type_ids", pa.inta()), ("input_ids", pa.intaa()), ("other", pa.intaa()), ] , ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.array(OptimizedTypedSequence(UpperCamelCase__ , col=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications _UpperCAmelCase = copy.deepcopy(UpperCamelCase__ ) _UpperCAmelCase = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(UpperCamelCase__ , UpperCamelCase__ ) _UpperCAmelCase = pa.array(OptimizedTypedSequence(UpperCamelCase__ , col=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("raise_exception" , [False, True] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = str(tmp_path / "dataset-train.arrow" ) try: with ArrowWriter(path=UpperCamelCase__ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = "mock://dataset-train.arrow" with ArrowWriter(path=UpperCamelCase__ , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(UpperCamelCase__ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(UpperCamelCase__ ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ParquetWriter(stream=UpperCamelCase__ ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pq.read_table(UpperCamelCase__ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("embed_local_files" , [False, True] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" import PIL.Image _UpperCAmelCase = str(tmp_path / "test_image_rgb.jpg" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(UpperCamelCase__ , format="png" ) _UpperCAmelCase = pa.BufferOutputStream() with ParquetWriter( stream=UpperCamelCase__ , features=Features({"image": Image()} ) , embed_local_files=UpperCamelCase__ ) as writer: writer.write({"image": image_path} ) writer.finalize() _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pq.read_table(UpperCamelCase__ ) _UpperCAmelCase = pa_table.to_pydict() if embed_local_files: assert isinstance(out["image"][0]["path"] , UpperCamelCase__ ) with open(UpperCamelCase__ , "rb" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.schema([pa.field("col_1" , pa.string() , nullable=UpperCamelCase__ )] ) _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter(stream=UpperCamelCase__ ) as writer: writer._build_writer(inferred_schema=UpperCamelCase__ ) assert writer._schema == pa.schema([pa.field("col_1" , pa.string() )] )
657
0
'''simple docstring''' def lowerCamelCase__ ( A : int , A : Optional[int] ): '''simple docstring''' if b == 0: return 1 if (b % 2) == 0: return actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) else: return a * actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) def lowerCamelCase__ ( A : Optional[Any] , A : Dict ): '''simple docstring''' if b < 0: return 1 / actual_power(UpperCamelCase__ , UpperCamelCase__ ) return actual_power(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": print(power(-2, -3))
210
"""simple docstring""" import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class _lowerCAmelCase ( unittest.TestCase ): def _a ( self ) -> Optional[Any]: _UpperCAmelCase = ["a", "b", "c"] # Defaults to last layer if both are None _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , a_ , a_ ) self.assertEqual(a_ , ["c"] ) self.assertEqual(a_ , [2] ) # Out indices set to match out features _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(["a", "c"] , a_ , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features set to match out indices _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , [0, 2] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features selected from negative indices _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , [-3, -1] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [-3, -1] ) def _a ( self ) -> Optional[int]: # Stage names must be set with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , a_ ) # Out features must be a list with self.assertRaises(a_ ): verify_out_features_out_indices(("a", "b") , (0, 1) , ["a", "b"] ) # Out features must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , ["a"] ) # Out indices must be a list or tuple with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , 0 , ["a", "b"] ) # Out indices must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , (0, 1) , ["a"] ) # Out features and out indices must be the same length with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0,) , ["a", "b", "c"] ) # Out features should match out indices with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 2) , ["a", "b", "c"] ) # Out features and out indices should be in order with self.assertRaises(a_ ): verify_out_features_out_indices(["b", "a"] , (0, 1) , ["a", "b"] ) # Check passes with valid inputs verify_out_features_out_indices(["a", "b", "d"] , (0, 1, -1) , ["a", "b", "c", "d"] ) def _a ( self ) -> int: _UpperCAmelCase = BackboneMixin() _UpperCAmelCase = ["a", "b", "c"] _UpperCAmelCase = ["a", "c"] _UpperCAmelCase = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly _UpperCAmelCase = ["a", "b"] self.assertEqual(backbone.out_features , ["a", "b"] ) self.assertEqual(backbone.out_indices , [0, 1] ) _UpperCAmelCase = [-3, -1] self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [-3, -1] )
657
0
from math import factorial def __a ( __UpperCAmelCase : Dict = 100 ) -> int: """simple docstring""" return sum(int(UpperCamelCase__ ) for x in str(factorial(UpperCamelCase__ ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
488
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = { '''configuration_electra''': ['''ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ElectraConfig''', '''ElectraOnnxConfig'''], '''tokenization_electra''': ['''ElectraTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''ElectraTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''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: __magic_name__ = [ '''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: __magic_name__ = [ '''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 __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
657
0
from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE ( metaclass=lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Dict = ['''torch''', '''torchsde'''] def __init__( self : Optional[int] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Tuple ): requires_backends(self , ["torch", "torchsde"] ) @classmethod def _A ( cls : Optional[int] , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Optional[int] ): requires_backends(cls , ["torch", "torchsde"] ) @classmethod def _A ( cls : Any , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(cls , ["torch", "torchsde"] )
62
"""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 _lowerCAmelCase ( lowerCamelCase , unittest.TestCase ): lowercase_ : Tuple = BarthezTokenizer lowercase_ : List[Any] = BarthezTokenizerFast lowercase_ : Dict = True lowercase_ : int = True def _a ( self ) -> Any: super().setUp() _UpperCAmelCase = BarthezTokenizerFast.from_pretrained("moussaKam/mbarthez" ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=a_ ) _UpperCAmelCase = tokenizer def _a ( self ) -> List[Any]: _UpperCAmelCase = "<pad>" _UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = 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(a_ ) , 101122 ) def _a ( self ) -> Union[str, Any]: self.assertEqual(self.get_tokenizer().vocab_size , 101122 ) @require_torch def _a ( self ) -> List[Any]: _UpperCAmelCase = ["A long paragraph for summarization.", "Another paragraph for summarization."] _UpperCAmelCase = [0, 57, 3018, 70307, 91, 2] _UpperCAmelCase = self.tokenizer( a_ , max_length=len(a_ ) , padding=a_ , truncation=a_ , return_tensors="pt" ) self.assertIsInstance(a_ , a_ ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) _UpperCAmelCase = batch.input_ids.tolist()[0] self.assertListEqual(a_ , a_ ) def _a ( self ) -> str: if not self.test_rust_tokenizer: return _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = self.get_rust_tokenizer() _UpperCAmelCase = "I was born in 92000, and this is falsé." _UpperCAmelCase = tokenizer.tokenize(a_ ) _UpperCAmelCase = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) _UpperCAmelCase = tokenizer.encode(a_ , add_special_tokens=a_ ) _UpperCAmelCase = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) _UpperCAmelCase = self.get_rust_tokenizer() _UpperCAmelCase = tokenizer.encode(a_ ) _UpperCAmelCase = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def _a ( self ) -> Dict: # fmt: off _UpperCAmelCase = {"input_ids": [[0, 490, 14328, 4507, 354, 47, 43669, 95, 25, 78117, 20215, 19779, 190, 22, 400, 4, 35343, 80310, 603, 86, 24937, 105, 33438, 94762, 196, 39642, 7, 15, 15933, 173, 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, 10534, 87, 25, 66, 3358, 196, 55289, 8, 82961, 81, 2204, 75203, 7, 15, 763, 12956, 216, 178, 14328, 9595, 1377, 69693, 7, 448, 71021, 196, 18106, 1437, 13974, 108, 9083, 4, 49315, 7, 39, 86, 1326, 2793, 46333, 4, 448, 196, 74588, 7, 49315, 7, 39, 21, 822, 38470, 74, 21, 66723, 62480, 8, 22050, 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. _UpperCAmelCase = [ "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=a_ , model_name="moussaKam/mbarthez" , revision="c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6" , sequences=a_ , )
657
0
class snake_case__ : # Public class to implement a graph def __init__( self : Tuple , _lowerCamelCase : Tuple , _lowerCamelCase : List[str] , _lowerCamelCase : Any ): snake_case__ : Tuple = row snake_case__ : Optional[int] = col snake_case__ : Optional[Any] = graph def UpperCAmelCase__ ( self : Union[str, Any] , _lowerCamelCase : Tuple , _lowerCamelCase : str , _lowerCamelCase : int ): return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def UpperCAmelCase__ ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : int ): # Checking all 8 elements surrounding nth element snake_case__ : List[str] = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order snake_case__ : Dict = [-1, 0, 1, -1, 1, -1, 0, 1] snake_case__ : List[str] = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , a_ ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , a_ ) def UpperCAmelCase__ ( self : Any ): # And finally, count all islands. snake_case__ : Union[str, Any] = [[False for j in range(self.COL )] for i in range(self.ROW )] snake_case__ : Optional[Any] = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(a_ , a_ , a_ ) count += 1 return count
170
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): _UpperCAmelCase = f"Input value of [number={number}] must be an integer" raise TypeError(UpperCamelCase__ ) if number < 0: return False _UpperCAmelCase = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
657
0
import os from pathlib import Path def lowerCAmelCase__ ( _a : str , _a : List[str] , _a : str , _a : Dict ): snake_case_ : Tuple = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, nicht wahr?", } # BLUE scores as follows: # "pair": [fairseq, transformers] snake_case_ : Any = { "wmt16-en-de-dist-12-1": [28.3, 27.52], "wmt16-en-de-dist-6-1": [27.4, 27.11], "wmt16-en-de-12-1": [26.9, 25.75], } snake_case_ : List[str] = F'''{src_lang}-{tgt_lang}''' snake_case_ : str = F'''\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"allenai/{model_name}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel | fairseq | transformers\n-------|---------|----------\n{model_name} | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don\'t use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n year={{2020}},\n eprint={{2006.10369}},\n archivePrefix={{arXiv}},\n primaryClass={{cs.CL}}\n}}\n```\n\n''' model_card_dir.mkdir(parents=UpperCamelCase__ , exist_ok=UpperCamelCase__ ) snake_case_ : str = os.path.join(UpperCamelCase__ , "README.md" ) print(F'''Generating {path}''' ) with open(UpperCamelCase__ , "w" , encoding="utf-8" ) as f: f.write(UpperCamelCase__ ) # make sure we are under the root of the project lowercase : List[Any] = Path(__file__).resolve().parent.parent.parent lowercase : List[str] = repo_dir / '''model_cards''' for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: lowercase : int = model_cards_dir / '''allenai''' / model_name write_model_card(model_card_dir, src_lang='''en''', tgt_lang='''de''', model_name=model_name)
568
"""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(lowerCamelCase ) class _lowerCAmelCase ( lowerCamelCase ): def __init__( self , *a_ , **a_ ) -> Optional[int]: super().__init__(*a_ , **a_ ) 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 _a ( self , **a_ ) -> List[str]: _UpperCAmelCase = {} if "threshold" in kwargs: _UpperCAmelCase = kwargs["threshold"] return {}, {}, postprocess_kwargs def __call__( self , *a_ , **a_ ) -> Union[Predictions, List[Prediction]]: return super().__call__(*a_ , **a_ ) def _a ( self , a_ ) -> Optional[Any]: _UpperCAmelCase = load_image(a_ ) _UpperCAmelCase = torch.IntTensor([[image.height, image.width]] ) _UpperCAmelCase = self.image_processor(images=[image] , return_tensors="pt" ) if self.tokenizer is not None: _UpperCAmelCase = self.tokenizer(text=inputs["words"] , boxes=inputs["boxes"] , return_tensors="pt" ) _UpperCAmelCase = target_size return inputs def _a ( self , a_ ) -> Optional[Any]: _UpperCAmelCase = model_inputs.pop("target_size" ) _UpperCAmelCase = self.model(**a_ ) _UpperCAmelCase = outputs.__class__({"target_size": target_size, **outputs} ) if self.tokenizer is not None: _UpperCAmelCase = model_inputs["bbox"] return model_outputs def _a ( self , a_ , a_=0.9 ) -> int: _UpperCAmelCase = 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. _UpperCAmelCase , _UpperCAmelCase = target_size[0].tolist() def unnormalize(a_ ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) _UpperCAmelCase , _UpperCAmelCase = model_outputs["logits"].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) _UpperCAmelCase = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] _UpperCAmelCase = [unnormalize(a_ ) for bbox in model_outputs["bbox"].squeeze(0 )] _UpperCAmelCase = ["score", "label", "box"] _UpperCAmelCase = [dict(zip(a_ , a_ ) ) for vals in zip(scores.tolist() , a_ , a_ ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel _UpperCAmelCase = self.image_processor.post_process_object_detection(a_ , a_ , a_ ) _UpperCAmelCase = raw_annotations[0] _UpperCAmelCase = raw_annotation["scores"] _UpperCAmelCase = raw_annotation["labels"] _UpperCAmelCase = raw_annotation["boxes"] _UpperCAmelCase = scores.tolist() _UpperCAmelCase = [self.model.config.idalabel[label.item()] for label in labels] _UpperCAmelCase = [self._get_bounding_box(a_ ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] _UpperCAmelCase = ["score", "label", "box"] _UpperCAmelCase = [ dict(zip(a_ , a_ ) ) for vals in zip(raw_annotation["scores"] , raw_annotation["labels"] , raw_annotation["boxes"] ) ] return annotation def _a ( self , a_ ) -> Dict[str, int]: if self.framework != "pt": raise ValueError("The ObjectDetectionPipeline is only available in PyTorch." ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = box.int().tolist() _UpperCAmelCase = { "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax, } return bbox
657
0
from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging UpperCAmelCase__ = logging.get_logger(__name__) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = ['''pixel_values'''] def __init__( self : Union[str, Any] , __UpperCAmelCase : Optional[int] = True , __UpperCAmelCase : Union[str, Any] = 32 , __UpperCAmelCase : Optional[Any]=PILImageResampling.BILINEAR , __UpperCAmelCase : Optional[int] = True , **__UpperCAmelCase : Optional[int] , ) ->None: """simple docstring""" a = do_resize a = do_rescale a = size_divisor a = resample super().__init__(**a_ ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any] = None , **__UpperCAmelCase : Union[str, Any] ) ->np.ndarray: """simple docstring""" a , a = get_image_size(a_ ) # Rounds the height and width down to the closest multiple of size_divisor a = height // size_divisor * size_divisor a = width // size_divisor * size_divisor a = resize(a_ , (new_h, new_w) , resample=a_ , data_format=a_ , **a_ ) return image def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : int , __UpperCAmelCase : List[Any] = None , **__UpperCAmelCase : List[str] ) ->np.ndarray: """simple docstring""" return rescale(image=a_ , scale=a_ , data_format=a_ , **a_ ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : str = None , __UpperCAmelCase : Optional[Any]=None , __UpperCAmelCase : List[str] = None , __UpperCAmelCase : Optional[Any] = None , __UpperCAmelCase : Tuple = ChannelDimension.FIRST , **__UpperCAmelCase : Optional[int] , ) ->BatchFeature: """simple docstring""" a = do_resize if do_resize is not None else self.do_resize a = do_rescale if do_rescale is not None else self.do_rescale a = size_divisor if size_divisor is not None else self.size_divisor a = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('''size_divisor is required for resizing''' ) a = make_list_of_images(a_ ) if not valid_images(a_ ): raise ValueError('''Invalid image(s)''' ) # All transformations expect numpy arrays. a = [to_numpy_array(a_ ) for img in images] if do_resize: a = [self.resize(a_ , size_divisor=a_ , resample=a_ ) for image in images] if do_rescale: a = [self.rescale(a_ , scale=1 / 255 ) for image in images] a = [to_channel_dimension_format(a_ , a_ ) for image in images] a = {'''pixel_values''': images} return BatchFeature(data=a_ , tensor_type=a_ )
117
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def merge(UpperCamelCase__ , UpperCamelCase__ ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(UpperCamelCase__ ) <= 1: return collection _UpperCAmelCase = len(UpperCamelCase__ ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() __magic_name__ = input('''Enter numbers separated by a comma:\n''').strip() __magic_name__ = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
657
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A = { "configuration_xlm": ["XLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMConfig", "XLMOnnxConfig"], "tokenization_xlm": ["XLMTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = [ "XLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMForMultipleChoice", "XLMForQuestionAnswering", "XLMForQuestionAnsweringSimple", "XLMForSequenceClassification", "XLMForTokenClassification", "XLMModel", "XLMPreTrainedModel", "XLMWithLMHeadModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = [ "TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLMForMultipleChoice", "TFXLMForQuestionAnsweringSimple", "TFXLMForSequenceClassification", "TFXLMForTokenClassification", "TFXLMMainLayer", "TFXLMModel", "TFXLMPreTrainedModel", "TFXLMWithLMHeadModel", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
475
"""simple docstring""" 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 _lowerCAmelCase : def __init__( self , a_ , a_=13 , a_=7 , a_=True , a_=True , a_=True , a_=99 , a_=32 , a_=5 , a_=4 , a_=37 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=16 , a_=2 , a_=0.02 , a_=3 , a_=4 , a_=None , ) -> List[str]: _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = seq_length _UpperCAmelCase = is_training _UpperCAmelCase = use_token_type_ids _UpperCAmelCase = use_labels _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = num_labels _UpperCAmelCase = num_choices _UpperCAmelCase = scope _UpperCAmelCase = self.vocab_size - 1 def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCAmelCase = None if self.use_token_type_ids: _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) _UpperCAmelCase = 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 , ) _UpperCAmelCase = 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 _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Optional[int]: _UpperCAmelCase = OpenAIGPTModel(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , head_mask=a_ ) _UpperCAmelCase = model(a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> List[Any]: _UpperCAmelCase = OpenAIGPTLMHeadModel(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Optional[Any]: _UpperCAmelCase = OpenAIGPTDoubleHeadsModel(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Dict: _UpperCAmelCase = self.num_labels _UpperCAmelCase = OpenAIGPTForSequenceClassification(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = config_and_inputs _UpperCAmelCase = { "input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask, } return config, inputs_dict @require_torch class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase_ : Any = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowercase_ : Optional[Any] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowercase_ : Union[str, Any] = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def _a ( self , a_ , a_ , a_ , a_ , a_ ) -> Any: 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 _a ( self , a_ , a_ , a_=False ) -> Optional[int]: _UpperCAmelCase = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=a_ , ) _UpperCAmelCase = inputs_dict["labels"] _UpperCAmelCase = inputs_dict["labels"] _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=a_ , ) _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) return inputs_dict def _a ( self ) -> Optional[int]: _UpperCAmelCase = OpenAIGPTModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=a_ , n_embd=37 ) def _a ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def _a ( self ) -> Any: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*a_ ) def _a ( self ) -> Tuple: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*a_ ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a_ ) @slow def _a ( self ) -> int: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = OpenAIGPTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) @require_torch class _lowerCAmelCase ( unittest.TestCase ): @slow def _a ( self ) -> Any: _UpperCAmelCase = OpenAIGPTLMHeadModel.from_pretrained("openai-gpt" ) model.to(a_ ) _UpperCAmelCase = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=a_ ) # the president is _UpperCAmelCase = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 40477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the _UpperCAmelCase = model.generate(a_ , do_sample=a_ ) self.assertListEqual(output_ids[0].tolist() , a_ )
657
0
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class __A (unittest.TestCase ): def __init__( self , UpperCamelCase_ , UpperCamelCase_=7 , UpperCamelCase_=3 , UpperCamelCase_=30 , UpperCamelCase_=4_00 , UpperCamelCase_=True , UpperCamelCase_=None , UpperCamelCase_=True , UpperCamelCase_=[0.5, 0.5, 0.5] , UpperCamelCase_=[0.5, 0.5, 0.5] , UpperCamelCase_=True , UpperCamelCase_=1 / 2_55 , UpperCamelCase_=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __UpperCAmelCase : List[str] = size if size is not None else {"shortest_edge": 18, "longest_edge": 13_33} __UpperCAmelCase : Optional[int] = parent __UpperCAmelCase : List[Any] = batch_size __UpperCAmelCase : Optional[Any] = num_channels __UpperCAmelCase : int = min_resolution __UpperCAmelCase : Dict = max_resolution __UpperCAmelCase : Any = do_resize __UpperCAmelCase : Union[str, Any] = size __UpperCAmelCase : List[str] = do_normalize __UpperCAmelCase : List[str] = image_mean __UpperCAmelCase : Any = image_std __UpperCAmelCase : Optional[Any] = do_rescale __UpperCAmelCase : Any = rescale_factor __UpperCAmelCase : Tuple = do_pad def _snake_case ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_=False ): if not batched: __UpperCAmelCase : Optional[Any] = image_inputs[0] if isinstance(a_ , Image.Image ): __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = image.size else: __UpperCAmelCase , __UpperCAmelCase : Tuple = image.shape[1], image.shape[2] if w < h: __UpperCAmelCase : str = int(self.size["shortest_edge"] * h / w ) __UpperCAmelCase : Optional[Any] = self.size["shortest_edge"] elif w > h: __UpperCAmelCase : int = self.size["shortest_edge"] __UpperCAmelCase : Optional[int] = int(self.size["shortest_edge"] * w / h ) else: __UpperCAmelCase : Any = self.size["shortest_edge"] __UpperCAmelCase : int = self.size["shortest_edge"] else: __UpperCAmelCase : str = [] for image in image_inputs: __UpperCAmelCase , __UpperCAmelCase : str = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __UpperCAmelCase : List[Any] = max(a_ , key=lambda UpperCamelCase_ : item[0] )[0] __UpperCAmelCase : Optional[int] = max(a_ , key=lambda UpperCamelCase_ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __A (__magic_name__ , unittest.TestCase ): snake_case :Tuple = ConditionalDetrImageProcessor if is_vision_available() else None def _snake_case ( self ): __UpperCAmelCase : Any = ConditionalDetrImageProcessingTester(self ) @property def _snake_case ( self ): return self.image_processor_tester.prepare_image_processor_dict() def _snake_case ( self ): __UpperCAmelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , "image_mean" ) ) self.assertTrue(hasattr(a_ , "image_std" ) ) self.assertTrue(hasattr(a_ , "do_normalize" ) ) self.assertTrue(hasattr(a_ , "do_resize" ) ) self.assertTrue(hasattr(a_ , "size" ) ) def _snake_case ( self ): __UpperCAmelCase : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 13_33} ) self.assertEqual(image_processor.do_pad , a_ ) __UpperCAmelCase : str = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=a_ ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , a_ ) def _snake_case ( self ): pass def _snake_case ( self ): # Initialize image_processing __UpperCAmelCase : int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __UpperCAmelCase : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input __UpperCAmelCase : Tuple = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __UpperCAmelCase , __UpperCAmelCase : Tuple = self.image_processor_tester.get_expected_values(a_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCAmelCase , __UpperCAmelCase : str = self.image_processor_tester.get_expected_values(a_ , batched=a_ ) __UpperCAmelCase : List[str] = image_processing(a_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _snake_case ( self ): # Initialize image_processing __UpperCAmelCase : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __UpperCAmelCase : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) # Test not batched input __UpperCAmelCase : List[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __UpperCAmelCase , __UpperCAmelCase : Tuple = self.image_processor_tester.get_expected_values(a_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCAmelCase : Tuple = image_processing(a_ , return_tensors="pt" ).pixel_values __UpperCAmelCase , __UpperCAmelCase : List[str] = self.image_processor_tester.get_expected_values(a_ , batched=a_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _snake_case ( self ): # Initialize image_processing __UpperCAmelCase : int = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __UpperCAmelCase : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input __UpperCAmelCase : int = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __UpperCAmelCase , __UpperCAmelCase : List[Any] = self.image_processor_tester.get_expected_values(a_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCAmelCase : Optional[Any] = image_processing(a_ , return_tensors="pt" ).pixel_values __UpperCAmelCase , __UpperCAmelCase : List[str] = self.image_processor_tester.get_expected_values(a_ , batched=a_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _snake_case ( self ): # prepare image and target __UpperCAmelCase : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: __UpperCAmelCase : Tuple = json.loads(f.read() ) __UpperCAmelCase : int = {"image_id": 3_97_69, "annotations": target} # encode them __UpperCAmelCase : str = ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50" ) __UpperCAmelCase : Tuple = image_processing(images=a_ , annotations=a_ , return_tensors="pt" ) # verify pixel values __UpperCAmelCase : int = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["pixel_values"].shape , a_ ) __UpperCAmelCase : List[Any] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , a_ , atol=1E-4 ) ) # verify area __UpperCAmelCase : List[Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , a_ ) ) # verify boxes __UpperCAmelCase : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , a_ ) __UpperCAmelCase : List[Any] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , a_ , atol=1E-3 ) ) # verify image_id __UpperCAmelCase : Union[str, Any] = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , a_ ) ) # verify is_crowd __UpperCAmelCase : int = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , a_ ) ) # verify class_labels __UpperCAmelCase : Union[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , a_ ) ) # verify orig_size __UpperCAmelCase : Optional[int] = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , a_ ) ) # verify size __UpperCAmelCase : Optional[Any] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , a_ ) ) @slow def _snake_case ( self ): # prepare image, target and masks_path __UpperCAmelCase : List[str] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: __UpperCAmelCase : Union[str, Any] = json.loads(f.read() ) __UpperCAmelCase : List[Any] = {"file_name": "000000039769.png", "image_id": 3_97_69, "segments_info": target} __UpperCAmelCase : Optional[Any] = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __UpperCAmelCase : str = ConditionalDetrImageProcessor(format="coco_panoptic" ) __UpperCAmelCase : Any = image_processing(images=a_ , annotations=a_ , masks_path=a_ , return_tensors="pt" ) # verify pixel values __UpperCAmelCase : int = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["pixel_values"].shape , a_ ) __UpperCAmelCase : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , a_ , atol=1E-4 ) ) # verify area __UpperCAmelCase : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , a_ ) ) # verify boxes __UpperCAmelCase : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , a_ ) __UpperCAmelCase : Tuple = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , a_ , atol=1E-3 ) ) # verify image_id __UpperCAmelCase : int = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , a_ ) ) # verify is_crowd __UpperCAmelCase : int = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , a_ ) ) # verify class_labels __UpperCAmelCase : Dict = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , a_ ) ) # verify masks __UpperCAmelCase : Dict = 82_28_73 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , a_ ) # verify orig_size __UpperCAmelCase : Optional[int] = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , a_ ) ) # verify size __UpperCAmelCase : Dict = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , a_ ) )
168
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__=10 ): """simple docstring""" _UpperCAmelCase = [] for _ in range(UpperCamelCase__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__=10 ): """simple docstring""" _UpperCAmelCase = [] for step in range(UpperCamelCase__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase = os.path.join(UpperCamelCase__ , "schedule.bin" ) torch.save(scheduler.state_dict() , UpperCamelCase__ ) _UpperCAmelCase = torch.load(UpperCamelCase__ ) scheduler.load_state_dict(UpperCamelCase__ ) return lrs @require_torch class _lowerCAmelCase ( unittest.TestCase ): def _a ( self , a_ , a_ , a_ ) -> Optional[int]: self.assertEqual(len(a_ ) , len(a_ ) ) for a, b in zip(a_ , a_ ): self.assertAlmostEqual(a_ , a_ , delta=a_ ) def _a ( self ) -> str: _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=a_ ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(100 ): _UpperCAmelCase = criterion(a_ , a_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=a_ ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = Adafactor( params=[w] , lr=1e-2 , eps=(1e-30, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=a_ , weight_decay=0.0 , relative_step=a_ , scale_parameter=a_ , warmup_init=a_ , ) for _ in range(1000 ): _UpperCAmelCase = criterion(a_ , a_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class _lowerCAmelCase ( unittest.TestCase ): lowercase_ : List[Any] = nn.Linear(50 , 50 ) if is_torch_available() else None lowercase_ : Tuple = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None lowercase_ : Dict = 10 def _a ( self , a_ , a_ , a_ , a_=None ) -> Union[str, Any]: self.assertEqual(len(a_ ) , len(a_ ) ) for a, b in zip(a_ , a_ ): self.assertAlmostEqual(a_ , a_ , delta=a_ , msg=a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = {"num_warmup_steps": 2, "num_training_steps": 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _UpperCAmelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {"num_warmup_steps": 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, "num_cycles": 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, "power": 2.0, "lr_end": 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {"num_warmup_steps": 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _UpperCAmelCase , _UpperCAmelCase = data _UpperCAmelCase = scheduler_func(self.optimizer , **a_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _UpperCAmelCase = unwrap_schedule(a_ , self.num_steps ) self.assertListAlmostEqual( a_ , a_ , tol=1e-2 , msg=f"failed for {scheduler_func} in normal scheduler" , ) _UpperCAmelCase = scheduler_func(self.optimizer , **a_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(a_ ) # wrap to test picklability of the schedule _UpperCAmelCase = unwrap_and_save_reload_schedule(a_ , self.num_steps ) self.assertListEqual(a_ , a_ , msg=f"failed for {scheduler_func} in save and reload" ) class _lowerCAmelCase : def __init__( self , a_ ) -> Union[str, Any]: _UpperCAmelCase = fn def __call__( self , *a_ , **a_ ) -> Union[str, Any]: return self.fn(*a_ , **a_ ) @classmethod def _a ( self , a_ ) -> Dict: _UpperCAmelCase = list(map(self , scheduler.lr_lambdas ) )
657
0
'''simple docstring''' import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, ) UpperCamelCase__ = logging.getLogger(__name__) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): """simple docstring""" lowercase_ : List[str] = git.Repo(search_parent_directories=UpperCamelCase__ ) lowercase_ : str = { "repo_id": str(UpperCamelCase__ ), "repo_sha": str(repo.head.object.hexsha ), "repo_branch": str(repo.active_branch ), } with open(os.path.join(UpperCamelCase__ , "git_log.json" ) , "w" ) as f: json.dump(UpperCamelCase__ , UpperCamelCase__ , indent=4 ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): """simple docstring""" if params.n_gpu <= 0: lowercase_ : Tuple = 0 lowercase_ : Tuple = -1 lowercase_ : str = True lowercase_ : Optional[Any] = False return assert torch.cuda.is_available() logger.info("Initializing GPUs" ) if params.n_gpu > 1: assert params.local_rank != -1 lowercase_ : Dict = int(os.environ["WORLD_SIZE"] ) lowercase_ : str = int(os.environ["N_GPU_NODE"] ) lowercase_ : List[Any] = int(os.environ["RANK"] ) # number of nodes / node ID lowercase_ : Union[str, Any] = params.world_size // params.n_gpu_per_node lowercase_ : Optional[int] = params.global_rank // params.n_gpu_per_node lowercase_ : List[str] = True assert params.n_nodes == int(os.environ["N_NODES"] ) assert params.node_id == int(os.environ["NODE_RANK"] ) # local job (single GPU) else: assert params.local_rank == -1 lowercase_ : List[str] = 1 lowercase_ : Dict = 0 lowercase_ : Any = 0 lowercase_ : List[str] = 0 lowercase_ : int = 1 lowercase_ : str = 1 lowercase_ : Optional[int] = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode lowercase_ : Optional[int] = params.node_id == 0 and params.local_rank == 0 lowercase_ : Any = params.n_nodes > 1 # summary lowercase_ : Any = F"""--- Global rank: {params.global_rank} - """ logger.info(PREFIX + "Number of nodes: %i" % params.n_nodes ) logger.info(PREFIX + "Node ID : %i" % params.node_id ) logger.info(PREFIX + "Local rank : %i" % params.local_rank ) logger.info(PREFIX + "World size : %i" % params.world_size ) logger.info(PREFIX + "GPUs per node : %i" % params.n_gpu_per_node ) logger.info(PREFIX + "Master : %s" % str(params.is_master ) ) logger.info(PREFIX + "Multi-node : %s" % str(params.multi_node ) ) logger.info(PREFIX + "Multi-GPU : %s" % str(params.multi_gpu ) ) logger.info(PREFIX + "Hostname : %s" % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info("Initializing PyTorch distributed" ) torch.distributed.init_process_group( init_method="env://" , backend="nccl" , ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): """simple docstring""" np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
620
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __lowerCamelCase ( UpperCamelCase__=None ): """simple docstring""" if subparsers is not None: _UpperCAmelCase = subparsers.add_parser("test" ) else: _UpperCAmelCase = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=UpperCamelCase__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=UpperCamelCase__ ) return parser def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: _UpperCAmelCase = script_name else: _UpperCAmelCase = f"--config_file={args.config_file} {script_name}" _UpperCAmelCase = ["accelerate-launch"] + test_args.split() _UpperCAmelCase = execute_subprocess_async(UpperCamelCase__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = test_command_parser() _UpperCAmelCase = parser.parse_args() test_command(UpperCamelCase__ ) if __name__ == "__main__": main()
657
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase : Dict = {"""configuration_focalnet""": ["""FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FocalNetConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ """FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """FocalNetForImageClassification""", """FocalNetForMaskedImageModeling""", """FocalNetBackbone""", """FocalNetModel""", """FocalNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys lowercase : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" return 10 - x * x def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) >= 0: raise ValueError("Wrong space!" ) _UpperCAmelCase = a while (b - a) >= 0.01: # Find middle point _UpperCAmelCase = (a + b) / 2 # Check if middle point is root if equation(UpperCamelCase__ ) == 0.0: break # Decide the side to repeat the steps if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) < 0: _UpperCAmelCase = c else: _UpperCAmelCase = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
657
0
'''simple docstring''' import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class _lowerCamelCase ( snake_case_ , snake_case_ ): '''simple docstring''' __lowercase : Optional[int] = 1 @register_to_config def __init__( self , __lowercase=2_000 , __lowercase=0.1 , __lowercase=20 , __lowercase=1E-3 ): """simple docstring""" __A : Tuple = None __A : Optional[Any] = None __A : Union[str, Any] = None def snake_case__ ( self , __lowercase , __lowercase = None ): """simple docstring""" __A : Union[str, Any] = torch.linspace(1 , self.config.sampling_eps , a_ , device=a_ ) def snake_case__ ( self , __lowercase , __lowercase , __lowercase , __lowercase=None ): """simple docstring""" if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __A : Any = ( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __A : str = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __A : Any = std.flatten() while len(std.shape ) < len(score.shape ): __A : Union[str, Any] = std.unsqueeze(-1 ) __A : Any = -score / std # compute __A : int = -1.0 / len(self.timesteps ) __A : Dict = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __A : List[str] = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __A : List[Any] = beta_t.unsqueeze(-1 ) __A : Dict = -0.5 * beta_t * x __A : Optional[Any] = torch.sqrt(a_ ) __A : Union[str, Any] = drift - diffusion**2 * score __A : List[Any] = x + drift * dt # add noise __A : Union[str, Any] = randn_tensor(x.shape , layout=x.layout , generator=a_ , device=x.device , dtype=x.dtype ) __A : Dict = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
365
"""simple docstring""" from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): lowercase_ : Tuple = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self , a_ , a_ , a_ = None , a_ = 50257 , a_ = 1024 , a_ = 768 , a_ = 12 , a_ = 12 , a_ = None , a_ = "gelu_new" , a_ = 0.1 , a_ = 0.1 , a_ = 0.1 , a_ = 1e-5 , a_ = 0.02 , a_ = True , a_ = True , a_ = False , a_ = False , ) -> List[str]: super().__init__() _UpperCAmelCase = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f"`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and" f" `n_embd`: {n_embd} are not equal." ) _UpperCAmelCase = prefix_inner_dim _UpperCAmelCase = prefix_hidden_dim _UpperCAmelCase = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) _UpperCAmelCase = ( nn.Linear(self.prefix_hidden_dim , a_ ) if self.prefix_hidden_dim is not None else nn.Identity() ) _UpperCAmelCase = GPTaConfig( vocab_size=a_ , n_positions=a_ , n_embd=a_ , n_layer=a_ , n_head=a_ , n_inner=a_ , activation_function=a_ , resid_pdrop=a_ , embd_pdrop=a_ , attn_pdrop=a_ , layer_norm_epsilon=a_ , initializer_range=a_ , scale_attn_weights=a_ , use_cache=a_ , scale_attn_by_inverse_layer_idx=a_ , reorder_and_upcast_attn=a_ , ) _UpperCAmelCase = GPTaLMHeadModel(a_ ) def _a ( self , a_ , a_ , a_ = None , a_ = None , ) -> Tuple: _UpperCAmelCase = self.transformer.transformer.wte(a_ ) _UpperCAmelCase = self.encode_prefix(a_ ) _UpperCAmelCase = self.decode_prefix(a_ ) _UpperCAmelCase = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: _UpperCAmelCase = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) _UpperCAmelCase = torch.cat((dummy_token, input_ids) , dim=1 ) _UpperCAmelCase = self.transformer(inputs_embeds=a_ , labels=a_ , attention_mask=a_ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def _a ( self , a_ , a_ ) -> torch.Tensor: return torch.zeros(a_ , self.prefix_length , dtype=torch.intaa , device=a_ ) def _a ( self , a_ ) -> Union[str, Any]: return self.encode_prefix(a_ ) @torch.no_grad() def _a ( self , a_ , a_ , a_ ) -> Union[str, Any]: _UpperCAmelCase = torch.split(a_ , 1 , dim=0 ) _UpperCAmelCase = [] _UpperCAmelCase = [] for feature in features: _UpperCAmelCase = self.decode_prefix(feature.to(a_ ) ) # back to the clip feature # Only support beam search for now _UpperCAmelCase , _UpperCAmelCase = self.generate_beam( input_embeds=a_ , device=a_ , eos_token_id=a_ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) _UpperCAmelCase = torch.stack(a_ ) _UpperCAmelCase = torch.stack(a_ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def _a ( self , a_=None , a_=None , a_=None , a_ = 5 , a_ = 67 , a_ = 1.0 , a_ = None , ) -> Optional[Any]: _UpperCAmelCase = eos_token_id _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = torch.ones(a_ , device=a_ , dtype=torch.int ) _UpperCAmelCase = torch.zeros(a_ , device=a_ , dtype=torch.bool ) if input_embeds is not None: _UpperCAmelCase = input_embeds else: _UpperCAmelCase = self.transformer.transformer.wte(a_ ) for i in range(a_ ): _UpperCAmelCase = self.transformer(inputs_embeds=a_ ) _UpperCAmelCase = outputs.logits _UpperCAmelCase = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) _UpperCAmelCase = logits.softmax(-1 ).log() if scores is None: _UpperCAmelCase , _UpperCAmelCase = logits.topk(a_ , -1 ) _UpperCAmelCase = generated.expand(a_ , *generated.shape[1:] ) _UpperCAmelCase , _UpperCAmelCase = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: _UpperCAmelCase = next_tokens else: _UpperCAmelCase = tokens.expand(a_ , *tokens.shape[1:] ) _UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) else: _UpperCAmelCase = -float(np.inf ) _UpperCAmelCase = 0 _UpperCAmelCase = scores[:, None] + logits seq_lengths[~is_stopped] += 1 _UpperCAmelCase = scores_sum / seq_lengths[:, None] _UpperCAmelCase , _UpperCAmelCase = scores_sum_average.view(-1 ).topk(a_ , -1 ) _UpperCAmelCase = next_tokens // scores_sum.shape[1] _UpperCAmelCase = seq_lengths[next_tokens_source] _UpperCAmelCase = next_tokens % scores_sum.shape[1] _UpperCAmelCase = next_tokens.unsqueeze(1 ) _UpperCAmelCase = tokens[next_tokens_source] _UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) _UpperCAmelCase = generated[next_tokens_source] _UpperCAmelCase = scores_sum_average * seq_lengths _UpperCAmelCase = is_stopped[next_tokens_source] _UpperCAmelCase = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) _UpperCAmelCase = torch.cat((generated, next_token_embed) , dim=1 ) _UpperCAmelCase = is_stopped + next_tokens.eq(a_ ).squeeze() if is_stopped.all(): break _UpperCAmelCase = scores / seq_lengths _UpperCAmelCase = scores.argsort(descending=a_ ) # tokens tensors are already padded to max_seq_length _UpperCAmelCase = [tokens[i] for i in order] _UpperCAmelCase = torch.stack(a_ , dim=0 ) _UpperCAmelCase = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
657
0
'''simple docstring''' import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() _lowercase : int = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) _lowercase : List[Any] = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", F"""encoder.layers.{i}.self_attn.out_proj.weight""") ) rename_keys.append( (F"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", F"""encoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.weight""", F"""encoder.layers.{i}.fc1.weight""")) rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.bias""", F"""encoder.layers.{i}.fc1.bias""")) rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.weight""", F"""encoder.layers.{i}.fc2.weight""")) rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.bias""", F"""encoder.layers.{i}.fc2.bias""")) rename_keys.append( (F"""transformer.encoder.layers.{i}.norm1.weight""", F"""encoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.norm1.bias""", F"""encoder.layers.{i}.self_attn_layer_norm.bias""")) rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.weight""", F"""encoder.layers.{i}.final_layer_norm.weight""")) rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.bias""", F"""encoder.layers.{i}.final_layer_norm.bias""")) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (F"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", F"""decoder.layers.{i}.self_attn.out_proj.weight""") ) rename_keys.append( (F"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", F"""decoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append( ( F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""", F"""decoder.layers.{i}.encoder_attn.out_proj.weight""", ) ) rename_keys.append( ( F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""", F"""decoder.layers.{i}.encoder_attn.out_proj.bias""", ) ) rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.weight""", F"""decoder.layers.{i}.fc1.weight""")) rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.bias""", F"""decoder.layers.{i}.fc1.bias""")) rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.weight""", F"""decoder.layers.{i}.fc2.weight""")) rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.bias""", F"""decoder.layers.{i}.fc2.bias""")) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm1.weight""", F"""decoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm1.bias""", F"""decoder.layers.{i}.self_attn_layer_norm.bias""")) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm2.weight""", F"""decoder.layers.{i}.encoder_attn_layer_norm.weight""") ) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm2.bias""", F"""decoder.layers.{i}.encoder_attn_layer_norm.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.weight""", F"""decoder.layers.{i}.final_layer_norm.weight""")) rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.bias""", F"""decoder.layers.{i}.final_layer_norm.bias""")) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("""input_proj.weight""", """input_projection.weight"""), ("""input_proj.bias""", """input_projection.bias"""), ("""query_embed.weight""", """query_position_embeddings.weight"""), ("""transformer.encoder.norm.weight""", """encoder.layernorm.weight"""), ("""transformer.encoder.norm.bias""", """encoder.layernorm.bias"""), ("""transformer.decoder.norm.weight""", """decoder.layernorm.weight"""), ("""transformer.decoder.norm.bias""", """decoder.layernorm.bias"""), ("""class_embed.weight""", """class_labels_classifier.weight"""), ("""class_embed.bias""", """class_labels_classifier.bias"""), ("""bbox_embed.layers.0.weight""", """bbox_predictor.layers.0.weight"""), ("""bbox_embed.layers.0.bias""", """bbox_predictor.layers.0.bias"""), ("""bbox_embed.layers.1.weight""", """bbox_predictor.layers.1.weight"""), ("""bbox_embed.layers.1.bias""", """bbox_predictor.layers.1.bias"""), ("""bbox_embed.layers.2.weight""", """bbox_predictor.layers.2.weight"""), ("""bbox_embed.layers.2.bias""", """bbox_predictor.layers.2.bias"""), ] ) def lowerCamelCase__ ( A : Tuple , A : str , A : Optional[int] ): '''simple docstring''' UpperCAmelCase = state_dict.pop(UpperCamelCase__ ) UpperCAmelCase = val def lowerCamelCase__ ( A : List[Any] ): '''simple docstring''' UpperCAmelCase = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: UpperCAmelCase = key.replace('''backbone.0.body''' , '''backbone.conv_encoder.model''' ) UpperCAmelCase = value else: UpperCAmelCase = value return new_state_dict def lowerCamelCase__ ( A : Any ): '''simple docstring''' UpperCAmelCase = '''''' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) UpperCAmelCase = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight""" ) UpperCAmelCase = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase = in_proj_weight[:2_56, :] UpperCAmelCase = in_proj_bias[:2_56] UpperCAmelCase = in_proj_weight[2_56:5_12, :] UpperCAmelCase = in_proj_bias[2_56:5_12] UpperCAmelCase = in_proj_weight[-2_56:, :] UpperCAmelCase = in_proj_bias[-2_56:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention UpperCAmelCase = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight""" ) UpperCAmelCase = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase = in_proj_weight[:2_56, :] UpperCAmelCase = in_proj_bias[:2_56] UpperCAmelCase = in_proj_weight[2_56:5_12, :] UpperCAmelCase = in_proj_bias[2_56:5_12] UpperCAmelCase = in_proj_weight[-2_56:, :] UpperCAmelCase = in_proj_bias[-2_56:] # read in weights + bias of input projection layer of cross-attention UpperCAmelCase = state_dict.pop( f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight""" ) UpperCAmelCase = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) of cross-attention to the state dict UpperCAmelCase = in_proj_weight_cross_attn[:2_56, :] UpperCAmelCase = in_proj_bias_cross_attn[:2_56] UpperCAmelCase = in_proj_weight_cross_attn[2_56:5_12, :] UpperCAmelCase = in_proj_bias_cross_attn[2_56:5_12] UpperCAmelCase = in_proj_weight_cross_attn[-2_56:, :] UpperCAmelCase = in_proj_bias_cross_attn[-2_56:] def lowerCamelCase__ ( A : Tuple , A : int ): '''simple docstring''' UpperCAmelCase , UpperCAmelCase = image.size UpperCAmelCase = max(UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase = 8_00 if '''detection''' in checkpoint_url else 10_00 UpperCAmelCase = target_max_size / current_max_size UpperCAmelCase = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def lowerCamelCase__ ( A : Tuple ): '''simple docstring''' UpperCAmelCase = F.to_tensor(UpperCamelCase__ ) UpperCAmelCase = F.normalize(UpperCamelCase__ , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def lowerCamelCase__ ( A : Any , A : Tuple , A : Union[str, Any] ): '''simple docstring''' logger.info('''Converting model...''' ) # load original state dict UpperCAmelCase = torch.hub.load_state_dict_from_url(UpperCamelCase__ , map_location='''cpu''' ) # rename keys for src, dest in rename_keys: rename_key(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase = rename_backbone_keys(UpperCamelCase__ ) # query, key and value matrices need special treatment read_in_q_k_v(UpperCamelCase__ ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them UpperCAmelCase = '''model.''' for key in state_dict.copy().keys(): if not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ): UpperCAmelCase = state_dict.pop(UpperCamelCase__ ) UpperCAmelCase = val # create HuggingFace model and load state dict UpperCAmelCase = TableTransformerConfig( backbone='''resnet18''' , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: UpperCAmelCase = 15 UpperCAmelCase = 2 UpperCAmelCase = {0: '''table''', 1: '''table rotated'''} UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} else: UpperCAmelCase = 1_25 UpperCAmelCase = 6 UpperCAmelCase = { 0: '''table''', 1: '''table column''', 2: '''table row''', 3: '''table column header''', 4: '''table projected row header''', 5: '''table spanning cell''', } UpperCAmelCase = idalabel UpperCAmelCase = {v: k for k, v in idalabel.items()} UpperCAmelCase = DetrImageProcessor( format='''coco_detection''' , max_size=8_00 if '''detection''' in checkpoint_url else 10_00 ) UpperCAmelCase = TableTransformerForObjectDetection(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # verify our conversion UpperCAmelCase = '''example_pdf.png''' if '''detection''' in checkpoint_url else '''example_table.png''' UpperCAmelCase = hf_hub_download(repo_id='''nielsr/example-pdf''' , repo_type='''dataset''' , filename=UpperCamelCase__ ) UpperCAmelCase = Image.open(UpperCamelCase__ ).convert('''RGB''' ) UpperCAmelCase = normalize(resize(UpperCamelCase__ , UpperCamelCase__ ) ).unsqueeze(0 ) UpperCAmelCase = model(UpperCamelCase__ ) if "detection" in checkpoint_url: UpperCAmelCase = (1, 15, 3) UpperCAmelCase = torch.tensor( [[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] ) UpperCAmelCase = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] ) else: UpperCAmelCase = (1, 1_25, 7) UpperCAmelCase = torch.tensor( [[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] ) UpperCAmelCase = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , UpperCamelCase__ , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , UpperCamelCase__ , atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) image_processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: # Push model to HF hub logger.info('''Pushing model to the hub...''' ) UpperCAmelCase = ( '''microsoft/table-transformer-detection''' if '''detection''' in checkpoint_url else '''microsoft/table-transformer-structure-recognition''' ) model.push_to_hub(UpperCamelCase__ ) image_processor.push_to_hub(UpperCamelCase__ ) if __name__ == "__main__": _lowercase : Optional[int] = argparse.ArgumentParser() parser.add_argument( """--checkpoint_url""", default="""https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth""", type=str, choices=[ """https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth""", """https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth""", ], help="""URL of the Table Transformer checkpoint you\'d like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) _lowercase : int = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
210
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable __magic_name__ = {'''configuration_gpt_neox''': ['''GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXConfig''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''GPTNeoXTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXForCausalLM''', '''GPTNeoXForQuestionAnswering''', '''GPTNeoXForSequenceClassification''', '''GPTNeoXForTokenClassification''', '''GPTNeoXLayer''', '''GPTNeoXModel''', '''GPTNeoXPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
657
0
def __a ( __UpperCAmelCase : int ) -> Any: """simple docstring""" return 10 - x * x def __a ( __UpperCAmelCase : List[str] , __UpperCAmelCase : Dict ) -> int: """simple docstring""" if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) >= 0: raise ValueError("Wrong space!" ) lowerCamelCase_ : Dict = a while (b - a) >= 0.0_1: # Find middle point lowerCamelCase_ : Any = (a + b) / 2 # Check if middle point is root if equation(UpperCamelCase__ ) == 0.0: break # Decide the side to repeat the steps if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) < 0: lowerCamelCase_ : str = c else: lowerCamelCase_ : List[str] = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
488
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''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 _lowerCAmelCase ( lowerCamelCase ): lowercase_ : Union[str, Any] = '''convbert''' def __init__( self , a_=30522 , 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_=768 , a_=2 , a_=9 , a_=1 , a_=None , **a_ , ) -> Tuple: super().__init__( pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ , ) _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = embedding_size _UpperCAmelCase = head_ratio _UpperCAmelCase = conv_kernel_size _UpperCAmelCase = num_groups _UpperCAmelCase = classifier_dropout class _lowerCAmelCase ( lowerCamelCase ): @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _UpperCAmelCase = {0: "batch", 1: "choice", 2: "sequence"} else: _UpperCAmelCase = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
657
0
import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """facebook/encodec_24khz""": """https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json""", """facebook/encodec_48khz""": """https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Dict = '''encodec''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=[1.5, 3.0, 6.0, 12.0, 24.0] , UpperCAmelCase_ : Any=2_4000 , UpperCAmelCase_ : Dict=1 , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : int=128 , UpperCAmelCase_ : List[str]=32 , UpperCAmelCase_ : int=1 , UpperCAmelCase_ : int=[8, 5, 4, 2] , UpperCAmelCase_ : Optional[Any]="weight_norm" , UpperCAmelCase_ : str=7 , UpperCAmelCase_ : Dict=7 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=2 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Any="reflect" , UpperCAmelCase_ : List[Any]=2 , UpperCAmelCase_ : str=2 , UpperCAmelCase_ : Optional[int]=1.0 , UpperCAmelCase_ : Dict=1024 , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : int=True , **UpperCAmelCase_ : Dict , ): SCREAMING_SNAKE_CASE : List[str] = target_bandwidths SCREAMING_SNAKE_CASE : Dict = sampling_rate SCREAMING_SNAKE_CASE : Any = audio_channels SCREAMING_SNAKE_CASE : Optional[Any] = normalize SCREAMING_SNAKE_CASE : Tuple = chunk_length_s SCREAMING_SNAKE_CASE : int = overlap SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : List[Any] = num_filters SCREAMING_SNAKE_CASE : Dict = num_residual_layers SCREAMING_SNAKE_CASE : Tuple = upsampling_ratios SCREAMING_SNAKE_CASE : Any = norm_type SCREAMING_SNAKE_CASE : Dict = kernel_size SCREAMING_SNAKE_CASE : Tuple = last_kernel_size SCREAMING_SNAKE_CASE : Dict = residual_kernel_size SCREAMING_SNAKE_CASE : Any = dilation_growth_rate SCREAMING_SNAKE_CASE : List[Any] = use_causal_conv SCREAMING_SNAKE_CASE : Dict = pad_mode SCREAMING_SNAKE_CASE : List[str] = compress SCREAMING_SNAKE_CASE : List[str] = num_lstm_layers SCREAMING_SNAKE_CASE : Tuple = trim_right_ratio SCREAMING_SNAKE_CASE : Any = codebook_size SCREAMING_SNAKE_CASE : Optional[int] = codebook_dim if codebook_dim is not None else hidden_size SCREAMING_SNAKE_CASE : int = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( f'''self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}''' ) super().__init__(**a_ ) @property def _A ( self : Dict ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def _A ( self : int ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[Any] = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def _A ( self : Tuple ): return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
62
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" return "".join([hex(UpperCamelCase__ )[2:].zfill(2 ).upper() for byte in list(UpperCamelCase__ )] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if (len(UpperCamelCase__ ) % 2) != 0: raise ValueError( "Base16 encoded data is invalid:\nData does not have an even number of hex digits." ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(UpperCamelCase__ ) <= set("0123456789ABCDEF" ): raise ValueError( "Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters." ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(UpperCamelCase__ ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
657
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase : int = {'configuration_mra': ['MRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MraConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = [ 'MRA_PRETRAINED_MODEL_ARCHIVE_LIST', 'MraForMaskedLM', 'MraForMultipleChoice', 'MraForQuestionAnswering', 'MraForSequenceClassification', 'MraForTokenClassification', 'MraLayer', 'MraModel', 'MraPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mra import ( MRA_PRETRAINED_MODEL_ARCHIVE_LIST, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraLayer, MraModel, MraPreTrainedModel, ) else: import sys lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
170
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" try: _UpperCAmelCase = float(UpperCamelCase__ ) except ValueError: raise ValueError("Please enter a valid number" ) _UpperCAmelCase = decimal - int(UpperCamelCase__ ) if fractional_part == 0: return int(UpperCamelCase__ ), 1 else: _UpperCAmelCase = len(str(UpperCamelCase__ ).split("." )[1] ) _UpperCAmelCase = int(decimal * (10**number_of_frac_digits) ) _UpperCAmelCase = 10**number_of_frac_digits _UpperCAmelCase , _UpperCAmelCase = denominator, numerator while True: _UpperCAmelCase = dividend % divisor if remainder == 0: break _UpperCAmelCase , _UpperCAmelCase = divisor, remainder _UpperCAmelCase , _UpperCAmelCase = numerator / divisor, denominator / divisor return int(UpperCamelCase__ ), int(UpperCamelCase__ ) if __name__ == "__main__": print(f'''{decimal_to_fraction(2) = }''') print(f'''{decimal_to_fraction(89.0) = }''') print(f'''{decimal_to_fraction("67") = }''') print(f'''{decimal_to_fraction("45.0") = }''') print(f'''{decimal_to_fraction(1.5) = }''') print(f'''{decimal_to_fraction("6.25") = }''') print(f'''{decimal_to_fraction("78td") = }''')
657
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase : List[Any] = { '''configuration_altclip''': [ '''ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''AltCLIPConfig''', '''AltCLIPTextConfig''', '''AltCLIPVisionConfig''', ], '''processing_altclip''': ['''AltCLIPProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Union[str, Any] = [ '''ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''AltCLIPPreTrainedModel''', '''AltCLIPModel''', '''AltCLIPTextModel''', '''AltCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys lowercase : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
568
"""simple docstring""" # Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, nicht wahr?", } # BLUE scores as follows: # "pair": [fairseq, transformers] _UpperCAmelCase = { "wmt16-en-de-dist-12-1": [28.3, 27.52], "wmt16-en-de-dist-6-1": [27.4, 27.11], "wmt16-en-de-12-1": [26.9, 25.75], } _UpperCAmelCase = f"{src_lang}-{tgt_lang}" _UpperCAmelCase = f"\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"allenai/{model_name}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel | fairseq | transformers\n-------|---------|----------\n{model_name} | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don't use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n year={{2020}},\n eprint={{2006.10369}},\n archivePrefix={{arXiv}},\n primaryClass={{cs.CL}}\n}}\n```\n\n" model_card_dir.mkdir(parents=UpperCamelCase__ , exist_ok=UpperCamelCase__ ) _UpperCAmelCase = os.path.join(UpperCamelCase__ , "README.md" ) print(f"Generating {path}" ) with open(UpperCamelCase__ , "w" , encoding="utf-8" ) as f: f.write(UpperCamelCase__ ) # make sure we are under the root of the project __magic_name__ = Path(__file__).resolve().parent.parent.parent __magic_name__ = repo_dir / '''model_cards''' for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: __magic_name__ = model_cards_dir / '''allenai''' / model_name write_model_card(model_card_dir, src_lang='''en''', tgt_lang='''de''', model_name=model_name)
657
0
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType 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, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase__ = logging.get_logger(__name__) def _a ( a :Optional[int] ) -> Optional[int]: if isinstance(UpperCamelCase__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(UpperCamelCase__ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(UpperCamelCase__ ): return [[videos]] raise ValueError(F"""Could not make batched video from {videos}""" ) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = ['''pixel_values'''] def __init__( self : Union[str, Any] , __UpperCAmelCase : Optional[Any] = True , __UpperCAmelCase : int = None , __UpperCAmelCase : Union[str, Any] = PILImageResampling.BILINEAR , __UpperCAmelCase : Dict = True , __UpperCAmelCase : Any = None , __UpperCAmelCase : Tuple = True , __UpperCAmelCase : Dict = 1 / 255 , __UpperCAmelCase : Tuple = True , __UpperCAmelCase : Optional[int] = True , __UpperCAmelCase : Union[str, Any] = None , __UpperCAmelCase : int = None , **__UpperCAmelCase : int , ) ->None: """simple docstring""" super().__init__(**a_ ) a = size if size is not None else {'''shortest_edge''': 256} a = get_size_dict(a_ , default_to_square=a_ ) a = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} a = get_size_dict(a_ , param_name='''crop_size''' ) a = do_resize a = size a = do_center_crop a = crop_size a = resample a = do_rescale a = rescale_factor a = offset a = do_normalize a = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN a = image_std if image_std is not None else IMAGENET_STANDARD_STD def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : Tuple = PILImageResampling.BILINEAR , __UpperCAmelCase : List[Any] = None , **__UpperCAmelCase : List[str] , ) ->np.ndarray: """simple docstring""" a = get_size_dict(a_ , default_to_square=a_ ) if "shortest_edge" in size: a = get_resize_output_image_size(a_ , size['''shortest_edge'''] , default_to_square=a_ ) elif "height" in size and "width" in size: a = (size['''height'''], size['''width''']) else: raise ValueError(F"""Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) return resize(a_ , size=a_ , resample=a_ , data_format=a_ , **a_ ) def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int] = None , **__UpperCAmelCase : Dict , ) ->np.ndarray: """simple docstring""" a = get_size_dict(a_ ) if "height" not in size or "width" not in size: raise ValueError(F"""Size must have 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(a_ , size=(size['''height'''], size['''width''']) , data_format=a_ , **a_ ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : List[Any] = True , __UpperCAmelCase : List[Any] = None , **__UpperCAmelCase : Optional[Any] , ) ->Union[str, Any]: """simple docstring""" a = image.astype(np.floataa ) if offset: a = image - (scale / 2) return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : int , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Any = None , **__UpperCAmelCase : Union[str, Any] , ) ->np.ndarray: """simple docstring""" return normalize(a_ , mean=a_ , std=a_ , data_format=a_ , **a_ ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[Any] = None , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Tuple = None , __UpperCAmelCase : Union[str, Any] = None , __UpperCAmelCase : str = None , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Optional[Any] = None , __UpperCAmelCase : Dict = None , __UpperCAmelCase : Union[str, Any] = None , __UpperCAmelCase : Tuple = None , __UpperCAmelCase : str = None , __UpperCAmelCase : Dict = ChannelDimension.FIRST , ) ->np.ndarray: """simple docstring""" if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_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.''' ) if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''' ) # All transformations expect numpy arrays. a = to_numpy_array(a_ ) if do_resize: a = self.resize(image=a_ , size=a_ , resample=a_ ) if do_center_crop: a = self.center_crop(a_ , size=a_ ) if do_rescale: a = self.rescale(image=a_ , scale=a_ , offset=a_ ) if do_normalize: a = self.normalize(image=a_ , mean=a_ , std=a_ ) a = to_channel_dimension_format(a_ , a_ ) return image def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Tuple = None , __UpperCAmelCase : Dict = None , __UpperCAmelCase : Any = None , __UpperCAmelCase : Any = None , __UpperCAmelCase : Dict = None , __UpperCAmelCase : int = None , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Tuple = None , __UpperCAmelCase : Any = None , __UpperCAmelCase : Any = None , __UpperCAmelCase : Any = None , __UpperCAmelCase : Optional[Any] = None , __UpperCAmelCase : List[Any] = ChannelDimension.FIRST , **__UpperCAmelCase : str , ) ->PIL.Image.Image: """simple docstring""" a = do_resize if do_resize is not None else self.do_resize a = resample if resample is not None else self.resample a = do_center_crop if do_center_crop is not None else self.do_center_crop a = do_rescale if do_rescale is not None else self.do_rescale a = rescale_factor if rescale_factor is not None else self.rescale_factor a = offset if offset is not None else self.offset a = do_normalize if do_normalize is not None else self.do_normalize a = image_mean if image_mean is not None else self.image_mean a = image_std if image_std is not None else self.image_std a = size if size is not None else self.size a = get_size_dict(a_ , default_to_square=a_ ) a = crop_size if crop_size is not None else self.crop_size a = get_size_dict(a_ , param_name='''crop_size''' ) if not valid_images(a_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) a = make_batched(a_ ) a = [ [ self._preprocess_image( image=a_ , do_resize=a_ , size=a_ , resample=a_ , do_center_crop=a_ , crop_size=a_ , do_rescale=a_ , rescale_factor=a_ , offset=a_ , do_normalize=a_ , image_mean=a_ , image_std=a_ , data_format=a_ , ) for img in video ] for video in videos ] a = {'''pixel_values''': videos} return BatchFeature(data=a_ , tensor_type=a_ )
117
"""simple docstring""" from ..utils import DummyObject, requires_backends class _lowerCAmelCase ( metaclass=lowerCamelCase ): lowercase_ : Dict = ['''torch''', '''torchsde'''] def __init__( self , *a_ , **a_ ) -> Optional[int]: requires_backends(self , ["torch", "torchsde"] ) @classmethod def _a ( cls , *a_ , **a_ ) -> Optional[Any]: requires_backends(cls , ["torch", "torchsde"] ) @classmethod def _a ( cls , *a_ , **a_ ) -> List[Any]: requires_backends(cls , ["torch", "torchsde"] )
657
0
import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml A = logging.get_logger(__name__) def __UpperCAmelCase ( __A , __A ) -> List[str]: '''simple docstring''' def run_func(__A ): @wraps(UpperCamelCase__ ) def run_in_eager_mode(*__A , **__A ): return func(*UpperCamelCase__ , **UpperCamelCase__ ) @wraps(UpperCamelCase__ ) @tf.function(experimental_compile=UpperCamelCase__ ) def run_in_graph_mode(*__A , **__A ): return func(*UpperCamelCase__ , **UpperCamelCase__ ) if do_eager_mode is True: if use_xla is not False: raise ValueError( "Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`." ) return run_in_eager_mode else: return run_in_graph_mode return run_func def __UpperCAmelCase ( __A , __A , __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = random.Random() UpperCAmelCase__ = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(UpperCamelCase__ , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class lowercase__ ( __SCREAMING_SNAKE_CASE ): A__= 42 A__= 42 A__= "TensorFlow" @property def _UpperCAmelCase ( self : List[Any] ): """simple docstring""" return tf.__version__ def _UpperCAmelCase ( self : List[str] , _lowercase : Union[str, Any] , _lowercase : List[str] , _lowercase : Optional[int] ): """simple docstring""" UpperCAmelCase__ = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) UpperCAmelCase__ = self._prepare_inference_func(a_ , a_ , a_ ) return self._measure_speed(_inference ) def _UpperCAmelCase ( self : Optional[int] , _lowercase : Any , _lowercase : Optional[int] , _lowercase : Union[str, Any] ): """simple docstring""" UpperCAmelCase__ = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) UpperCAmelCase__ = self._prepare_train_func(a_ , a_ , a_ ) return self._measure_speed(_train ) def _UpperCAmelCase ( self : int , _lowercase : List[Any] , _lowercase : Optional[int] , _lowercase : Union[str, Any] ): """simple docstring""" if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , a_ ) UpperCAmelCase__ = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) UpperCAmelCase__ = self._prepare_inference_func(a_ , a_ , a_ ) return self._measure_memory(_inference ) def _UpperCAmelCase ( self : Dict , _lowercase : Optional[Any] , _lowercase : List[str] , _lowercase : Optional[Any] ): """simple docstring""" if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , a_ ) UpperCAmelCase__ = self.args.strategy if strategy is None: raise ValueError("A device strategy has to be initialized before using TensorFlow." ) UpperCAmelCase__ = self._prepare_train_func(a_ , a_ , a_ ) return self._measure_memory(_train ) def _UpperCAmelCase ( self : Tuple , _lowercase : List[str] , _lowercase : str , _lowercase : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError("Mixed precision is currently not supported." ) UpperCAmelCase__ = ( hasattr(a_ , "architectures" ) and isinstance(config.architectures , a_ ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: UpperCAmelCase__ = "TF" + config.architectures[0] # prepend 'TF' for tensorflow model UpperCAmelCase__ = __import__("transformers" , fromlist=[model_class] ) UpperCAmelCase__ = getattr(a_ , a_ ) UpperCAmelCase__ = model_cls(a_ ) except ImportError: raise ImportError( F"""{model_class} does not exist. If you just want to test the pretrained model, you might want to""" " set `--only_pretrain_model` or `args.only_pretrain_model=True`." ) else: UpperCAmelCase__ = TF_MODEL_MAPPING[config.__class__](a_ ) # encoder-decoder has vocab size saved differently UpperCAmelCase__ = config.vocab_size if hasattr(a_ , "vocab_size" ) else config.encoder.vocab_size UpperCAmelCase__ = random_input_ids(a_ , a_ , a_ ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(a_ , decoder_input_ids=a_ , training=a_ ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(a_ , training=a_ ) UpperCAmelCase__ = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def _UpperCAmelCase ( self : int , _lowercase : List[str] , _lowercase : Tuple , _lowercase : Optional[int] ): """simple docstring""" UpperCAmelCase__ = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError("Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`." ) if self.args.fpaa: raise NotImplementedError("Mixed precision is currently not supported." ) UpperCAmelCase__ = ( hasattr(a_ , "architectures" ) and isinstance(config.architectures , a_ ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: UpperCAmelCase__ = "TF" + config.architectures[0] # prepend 'TF' for tensorflow model UpperCAmelCase__ = __import__("transformers" , fromlist=[model_class] ) UpperCAmelCase__ = getattr(a_ , a_ ) UpperCAmelCase__ = model_cls(a_ ) except ImportError: raise ImportError( F"""{model_class} does not exist. If you just want to test the pretrained model, you might want to""" " set `--only_pretrain_model` or `args.only_pretrain_model=True`." ) else: UpperCAmelCase__ = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](a_ ) # encoder-decoder has vocab size saved differently UpperCAmelCase__ = config.vocab_size if hasattr(a_ , "vocab_size" ) else config.encoder.vocab_size UpperCAmelCase__ = random_input_ids(a_ , a_ , a_ ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): UpperCAmelCase__ = model(a_ , decoder_input_ids=a_ , labels=a_ , training=a_ )[0] UpperCAmelCase__ = tf.gradients(a_ , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): UpperCAmelCase__ = model(a_ , labels=a_ , training=a_ )[0] UpperCAmelCase__ = tf.gradients(a_ , model.trainable_variables ) return gradients UpperCAmelCase__ = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def _UpperCAmelCase ( self : Union[str, Any] , _lowercase : Union[str, Any] ): """simple docstring""" with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info("Do inference on TPU. Running model 5 times to stabilize compilation" ) timeit.repeat(a_ , repeat=1 , number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average UpperCAmelCase__ = timeit.repeat( a_ , repeat=self.args.repeat , number=10 , ) return min(a_ ) / 1_0.0 except ResourceExhaustedError as e: self.print_fn(F"""Doesn't fit on GPU. {e}""" ) def _UpperCAmelCase ( self : List[str] , _lowercase : Optional[int] ): """simple docstring""" logger.info( "Note that TensorFlow allocates more memory than " "it might need to speed up computation. " "The memory reported here corresponds to the memory " "reported by `nvidia-smi`, which can vary depending " "on total available memory on the GPU that is used." ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( "`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory" " consumption line by line." ) UpperCAmelCase__ = start_memory_tracing("transformers" ) if self.args.is_tpu: # tpu raise NotImplementedError( "Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking" " with `args.memory=False`" ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( "py3nvml not installed, we won't log GPU memory usage. " "Install py3nvml (pip install py3nvml) to log information about GPU." ) UpperCAmelCase__ = "N/A" else: logger.info( "Measuring total GPU usage on GPU device. Make sure to not have additional processes" " running on the same GPU." ) # init nvml nvml.nvmlInit() func() UpperCAmelCase__ = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) UpperCAmelCase__ = nvml.nvmlDeviceGetMemoryInfo(a_ ) UpperCAmelCase__ = meminfo.used UpperCAmelCase__ = Memory(a_ ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( "When enabling line by line tracing, the max peak memory for CPU is inaccurate in" " TensorFlow." ) UpperCAmelCase__ = None else: UpperCAmelCase__ = measure_peak_memory_cpu(a_ ) UpperCAmelCase__ = Memory(a_ ) if isinstance(a_ , a_ ) else memory_bytes if self.args.trace_memory_line_by_line: UpperCAmelCase__ = stop_memory_tracing(a_ ) if memory is None: UpperCAmelCase__ = summary.total else: UpperCAmelCase__ = None return memory, summary except ResourceExhaustedError as e: self.print_fn(F"""Doesn't fit on GPU. {e}""" ) return "N/A", None
475
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __magic_name__ = logging.get_logger(__name__) class _lowerCAmelCase ( lowerCamelCase ): lowercase_ : Optional[Any] = '''upernet''' def __init__( self , a_=None , a_=512 , a_=0.02 , a_=[1, 2, 3, 6] , a_=True , a_=0.4 , a_=384 , a_=256 , a_=1 , a_=False , a_=255 , **a_ , ) -> List[Any]: super().__init__(**a_ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) _UpperCAmelCase = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(a_ , a_ ): _UpperCAmelCase = backbone_config.get("model_type" ) _UpperCAmelCase = CONFIG_MAPPING[backbone_model_type] _UpperCAmelCase = config_class.from_dict(a_ ) _UpperCAmelCase = backbone_config _UpperCAmelCase = hidden_size _UpperCAmelCase = initializer_range _UpperCAmelCase = pool_scales _UpperCAmelCase = use_auxiliary_head _UpperCAmelCase = auxiliary_loss_weight _UpperCAmelCase = auxiliary_in_channels _UpperCAmelCase = auxiliary_channels _UpperCAmelCase = auxiliary_num_convs _UpperCAmelCase = auxiliary_concat_input _UpperCAmelCase = loss_ignore_index def _a ( self ) -> int: _UpperCAmelCase = copy.deepcopy(self.__dict__ ) _UpperCAmelCase = self.backbone_config.to_dict() _UpperCAmelCase = self.__class__.model_type return output
657
0
'''simple docstring''' import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py _a : str = "src/diffusers" _a : Tuple = "." # This is to make sure the diffusers module imported is the one in the repo. _a : Optional[Any] = importlib.util.spec_from_file_location( "diffusers", os.path.join(DIFFUSERS_PATH, "__init__.py"), submodule_search_locations=[DIFFUSERS_PATH], ) _a : List[Any] = spec.loader.load_module() def _lowercase ( lowerCamelCase__ , lowerCamelCase__ ) -> Any: """simple docstring""" return line.startswith(UpperCamelCase__ ) or len(UpperCamelCase__ ) <= 1 or re.search(R"^\s*\)(\s*->.*:|:)\s*$" , UpperCamelCase__ ) is not None def _lowercase ( lowerCamelCase__ ) -> Dict: """simple docstring""" __UpperCAmelCase : List[str] = object_name.split("." ) __UpperCAmelCase : Optional[int] = 0 # First let's find the module where our object lives. __UpperCAmelCase : Union[str, Any] = parts[i] while i < len(UpperCamelCase__ ) and not os.path.isfile(os.path.join(UpperCamelCase__ , f"""{module}.py""" ) ): i += 1 if i < len(UpperCamelCase__ ): __UpperCAmelCase : Union[str, Any] = os.path.join(UpperCamelCase__ , parts[i] ) if i >= len(UpperCamelCase__ ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(UpperCamelCase__ , f"""{module}.py""" ) , "r" , encoding="utf-8" , newline="\n" ) as f: __UpperCAmelCase : Any = f.readlines() # Now let's find the class / func in the code! __UpperCAmelCase : int = "" __UpperCAmelCase : Optional[Any] = 0 for name in parts[i + 1 :]: while ( line_index < len(UpperCamelCase__ ) and re.search(Rf"""^{indent}(class|def)\s+{name}(\(|\:)""" , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(UpperCamelCase__ ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). __UpperCAmelCase : int = line_index while line_index < len(UpperCamelCase__ ) and _should_continue(lines[line_index] , UpperCamelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __UpperCAmelCase : List[str] = lines[start_index:line_index] return "".join(UpperCamelCase__ ) _a : Union[str, Any] = re.compile(R"^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)") _a : Tuple = re.compile(R"^\s*(\S+)->(\S+)(\s+.*|$)") _a : Union[str, Any] = re.compile(R"<FILL\s+[^>]*>") def _lowercase ( lowerCamelCase__ ) -> str: """simple docstring""" __UpperCAmelCase : Optional[Any] = code.split("\n" ) __UpperCAmelCase : Optional[int] = 0 while idx < len(UpperCamelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(UpperCamelCase__ ): return re.search(R"^(\s*)\S" , lines[idx] ).groups()[0] return "" def _lowercase ( lowerCamelCase__ ) -> List[Any]: """simple docstring""" __UpperCAmelCase : Dict = len(get_indent(UpperCamelCase__ ) ) > 0 if has_indent: __UpperCAmelCase : Dict = f"""class Bla:\n{code}""" __UpperCAmelCase : int = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=UpperCamelCase__ ) __UpperCAmelCase : Optional[Any] = black.format_str(UpperCamelCase__ , mode=UpperCamelCase__ ) __UpperCAmelCase , __UpperCAmelCase : int = style_docstrings_in_code(UpperCamelCase__ ) return result[len("class Bla:\n" ) :] if has_indent else result def _lowercase ( lowerCamelCase__ , lowerCamelCase__=False ) -> Union[str, Any]: """simple docstring""" with open(UpperCamelCase__ , "r" , encoding="utf-8" , newline="\n" ) as f: __UpperCAmelCase : Any = f.readlines() __UpperCAmelCase : Optional[int] = [] __UpperCAmelCase : str = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(UpperCamelCase__ ): __UpperCAmelCase : List[Any] = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Dict = search.groups() __UpperCAmelCase : Optional[Any] = find_code_in_diffusers(UpperCamelCase__ ) __UpperCAmelCase : Tuple = get_indent(UpperCamelCase__ ) __UpperCAmelCase : Dict = line_index + 1 if indent == theoretical_indent else line_index + 2 __UpperCAmelCase : Dict = theoretical_indent __UpperCAmelCase : int = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. __UpperCAmelCase : str = True while line_index < len(UpperCamelCase__ ) and should_continue: line_index += 1 if line_index >= len(UpperCamelCase__ ): break __UpperCAmelCase : Optional[int] = lines[line_index] __UpperCAmelCase : Any = _should_continue(UpperCamelCase__ , UpperCamelCase__ ) and re.search(f"""^{indent}# End copy""" , UpperCamelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __UpperCAmelCase : int = lines[start_index:line_index] __UpperCAmelCase : str = "".join(UpperCamelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies __UpperCAmelCase : List[Any] = [line for line in theoretical_code.split("\n" ) if _re_copy_warning.search(UpperCamelCase__ ) is None] __UpperCAmelCase : Union[str, Any] = "\n".join(UpperCamelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(UpperCamelCase__ ) > 0: __UpperCAmelCase : int = replace_pattern.replace("with" , "" ).split("," ) __UpperCAmelCase : Tuple = [_re_replace_pattern.search(UpperCamelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Tuple = pattern.groups() __UpperCAmelCase : Any = re.sub(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if option.strip() == "all-casing": __UpperCAmelCase : Optional[int] = re.sub(obja.lower() , obja.lower() , UpperCamelCase__ ) __UpperCAmelCase : Dict = re.sub(obja.upper() , obja.upper() , UpperCamelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line __UpperCAmelCase : Optional[Any] = blackify(lines[start_index - 1] + theoretical_code ) __UpperCAmelCase : Dict = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: __UpperCAmelCase : List[Any] = lines[:start_index] + [theoretical_code] + lines[line_index:] __UpperCAmelCase : Any = start_index + 1 if overwrite and len(UpperCamelCase__ ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(UpperCamelCase__ , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(UpperCamelCase__ ) return diffs def _lowercase ( lowerCamelCase__ = False ) -> List[str]: """simple docstring""" __UpperCAmelCase : int = glob.glob(os.path.join(UpperCamelCase__ , "**/*.py" ) , recursive=UpperCamelCase__ ) __UpperCAmelCase : str = [] for filename in all_files: __UpperCAmelCase : List[str] = is_copy_consistent(UpperCamelCase__ , UpperCamelCase__ ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(UpperCamelCase__ ) > 0: __UpperCAmelCase : Optional[Any] = "\n".join(UpperCamelCase__ ) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) if __name__ == "__main__": _a : List[Any] = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") _a : int = parser.parse_args() check_copies(args.fix_and_overwrite)
168
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import _LazyModule __magic_name__ = {'''tokenization_tapex''': ['''TapexTokenizer''']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
657
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase__ = { 'configuration_electra': ['ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ElectraConfig', 'ElectraOnnxConfig'], 'tokenization_electra': ['ElectraTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ['ElectraTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ '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: UpperCamelCase__ = [ '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: UpperCamelCase__ = [ '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 UpperCamelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
620
"""simple docstring""" import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase : def __init__( self , a_ , a_=2 , a_=3 , a_=4 , a_=2 , a_=7 , a_=True , a_=True , a_=True , a_=True , a_=99 , a_=36 , a_=3 , a_=4 , a_=37 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=16 , a_=2 , a_=0.02 , a_=6 , a_=6 , a_=3 , a_=4 , a_=None , a_=1000 , ) -> Optional[Any]: _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = text_seq_length _UpperCAmelCase = is_training _UpperCAmelCase = use_input_mask _UpperCAmelCase = use_token_type_ids _UpperCAmelCase = use_labels _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = coordinate_size _UpperCAmelCase = shape_size _UpperCAmelCase = num_labels _UpperCAmelCase = num_choices _UpperCAmelCase = scope _UpperCAmelCase = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) _UpperCAmelCase = text_seq_length _UpperCAmelCase = (image_size // patch_size) ** 2 + 1 _UpperCAmelCase = self.text_seq_length + self.image_seq_length def _a ( self ) -> Dict: _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_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]: _UpperCAmelCase = bbox[i, j, 3] _UpperCAmelCase = bbox[i, j, 1] _UpperCAmelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: _UpperCAmelCase = bbox[i, j, 2] _UpperCAmelCase = bbox[i, j, 0] _UpperCAmelCase = t _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_input_mask: _UpperCAmelCase = random_attention_mask([self.batch_size, self.text_seq_length] ) _UpperCAmelCase = None if self.use_token_type_ids: _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) _UpperCAmelCase = None _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) _UpperCAmelCase = LayoutLMvaConfig( 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 , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Tuple: _UpperCAmelCase = LayoutLMvaModel(config=a_ ) model.to(a_ ) model.eval() # text + image _UpperCAmelCase = model(a_ , pixel_values=a_ ) _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ , bbox=a_ , pixel_values=a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ , bbox=a_ , pixel_values=a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only _UpperCAmelCase = model(a_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only _UpperCAmelCase = model(pixel_values=a_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Optional[Any]: _UpperCAmelCase = self.num_labels _UpperCAmelCase = LayoutLMvaForSequenceClassification(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Union[str, Any]: _UpperCAmelCase = self.num_labels _UpperCAmelCase = LayoutLMvaForTokenClassification(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Dict: _UpperCAmelCase = LayoutLMvaForQuestionAnswering(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , start_positions=a_ , end_positions=a_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _a ( self ) -> Optional[int]: _UpperCAmelCase = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = config_and_inputs _UpperCAmelCase = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase_ : Any = False lowercase_ : Dict = False lowercase_ : List[str] = False lowercase_ : str = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) lowercase_ : int = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def _a ( self , a_ , a_ , a_ , a_ , a_ ) -> List[str]: # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = LayoutLMvaModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=a_ , hidden_size=37 ) def _a ( self , a_ , a_ , a_=False ) -> List[str]: _UpperCAmelCase = copy.deepcopy(a_ ) if model_class in get_values(a_ ): _UpperCAmelCase = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(a_ , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a_ ): _UpperCAmelCase = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in get_values(a_ ): _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in [ *get_values(a_ ), ]: _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in [ *get_values(a_ ), ]: _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=a_ , ) return inputs_dict def _a ( self ) -> int: self.config_tester.run_common_tests() def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _UpperCAmelCase = type self.model_tester.create_and_check_model(*a_ ) def _a ( self ) -> int: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a_ ) def _a ( self ) -> Any: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) @slow def _a ( self ) -> List[str]: for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = LayoutLMvaModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class _lowerCAmelCase ( unittest.TestCase ): @cached_property def _a ( self ) -> List[Any]: return LayoutLMvaImageProcessor(apply_ocr=a_ ) if is_vision_available() else None @slow def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ).to(a_ ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=a_ , return_tensors="pt" ).pixel_values.to(a_ ) _UpperCAmelCase = torch.tensor([[1, 2]] ) _UpperCAmelCase = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass _UpperCAmelCase = model( input_ids=input_ids.to(a_ ) , bbox=bbox.to(a_ ) , pixel_values=pixel_values.to(a_ ) , ) # verify the logits _UpperCAmelCase = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , a_ ) _UpperCAmelCase = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(a_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , a_ , atol=1e-4 ) )
657
0
from sympy import diff, lambdify, symbols from sympy.functions import * # noqa: F403 def A_ ( A__ , A__ , A__ = "x" , A__ = 10**-10 , A__ = 1 , ) -> Optional[Any]: a__ : Union[str, Any] = symbols(UpperCamelCase__ ) a__ : List[Any] = lambdify(UpperCamelCase__ , UpperCamelCase__ ) a__ : List[str] = lambdify(UpperCamelCase__ , diff(UpperCamelCase__ , UpperCamelCase__ ) ) a__ : Any = starting_point while True: if diff_function(UpperCamelCase__ ) != 0: a__ : List[str] = prev_guess - multiplicity * func(UpperCamelCase__ ) / diff_function( UpperCamelCase__ ) else: raise ZeroDivisionError('Could not find root' ) from None # Precision is checked by comparing the difference of consecutive guesses if abs(next_guess - prev_guess ) < precision: return next_guess a__ : int = next_guess # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F"""The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}""") # Find root of polynomial # Find fourth Root of 5 print(F"""The root of x**4 - 5 = 0 is {newton_raphson('x**4 -5', 0.4 +5j)}""") # Find value of e print( """The root of log(y) - 1 = 0 is """, F"""{newton_raphson('log(y) - 1', 2, variable='y')}""", ) # Exponential Roots print( """The root of exp(x) - 1 = 0 is""", F"""{newton_raphson('exp(x) - 1', 1_0, precision=0.005)}""", ) # Find root of cos(x) print(F"""The root of cos(x) = 0 is {newton_raphson('cos(x)', 0)}""")
302
"""simple docstring""" import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class _lowerCAmelCase ( unittest.TestCase ): lowercase_ : str = MODEL_FOR_MASKED_LM_MAPPING lowercase_ : List[str] = TF_MODEL_FOR_MASKED_LM_MAPPING def _a ( self ) -> Optional[Any]: super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def _a ( self ) -> str: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="tf" ) _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is grouped", "score": 2.1e-05, "token": 38015, "token_str": " grouped"}, {"sequence": "My name is accuser", "score": 2.1e-05, "token": 25506, "token_str": " accuser"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ { "sequence": "The largest city in France is grouped", "score": 2.1e-05, "token": 38015, "token_str": " grouped", }, { "sequence": "The largest city in France is accuser", "score": 2.1e-05, "token": 25506, "token_str": " accuser", }, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, {"sequence": "My name is Patrick", "score": 2e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 1.9e-05, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="pt" ) _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul"}, {"sequence": "My name isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ { "sequence": "The largest city in France is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul", }, {"sequence": "The largest city in France isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Patrick", "score": 2.1e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 2e-05, "token": 2941, "token_str": " Te"}, {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, ] , ) _UpperCAmelCase = unmasker("My name is <mask> <mask>" , top_k=2 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ [ { "score": 2.2e-05, "token": 35676, "token_str": " Maul", "sequence": "<s>My name is Maul<mask></s>", }, {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name isELS<mask></s>"}, ], [ { "score": 2.2e-05, "token": 35676, "token_str": " Maul", "sequence": "<s>My name is<mask> Maul</s>", }, {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name is<mask>ELS</s>"}, ], ] , ) @require_torch_gpu def _a ( self ) -> int: _UpperCAmelCase = pipeline("fill-mask" , model="hf-internal-testing/tiny-random-distilbert" , device=0 , framework="pt" ) # convert model to fp16 pipe.model.half() _UpperCAmelCase = pipe("Paris is the [MASK] of France." ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(a_ , a_ ) @slow @require_torch def _a ( self ) -> int: _UpperCAmelCase = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="pt" ) self.run_large_test(a_ ) @slow @require_tf def _a ( self ) -> int: _UpperCAmelCase = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="tf" ) self.run_large_test(a_ ) def _a ( self , a_ ) -> int: _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ ) , [ {"sequence": "My name is John", "score": 0.008, "token": 610, "token_str": " John"}, {"sequence": "My name is Chris", "score": 0.007, "token": 1573, "token_str": " Chris"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ ) , [ { "sequence": "The largest city in France is Paris", "score": 0.251, "token": 2201, "token_str": " Paris", }, { "sequence": "The largest city in France is Lyon", "score": 0.214, "token": 12790, "token_str": " Lyon", }, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ ) , [ {"sequence": "My name is Patrick", "score": 0.005, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Clara", "score": 0.000, "token": 13606, "token_str": " Clara"}, {"sequence": "My name is Te", "score": 0.000, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _a ( self ) -> Any: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="pt" ) _UpperCAmelCase = None _UpperCAmelCase = None self.run_pipeline_test(a_ , [] ) @require_tf def _a ( self ) -> List[Any]: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="tf" ) _UpperCAmelCase = None _UpperCAmelCase = None self.run_pipeline_test(a_ , [] ) def _a ( self , a_ , a_ , a_ ) -> Optional[Any]: if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("The provided tokenizer has no mask token, (probably reformer or wav2vec2)" ) _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = [ f"This is another {tokenizer.mask_token} test", ] return fill_masker, examples def _a ( self , a_ , a_ ) -> List[str]: _UpperCAmelCase = fill_masker.tokenizer _UpperCAmelCase = fill_masker.model _UpperCAmelCase = fill_masker( f"This is a {tokenizer.mask_token}" , ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = fill_masker([f"This is a {tokenizer.mask_token}"] ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = fill_masker([f"This is a {tokenizer.mask_token}", f"Another {tokenizer.mask_token} great test."] ) self.assertEqual( a_ , [ [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], ] , ) with self.assertRaises(a_ ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(a_ ): fill_masker("This is" ) self.run_test_top_k(a_ , a_ ) self.run_test_targets(a_ , a_ ) self.run_test_top_k_targets(a_ , a_ ) self.fill_mask_with_duplicate_targets_and_top_k(a_ , a_ ) self.fill_mask_with_multiple_masks(a_ , a_ ) def _a ( self , a_ , a_ ) -> Optional[int]: _UpperCAmelCase = tokenizer.get_vocab() _UpperCAmelCase = sorted(vocab.keys() )[:2] # Pipeline argument _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ , targets=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , a_ ) _UpperCAmelCase = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(a_ ) ) # Call argument _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , a_ ) _UpperCAmelCase = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(a_ ) ) # Score equivalence _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) _UpperCAmelCase = [top_mask["token_str"] for top_mask in outputs] _UpperCAmelCase = [top_mask["score"] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(a_ ) == set(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) _UpperCAmelCase = [top_mask["score"] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) # Raises with invalid with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=[""] ) with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets="" ) def _a ( self , a_ , a_ ) -> str: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ , top_k=2 ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=2 ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) def _a ( self , a_ , a_ ) -> List[Any]: _UpperCAmelCase = tokenizer.get_vocab() _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) # top_k=2, ntargets=3 _UpperCAmelCase = sorted(vocab.keys() )[:3] _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=2 , targets=a_ ) # If we use the most probably targets, and filter differently, we should still # have the same results _UpperCAmelCase = [el["token_str"] for el in sorted(a_ , key=lambda a_ : x["score"] , reverse=a_ )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(a_ ).issubset(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=3 , targets=a_ ) # They should yield exactly the same result self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) def _a ( self , a_ , a_ ) -> Optional[Any]: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = tokenizer.get_vocab() # String duplicates + id duplicates _UpperCAmelCase = sorted(vocab.keys() )[:3] _UpperCAmelCase = [targets[0], targets[1], targets[0], targets[2], targets[1]] _UpperCAmelCase = fill_masker(f"My name is {tokenizer.mask_token}" , targets=a_ , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(a_ ) , 3 ) def _a ( self , a_ , a_ ) -> Any: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker( f"This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}" , top_k=2 ) self.assertEqual( a_ , [ [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], ] , )
657
0
'''simple docstring''' from __future__ import annotations def _lowercase ( UpperCamelCase__ : Optional[Any] ): if len(UpperCamelCase__ ) < 2: raise ValueError('Monogons and Digons are not polygons in the Euclidean space' ) if any(i <= 0 for i in nums ): raise ValueError('All values must be greater than 0' ) __A : Dict = nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1] ) if __name__ == "__main__": import doctest doctest.testmod()
365
"""simple docstring""" import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class _lowerCAmelCase ( lowerCamelCase ): def _a ( self ) -> List[str]: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> Optional[int]: with self.assertRaises(a_ ): _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def _a ( self ) -> int: with self.assertRaises(a_ ): _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("bool" ) , type=Value("int64" ) ) ) def _a ( self ) -> Optional[Any]: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> int: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , type=Value("int64" ) ) ) def _a ( self ) -> Dict: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , try_type=Value("int64" ) ) ) self.assertEqual(arr.type , pa.string() ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def _a ( self ) -> Tuple: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , type=ArrayaD((1, 3) , "int64" ) ) ) def _a ( self ) -> str: _UpperCAmelCase = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def _a ( self ) -> Tuple: _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def _a ( self ) -> List[str]: import PIL.Image _UpperCAmelCase = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( "datasets.arrow_writer.cast_to_python_objects" , side_effect=a_ ) as mock_cast_to_python_objects: _UpperCAmelCase = pa.array(TypedSequence([{"path": None, "bytes": B"image_bytes"}, pil_image] , type=Image() ) ) _UpperCAmelCase , _UpperCAmelCase = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("optimize_list_casting" , a_ ) self.assertFalse(kwargs["optimize_list_casting"] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferReader(UpperCamelCase__ ) if isinstance(UpperCamelCase__ , pa.Buffer ) else pa.memory_map(UpperCamelCase__ ) _UpperCAmelCase = pa.ipc.open_stream(UpperCamelCase__ ) _UpperCAmelCase = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = Features({"labels": ClassLabel(names=["neg", "pos"] )} ) with ArrowWriter(stream=UpperCamelCase__ , features=UpperCamelCase__ ) as writer: writer.write({"labels": 0} ) writer.write({"labels": 1} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pa.ipc.open_stream(UpperCamelCase__ ) _UpperCAmelCase = f.read_all() _UpperCAmelCase = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(UpperCamelCase__ ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: with pytest.raises(UpperCamelCase__ ): writer.write({"col_1": "foo", "col_2": 1} , key=[1, 2] ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: with pytest.raises(UpperCamelCase__ ): writer.write({"col_1": "foo", "col_2": 1} , key=10 ) writer.write({"col_1": "bar", "col_2": 2} , key=10 ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: writer.write({"col_1": "foo", "col_2": 1} , key=1 ) writer.write({"col_1": "bar", "col_2": 2} , key=2 ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) writer.write_batch({"col_1": [], "col_2": []} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_table(pa.Table.from_pydict({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_row(pa.Table.from_pydict({"col_1": ["foo"], "col_2": [1]} ) ) writer.write_row(pa.Table.from_pydict({"col_1": ["bar"], "col_2": [2]} ) ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __lowerCamelCase ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} _UpperCAmelCase = os.path.join(UpperCamelCase__ , "test.arrow" ) with ArrowWriter(path=UpperCamelCase__ , schema=pa.schema(UpperCamelCase__ ) ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(UpperCamelCase__ , 1 ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if pa.types.is_list(UpperCamelCase__ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if isinstance(lst[0] , UpperCamelCase__ ): change_first_primitive_element_in_list(lst[0] , UpperCamelCase__ ) else: _UpperCAmelCase = value @pytest.mark.parametrize("optimized_int_type, expected_dtype" , [(None, pa.intaa()), (Value("int32" ), pa.intaa())] ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.array(TypedSequence(UpperCamelCase__ , optimized_int_type=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( "col, expected_dtype" , [ ("attention_mask", pa.inta()), ("special_tokens_mask", pa.inta()), ("token_type_ids", pa.inta()), ("input_ids", pa.intaa()), ("other", pa.intaa()), ] , ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.array(OptimizedTypedSequence(UpperCamelCase__ , col=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications _UpperCAmelCase = copy.deepcopy(UpperCamelCase__ ) _UpperCAmelCase = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(UpperCamelCase__ , UpperCamelCase__ ) _UpperCAmelCase = pa.array(OptimizedTypedSequence(UpperCamelCase__ , col=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("raise_exception" , [False, True] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = str(tmp_path / "dataset-train.arrow" ) try: with ArrowWriter(path=UpperCamelCase__ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = "mock://dataset-train.arrow" with ArrowWriter(path=UpperCamelCase__ , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(UpperCamelCase__ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(UpperCamelCase__ ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ParquetWriter(stream=UpperCamelCase__ ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pq.read_table(UpperCamelCase__ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("embed_local_files" , [False, True] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" import PIL.Image _UpperCAmelCase = str(tmp_path / "test_image_rgb.jpg" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(UpperCamelCase__ , format="png" ) _UpperCAmelCase = pa.BufferOutputStream() with ParquetWriter( stream=UpperCamelCase__ , features=Features({"image": Image()} ) , embed_local_files=UpperCamelCase__ ) as writer: writer.write({"image": image_path} ) writer.finalize() _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pq.read_table(UpperCamelCase__ ) _UpperCAmelCase = pa_table.to_pydict() if embed_local_files: assert isinstance(out["image"][0]["path"] , UpperCamelCase__ ) with open(UpperCamelCase__ , "rb" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.schema([pa.field("col_1" , pa.string() , nullable=UpperCamelCase__ )] ) _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter(stream=UpperCamelCase__ ) as writer: writer._build_writer(inferred_schema=UpperCamelCase__ ) assert writer._schema == pa.schema([pa.field("col_1" , pa.string() )] )
657
0
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class UpperCamelCase__( unittest.TestCase ): def a__( self : Union[str, Any] )-> Tuple: """simple docstring""" UpperCAmelCase = inspect.getfile(accelerate.test_utils ) UpperCAmelCase = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''external_deps''', '''test_metrics.py'''] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 UpperCAmelCase = test_metrics @require_cpu def a__( self : Any )-> Optional[int]: """simple docstring""" debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def a__( self : str )-> Dict: """simple docstring""" debug_launcher(self.test_metrics.main ) @require_single_gpu def a__( self : Dict )-> Union[str, Any]: """simple docstring""" self.test_metrics.main() @require_multi_gpu def a__( self : List[str] )-> Dict: """simple docstring""" print(F"""Found {torch.cuda.device_count()} devices.""" ) UpperCAmelCase = ['''torchrun''', F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(a_ , env=os.environ.copy() )
210
"""simple docstring""" import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class _lowerCAmelCase ( unittest.TestCase ): def _a ( self ) -> Optional[Any]: _UpperCAmelCase = ["a", "b", "c"] # Defaults to last layer if both are None _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , a_ , a_ ) self.assertEqual(a_ , ["c"] ) self.assertEqual(a_ , [2] ) # Out indices set to match out features _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(["a", "c"] , a_ , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features set to match out indices _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , [0, 2] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features selected from negative indices _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , [-3, -1] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [-3, -1] ) def _a ( self ) -> Optional[int]: # Stage names must be set with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , a_ ) # Out features must be a list with self.assertRaises(a_ ): verify_out_features_out_indices(("a", "b") , (0, 1) , ["a", "b"] ) # Out features must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , ["a"] ) # Out indices must be a list or tuple with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , 0 , ["a", "b"] ) # Out indices must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , (0, 1) , ["a"] ) # Out features and out indices must be the same length with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0,) , ["a", "b", "c"] ) # Out features should match out indices with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 2) , ["a", "b", "c"] ) # Out features and out indices should be in order with self.assertRaises(a_ ): verify_out_features_out_indices(["b", "a"] , (0, 1) , ["a", "b"] ) # Check passes with valid inputs verify_out_features_out_indices(["a", "b", "d"] , (0, 1, -1) , ["a", "b", "c", "d"] ) def _a ( self ) -> int: _UpperCAmelCase = BackboneMixin() _UpperCAmelCase = ["a", "b", "c"] _UpperCAmelCase = ["a", "c"] _UpperCAmelCase = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly _UpperCAmelCase = ["a", "b"] self.assertEqual(backbone.out_features , ["a", "b"] ) self.assertEqual(backbone.out_indices , [0, 1] ) _UpperCAmelCase = [-3, -1] self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [-3, -1] )
657
0
import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class snake_case_ ( __A ): '''simple docstring''' @require_torch def __SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched lowerCamelCase_ : str = "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " lowerCamelCase_ : Union[str, Any] = "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " lowerCamelCase_ : Union[str, Any] = "\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache lowerCamelCase_ : Tuple = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(a_ ) BertModel.from_pretrained(a_ ) BertTokenizer.from_pretrained(a_ ) pipeline(task="fill-mask" , model=a_ ) # baseline - just load from_pretrained with normal network lowerCamelCase_ : Optional[Any] = [sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed lowerCamelCase_ : str = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files lowerCamelCase_ : str = "1" lowerCamelCase_ : Optional[int] = subprocess.run(a_ , env=a_ , check=a_ , capture_output=a_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) @require_torch def __SCREAMING_SNAKE_CASE ( self : int ) -> Any: # python one-liner segments # this must be loaded before socket.socket is monkey-patched lowerCamelCase_ : int = "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " lowerCamelCase_ : Union[str, Any] = "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " lowerCamelCase_ : List[str] = "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache lowerCamelCase_ : Tuple = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(a_ ) BertModel.from_pretrained(a_ ) BertTokenizer.from_pretrained(a_ ) pipeline(task="fill-mask" , model=a_ ) # baseline - just load from_pretrained with normal network lowerCamelCase_ : str = [sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed lowerCamelCase_ : Tuple = self.get_env() lowerCamelCase_ : List[str] = subprocess.run(a_ , env=a_ , check=a_ , capture_output=a_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) @require_torch def __SCREAMING_SNAKE_CASE ( self : str ) -> int: # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched lowerCamelCase_ : Union[str, Any] = "\nfrom transformers import BertConfig, BertModel, BertTokenizer\n " lowerCamelCase_ : Dict = "\nmname = \"hf-internal-testing/tiny-random-bert-sharded\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint(\"success\")\n " lowerCamelCase_ : List[Any] = "\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " # baseline - just load from_pretrained with normal network lowerCamelCase_ : Dict = [sys.executable, "-c", "\n".join([load, run] )] # should succeed lowerCamelCase_ : List[Any] = self.get_env() lowerCamelCase_ : Union[str, Any] = subprocess.run(a_ , env=a_ , check=a_ , capture_output=a_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) # next emulate no network lowerCamelCase_ : Optional[Any] = [sys.executable, "-c", "\n".join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files lowerCamelCase_ : Any = "1" lowerCamelCase_ : List[Any] = subprocess.run(a_ , env=a_ , check=a_ , capture_output=a_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) @require_torch def __SCREAMING_SNAKE_CASE ( self : int ) -> int: lowerCamelCase_ : Any = "\nfrom transformers import pipeline\n " lowerCamelCase_ : str = "\nmname = \"hf-internal-testing/tiny-random-bert\"\npipe = pipeline(model=mname)\n " lowerCamelCase_ : Tuple = "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " lowerCamelCase_ : Any = self.get_env() lowerCamelCase_ : str = "1" lowerCamelCase_ : Tuple = [sys.executable, "-c", "\n".join([load, mock, run] )] lowerCamelCase_ : Dict = subprocess.run(a_ , env=a_ , check=a_ , capture_output=a_ ) self.assertEqual(result.returncode , 1 , result.stderr ) self.assertIn( "You cannot infer task automatically within `pipeline` when using offline mode" , result.stderr.decode().replace("\n" , "" ) , ) @require_torch def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: lowerCamelCase_ : List[str] = "\nfrom transformers import AutoModel\n " lowerCamelCase_ : str = "\nmname = \"hf-internal-testing/test_dynamic_model\"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint(\"success\")\n " # baseline - just load from_pretrained with normal network lowerCamelCase_ : Tuple = [sys.executable, "-c", "\n".join([load, run] )] # should succeed lowerCamelCase_ : Optional[int] = self.get_env() lowerCamelCase_ : Optional[Any] = subprocess.run(a_ , env=a_ , check=a_ , capture_output=a_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files lowerCamelCase_ : int = "1" lowerCamelCase_ : Optional[Any] = subprocess.run(a_ , env=a_ , check=a_ , capture_output=a_ ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("success" , result.stdout.decode() )
488
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = { '''configuration_electra''': ['''ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ElectraConfig''', '''ElectraOnnxConfig'''], '''tokenization_electra''': ['''ElectraTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''ElectraTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''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: __magic_name__ = [ '''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: __magic_name__ = [ '''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 __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
657
0
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 6_5_0, '''eval_accuracy''': 0.6, '''eval_loss''': 0.9}, }, { '''framework''': '''tensorflow''', '''script''': '''run_tf.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 6_0_0, '''eval_accuracy''': 0.3, '''eval_loss''': 0.9}, }, ] ) class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : int ): if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding="utf-8" , check=a_ , ) assert hasattr(self , "env" ) def _A ( self : Optional[int] , UpperCAmelCase_ : Optional[Any]=1 ): # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-single''' , instance_count=a_ , instance_type=self.instance_type , debugger_hook_config=a_ , hyperparameters={**self.env.hyperparameters, "model_name_or_path": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version="py36" , ) def _A ( self : Optional[int] , UpperCAmelCase_ : Dict ): TrainingJobAnalytics(a_ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) def _A ( self : Optional[int] ): # create estimator SCREAMING_SNAKE_CASE : Any = self.create_estimator() # run training estimator.fit() # result dataframe SCREAMING_SNAKE_CASE : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis SCREAMING_SNAKE_CASE : int = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"] ) SCREAMING_SNAKE_CASE : str = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping SCREAMING_SNAKE_CASE : Tuple = ( Session().describe_training_job(estimator.latest_training_job.name ).get("TrainingTimeInSeconds" , 99_9999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy ) assert all(t <= self.results["eval_loss"] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , "w" ) as outfile: json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss} , a_ )
62
"""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 _lowerCAmelCase ( lowerCamelCase , unittest.TestCase ): lowercase_ : Tuple = BarthezTokenizer lowercase_ : List[Any] = BarthezTokenizerFast lowercase_ : Dict = True lowercase_ : int = True def _a ( self ) -> Any: super().setUp() _UpperCAmelCase = BarthezTokenizerFast.from_pretrained("moussaKam/mbarthez" ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=a_ ) _UpperCAmelCase = tokenizer def _a ( self ) -> List[Any]: _UpperCAmelCase = "<pad>" _UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = 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(a_ ) , 101122 ) def _a ( self ) -> Union[str, Any]: self.assertEqual(self.get_tokenizer().vocab_size , 101122 ) @require_torch def _a ( self ) -> List[Any]: _UpperCAmelCase = ["A long paragraph for summarization.", "Another paragraph for summarization."] _UpperCAmelCase = [0, 57, 3018, 70307, 91, 2] _UpperCAmelCase = self.tokenizer( a_ , max_length=len(a_ ) , padding=a_ , truncation=a_ , return_tensors="pt" ) self.assertIsInstance(a_ , a_ ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) _UpperCAmelCase = batch.input_ids.tolist()[0] self.assertListEqual(a_ , a_ ) def _a ( self ) -> str: if not self.test_rust_tokenizer: return _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = self.get_rust_tokenizer() _UpperCAmelCase = "I was born in 92000, and this is falsé." _UpperCAmelCase = tokenizer.tokenize(a_ ) _UpperCAmelCase = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) _UpperCAmelCase = tokenizer.encode(a_ , add_special_tokens=a_ ) _UpperCAmelCase = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) _UpperCAmelCase = self.get_rust_tokenizer() _UpperCAmelCase = tokenizer.encode(a_ ) _UpperCAmelCase = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def _a ( self ) -> Dict: # fmt: off _UpperCAmelCase = {"input_ids": [[0, 490, 14328, 4507, 354, 47, 43669, 95, 25, 78117, 20215, 19779, 190, 22, 400, 4, 35343, 80310, 603, 86, 24937, 105, 33438, 94762, 196, 39642, 7, 15, 15933, 173, 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, 10534, 87, 25, 66, 3358, 196, 55289, 8, 82961, 81, 2204, 75203, 7, 15, 763, 12956, 216, 178, 14328, 9595, 1377, 69693, 7, 448, 71021, 196, 18106, 1437, 13974, 108, 9083, 4, 49315, 7, 39, 86, 1326, 2793, 46333, 4, 448, 196, 74588, 7, 49315, 7, 39, 21, 822, 38470, 74, 21, 66723, 62480, 8, 22050, 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. _UpperCAmelCase = [ "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=a_ , model_name="moussaKam/mbarthez" , revision="c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6" , sequences=a_ , )
657
0
import json import logging import os import sys from time import time from unittest.mock import patch from transformers.testing_utils import TestCasePlus, require_torch_tpu logging.basicConfig(level=logging.DEBUG) lowerCamelCase : Any = logging.getLogger() def lowercase__( A ): snake_case__ : List[Any] = {} snake_case__ : str = os.path.join(UpperCamelCase__ , 'all_results.json' ) if os.path.exists(UpperCamelCase__ ): with open(UpperCamelCase__ , 'r' ) as f: snake_case__ : Union[str, Any] = json.load(UpperCamelCase__ ) else: raise ValueError(f'''can\'t find {path}''' ) return results lowerCamelCase : Optional[int] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @require_torch_tpu class snake_case__ ( UpperCamelCase_ ): def UpperCAmelCase__ ( self : List[Any] ): import xla_spawn snake_case__ : int = self.get_auto_remove_tmp_dir() snake_case__ : Any = F'''\n ./examples/pytorch/text-classification/run_glue.py\n --num_cores=8\n ./examples/pytorch/text-classification/run_glue.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --do_train\n --do_eval\n --debug tpu_metrics_debug\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --max_steps=10\n --warmup_steps=2\n --seed=42\n --max_seq_length=128\n '''.split() with patch.object(a_ , 'argv' , a_ ): snake_case__ : int = time() xla_spawn.main() snake_case__ : Tuple = time() snake_case__ : Optional[Any] = get_results(a_ ) self.assertGreaterEqual(result['eval_accuracy'] , 0.75 ) # Assert that the script takes less than 500 seconds to make sure it doesn't hang. self.assertLess(end - start , 5_0_0 ) def UpperCAmelCase__ ( self : Tuple ): import xla_spawn snake_case__ : Dict = '\n ./tests/test_trainer_tpu.py\n --num_cores=8\n ./tests/test_trainer_tpu.py\n '.split() with patch.object(a_ , 'argv' , a_ ): xla_spawn.main()
170
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): _UpperCAmelCase = f"Input value of [number={number}] must be an integer" raise TypeError(UpperCamelCase__ ) if number < 0: return False _UpperCAmelCase = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
657
0
import importlib.metadata from typing import Union from packaging.version import Version, parse from .constants import STR_OPERATION_TO_FUNC lowercase : str = parse(importlib.metadata.version('''torch''')) def lowerCAmelCase__ ( _a : List[str] , _a : Tuple , _a : List[Any] ): if operation not in STR_OPERATION_TO_FUNC.keys(): raise ValueError(F'''`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys() )}, received {operation}''' ) snake_case_ : Tuple = STR_OPERATION_TO_FUNC[operation] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): snake_case_ : int = parse(importlib.metadata.version(UpperCamelCase__ ) ) return operation(UpperCamelCase__ , parse(UpperCamelCase__ ) ) def lowerCAmelCase__ ( _a : List[Any] , _a : Optional[Any] ): return compare_versions(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
568
"""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(lowerCamelCase ) class _lowerCAmelCase ( lowerCamelCase ): def __init__( self , *a_ , **a_ ) -> Optional[int]: super().__init__(*a_ , **a_ ) 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 _a ( self , **a_ ) -> List[str]: _UpperCAmelCase = {} if "threshold" in kwargs: _UpperCAmelCase = kwargs["threshold"] return {}, {}, postprocess_kwargs def __call__( self , *a_ , **a_ ) -> Union[Predictions, List[Prediction]]: return super().__call__(*a_ , **a_ ) def _a ( self , a_ ) -> Optional[Any]: _UpperCAmelCase = load_image(a_ ) _UpperCAmelCase = torch.IntTensor([[image.height, image.width]] ) _UpperCAmelCase = self.image_processor(images=[image] , return_tensors="pt" ) if self.tokenizer is not None: _UpperCAmelCase = self.tokenizer(text=inputs["words"] , boxes=inputs["boxes"] , return_tensors="pt" ) _UpperCAmelCase = target_size return inputs def _a ( self , a_ ) -> Optional[Any]: _UpperCAmelCase = model_inputs.pop("target_size" ) _UpperCAmelCase = self.model(**a_ ) _UpperCAmelCase = outputs.__class__({"target_size": target_size, **outputs} ) if self.tokenizer is not None: _UpperCAmelCase = model_inputs["bbox"] return model_outputs def _a ( self , a_ , a_=0.9 ) -> int: _UpperCAmelCase = 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. _UpperCAmelCase , _UpperCAmelCase = target_size[0].tolist() def unnormalize(a_ ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) _UpperCAmelCase , _UpperCAmelCase = model_outputs["logits"].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) _UpperCAmelCase = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] _UpperCAmelCase = [unnormalize(a_ ) for bbox in model_outputs["bbox"].squeeze(0 )] _UpperCAmelCase = ["score", "label", "box"] _UpperCAmelCase = [dict(zip(a_ , a_ ) ) for vals in zip(scores.tolist() , a_ , a_ ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel _UpperCAmelCase = self.image_processor.post_process_object_detection(a_ , a_ , a_ ) _UpperCAmelCase = raw_annotations[0] _UpperCAmelCase = raw_annotation["scores"] _UpperCAmelCase = raw_annotation["labels"] _UpperCAmelCase = raw_annotation["boxes"] _UpperCAmelCase = scores.tolist() _UpperCAmelCase = [self.model.config.idalabel[label.item()] for label in labels] _UpperCAmelCase = [self._get_bounding_box(a_ ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] _UpperCAmelCase = ["score", "label", "box"] _UpperCAmelCase = [ dict(zip(a_ , a_ ) ) for vals in zip(raw_annotation["scores"] , raw_annotation["labels"] , raw_annotation["boxes"] ) ] return annotation def _a ( self , a_ ) -> Dict[str, int]: if self.framework != "pt": raise ValueError("The ObjectDetectionPipeline is only available in PyTorch." ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = box.int().tolist() _UpperCAmelCase = { "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax, } return bbox
657
0
import sys from pathlib import Path UpperCAmelCase__ = Path(__file__).resolve().parents[3] / "src" sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) UpperCAmelCase__ = {"base": "patrickvonplaten/wav2vec2_tiny_random", "robust": "patrickvonplaten/wav2vec2_tiny_random_robust"} UpperCAmelCase__ = "zero2" UpperCAmelCase__ = "zero3" UpperCAmelCase__ = [ZEROa, ZEROa] def _a ( a :Union[str, Any] , a :Union[str, Any] , a :List[str] ) -> Tuple: a = parameterized.to_safe_name('''_'''.join(str(UpperCamelCase__ ) for x in param.args ) ) return F"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test UpperCAmelCase__ = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class lowercase_ ( lowercase ): '''simple docstring''' @parameterized.expand(a_ , name_func=a_ ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple ) ->int: """simple docstring""" self.run_and_check( stage=a_ , model=a_ , distributed=a_ , fpaa=a_ , ) @require_torch_multi_gpu @parameterized.expand(a_ , name_func=a_ ) def __lowerCAmelCase ( self : str , __UpperCAmelCase : str , __UpperCAmelCase : Dict ) ->str: """simple docstring""" self.run_and_check( stage=a_ , model=a_ , distributed=a_ , fpaa=a_ , ) @parameterized.expand(a_ , name_func=a_ ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=a_ , model=a_ , distributed=a_ , fpaa=a_ , ) @require_torch_multi_gpu @parameterized.expand(a_ , name_func=a_ ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : str ) ->Any: """simple docstring""" self.run_and_check( stage=a_ , model=a_ , distributed=a_ , fpaa=a_ , ) def __lowerCAmelCase ( self : str , __UpperCAmelCase : Any ) ->List[Any]: """simple docstring""" pass def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Any , __UpperCAmelCase : int = 10 , __UpperCAmelCase : Dict = True , __UpperCAmelCase : int = True , __UpperCAmelCase : int = True , ) ->Union[str, Any]: """simple docstring""" a = models[model] a = self.run_trainer( stage=a_ , model_name=a_ , eval_steps=a_ , num_train_epochs=1 , distributed=a_ , fpaa=a_ , ) self.do_checks(a_ ) return output_dir def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Any = 10 , __UpperCAmelCase : Optional[int] = 1 , __UpperCAmelCase : Any = True , __UpperCAmelCase : Union[str, Any] = True , ) ->Dict: """simple docstring""" a = self.get_auto_remove_tmp_dir('''./xxx''' , after=a_ ) a = F"""\n --model_name_or_path {model_name}\n --dataset_name hf-internal-testing/librispeech_asr_dummy\n --dataset_config_name clean\n --train_split_name validation\n --validation_split_name validation\n --output_dir {output_dir}\n --num_train_epochs {str(a_ )}\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 2\n --evaluation_strategy steps\n --learning_rate 5e-4\n --warmup_steps 8\n --orthography timit\n --preprocessing_num_workers 1\n --group_by_length\n --freeze_feature_extractor\n --report_to none\n --save_steps 0\n --eval_steps {eval_steps}\n --report_to none\n """.split() if fpaa: args.extend(['''--fp16'''] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files a = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() a = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] a = self.get_launcher(a_ ) a = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(a_ , env=self.get_env() ) return output_dir def __lowerCAmelCase ( self : str , __UpperCAmelCase : Optional[int]=False ) ->List[Any]: """simple docstring""" a = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
117
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def merge(UpperCamelCase__ , UpperCamelCase__ ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(UpperCamelCase__ ) <= 1: return collection _UpperCAmelCase = len(UpperCamelCase__ ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() __magic_name__ = input('''Enter numbers separated by a comma:\n''').strip() __magic_name__ = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
657
0
from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class lowercase__ ( __SCREAMING_SNAKE_CASE ): def __init__( self : List[Any] , _lowercase : List[Any] , _lowercase : int ): """simple docstring""" super().__init__() self.register_modules(unet=a_ , scheduler=a_ ) @torch.no_grad() def __call__( self : List[str] , _lowercase : Optional[Any] = 1 , _lowercase : Optional[int] = None , _lowercase : Optional[int] = 50 , _lowercase : List[Any] = "pil" , _lowercase : Tuple = True , **_lowercase : Union[str, Any] , ): """simple docstring""" UpperCAmelCase__ = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=a_ , ) UpperCAmelCase__ = image.to(self.device ) # set step values self.scheduler.set_timesteps(a_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output UpperCAmelCase__ = self.unet(a_ , a_ ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 UpperCAmelCase__ = self.scheduler.step(a_ , a_ , a_ ).prev_sample UpperCAmelCase__ = (image / 2 + 0.5).clamp(0 , 1 ) UpperCAmelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCAmelCase__ = self.numpy_to_pil(a_ ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=a_ ), "This is a local test"
475
"""simple docstring""" 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 _lowerCAmelCase : def __init__( self , a_ , a_=13 , a_=7 , a_=True , a_=True , a_=True , a_=99 , a_=32 , a_=5 , a_=4 , a_=37 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=16 , a_=2 , a_=0.02 , a_=3 , a_=4 , a_=None , ) -> List[str]: _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = seq_length _UpperCAmelCase = is_training _UpperCAmelCase = use_token_type_ids _UpperCAmelCase = use_labels _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = num_labels _UpperCAmelCase = num_choices _UpperCAmelCase = scope _UpperCAmelCase = self.vocab_size - 1 def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCAmelCase = None if self.use_token_type_ids: _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) _UpperCAmelCase = 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 , ) _UpperCAmelCase = 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 _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Optional[int]: _UpperCAmelCase = OpenAIGPTModel(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , head_mask=a_ ) _UpperCAmelCase = model(a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> List[Any]: _UpperCAmelCase = OpenAIGPTLMHeadModel(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Optional[Any]: _UpperCAmelCase = OpenAIGPTDoubleHeadsModel(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Dict: _UpperCAmelCase = self.num_labels _UpperCAmelCase = OpenAIGPTForSequenceClassification(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = config_and_inputs _UpperCAmelCase = { "input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask, } return config, inputs_dict @require_torch class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase_ : Any = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowercase_ : Optional[Any] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowercase_ : Union[str, Any] = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def _a ( self , a_ , a_ , a_ , a_ , a_ ) -> Any: 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 _a ( self , a_ , a_ , a_=False ) -> Optional[int]: _UpperCAmelCase = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=a_ , ) _UpperCAmelCase = inputs_dict["labels"] _UpperCAmelCase = inputs_dict["labels"] _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=a_ , ) _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) return inputs_dict def _a ( self ) -> Optional[int]: _UpperCAmelCase = OpenAIGPTModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=a_ , n_embd=37 ) def _a ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def _a ( self ) -> Any: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*a_ ) def _a ( self ) -> Tuple: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*a_ ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a_ ) @slow def _a ( self ) -> int: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = OpenAIGPTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) @require_torch class _lowerCAmelCase ( unittest.TestCase ): @slow def _a ( self ) -> Any: _UpperCAmelCase = OpenAIGPTLMHeadModel.from_pretrained("openai-gpt" ) model.to(a_ ) _UpperCAmelCase = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=a_ ) # the president is _UpperCAmelCase = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 40477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the _UpperCAmelCase = model.generate(a_ , do_sample=a_ ) self.assertListEqual(output_ids[0].tolist() , a_ )
657
0
'''simple docstring''' from manim import * class __A (__magic_name__ ): def _snake_case ( self ): __UpperCAmelCase : Any = Rectangle(height=0.5 , width=0.5 ) __UpperCAmelCase : Tuple = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) __UpperCAmelCase : List[Any] = Rectangle(height=0.2_5 , width=0.2_5 ) __UpperCAmelCase : Optional[Any] = [mem.copy() for i in range(6 )] __UpperCAmelCase : Tuple = [mem.copy() for i in range(6 )] __UpperCAmelCase : Tuple = VGroup(*a_ ).arrange(a_ , buff=0 ) __UpperCAmelCase : Tuple = VGroup(*a_ ).arrange(a_ , buff=0 ) __UpperCAmelCase : Dict = VGroup(a_ , a_ ).arrange(a_ , buff=0 ) __UpperCAmelCase : List[str] = Text("CPU" , font_size=24 ) __UpperCAmelCase : List[Any] = Group(a_ , a_ ).arrange(a_ , buff=0.5 , aligned_edge=a_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(a_ ) __UpperCAmelCase : Dict = [mem.copy() for i in range(4 )] __UpperCAmelCase : int = VGroup(*a_ ).arrange(a_ , buff=0 ) __UpperCAmelCase : List[Any] = Text("GPU" , font_size=24 ) __UpperCAmelCase : Optional[Any] = Group(a_ , a_ ).arrange(a_ , buff=0.5 , aligned_edge=a_ ) gpu.move_to([-1, -1, 0] ) self.add(a_ ) __UpperCAmelCase : Tuple = [mem.copy() for i in range(6 )] __UpperCAmelCase : Tuple = VGroup(*a_ ).arrange(a_ , buff=0 ) __UpperCAmelCase : int = Text("Model" , font_size=24 ) __UpperCAmelCase : Any = Group(a_ , a_ ).arrange(a_ , buff=0.5 , aligned_edge=a_ ) model.move_to([3, -1.0, 0] ) self.add(a_ ) __UpperCAmelCase : Tuple = [] __UpperCAmelCase : Optional[Any] = [] for i, rect in enumerate(a_ ): __UpperCAmelCase : Union[str, Any] = fill.copy().set_fill(a_ , opacity=0.8 ) target.move_to(a_ ) model_arr.append(a_ ) __UpperCAmelCase : str = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0.0 ).set_fill(a_ , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(a_ ) self.add(*a_ , *a_ ) __UpperCAmelCase : str = [meta_mem.copy() for i in range(6 )] __UpperCAmelCase : Dict = [meta_mem.copy() for i in range(6 )] __UpperCAmelCase : Tuple = VGroup(*a_ ).arrange(a_ , buff=0 ) __UpperCAmelCase : Optional[int] = VGroup(*a_ ).arrange(a_ , buff=0 ) __UpperCAmelCase : Tuple = VGroup(a_ , a_ ).arrange(a_ , buff=0 ) __UpperCAmelCase : Any = Text("Disk" , font_size=24 ) __UpperCAmelCase : Optional[int] = Group(a_ , a_ ).arrange(a_ , buff=0.5 , aligned_edge=a_ ) disk.move_to([-4, -1.2_5, 0] ) self.add(a_ , a_ ) __UpperCAmelCase : List[str] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __UpperCAmelCase : int = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(a_ , a_ ) __UpperCAmelCase : str = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(a_ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(a_ ) __UpperCAmelCase : List[str] = MarkupText( f"""Now watch as an input is passed through the model\nand how the memory is utilized and handled.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(a_ ) ) __UpperCAmelCase : List[str] = Square(0.3 ) input.set_fill(a_ , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , a_ , buff=0.5 ) self.play(Write(a_ ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=a_ , buff=0.0_2 ) self.play(MoveToTarget(a_ ) ) self.play(FadeOut(a_ ) ) __UpperCAmelCase : str = Arrow(start=a_ , end=a_ , color=a_ , buff=0.5 ) a.next_to(model_arr[0].get_left() , a_ , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) __UpperCAmelCase : Union[str, Any] = MarkupText( f"""As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(a_ , run_time=3 ) ) __UpperCAmelCase : Dict = {"run_time": 1, "fade_in": True, "fade_out": True, "buff": 0.0_2} self.play( Write(a_ ) , Circumscribe(model_arr[0] , color=a_ , **a_ ) , Circumscribe(model_cpu_arr[0] , color=a_ , **a_ ) , Circumscribe(gpu_rect[0] , color=a_ , **a_ ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) __UpperCAmelCase : Tuple = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.0_2 , a_ , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.0_2 ) __UpperCAmelCase : Optional[int] = AnimationGroup( FadeOut(a_ , run_time=0.5 ) , MoveToTarget(a_ , run_time=0.5 ) , FadeIn(a_ , run_time=0.5 ) , lag_ratio=0.2 ) self.play(a_ ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: __UpperCAmelCase : Union[str, Any] = 0.7 self.play( Circumscribe(model_arr[i] , **a_ ) , Circumscribe(cpu_left_col_base[i] , **a_ ) , Circumscribe(cpu_left_col_base[i + 1] , color=a_ , **a_ ) , Circumscribe(gpu_rect[0] , color=a_ , **a_ ) , Circumscribe(model_arr[i + 1] , color=a_ , **a_ ) , ) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) , MoveToTarget(model_cpu_arr[i + 1] ) , ) else: self.play( MoveToTarget(model_cpu_arr[i] , run_time=0.7 ) , MoveToTarget(model_cpu_arr[i + 1] , run_time=0.7 ) , ) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() , RIGHT + 0.0_2 , buff=0.2 ) self.play( Circumscribe(model_arr[-1] , color=a_ , **a_ ) , Circumscribe(cpu_left_col_base[-1] , color=a_ , **a_ ) , Circumscribe(gpu_rect[0] , color=a_ , **a_ ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) __UpperCAmelCase : List[str] = a_c __UpperCAmelCase : int = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.0_2 , buff=0.5 ) self.play( FadeOut(a_ ) , FadeOut(a_ , run_time=0.5 ) , ) __UpperCAmelCase : List[str] = MarkupText(f"""Inference on a model too large for GPU memory\nis successfully completed.""" , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(a_ , run_time=3 ) , MoveToTarget(a_ ) ) self.wait()
168
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__=10 ): """simple docstring""" _UpperCAmelCase = [] for _ in range(UpperCamelCase__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__=10 ): """simple docstring""" _UpperCAmelCase = [] for step in range(UpperCamelCase__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase = os.path.join(UpperCamelCase__ , "schedule.bin" ) torch.save(scheduler.state_dict() , UpperCamelCase__ ) _UpperCAmelCase = torch.load(UpperCamelCase__ ) scheduler.load_state_dict(UpperCamelCase__ ) return lrs @require_torch class _lowerCAmelCase ( unittest.TestCase ): def _a ( self , a_ , a_ , a_ ) -> Optional[int]: self.assertEqual(len(a_ ) , len(a_ ) ) for a, b in zip(a_ , a_ ): self.assertAlmostEqual(a_ , a_ , delta=a_ ) def _a ( self ) -> str: _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=a_ ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(100 ): _UpperCAmelCase = criterion(a_ , a_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=a_ ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = Adafactor( params=[w] , lr=1e-2 , eps=(1e-30, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=a_ , weight_decay=0.0 , relative_step=a_ , scale_parameter=a_ , warmup_init=a_ , ) for _ in range(1000 ): _UpperCAmelCase = criterion(a_ , a_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class _lowerCAmelCase ( unittest.TestCase ): lowercase_ : List[Any] = nn.Linear(50 , 50 ) if is_torch_available() else None lowercase_ : Tuple = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None lowercase_ : Dict = 10 def _a ( self , a_ , a_ , a_ , a_=None ) -> Union[str, Any]: self.assertEqual(len(a_ ) , len(a_ ) ) for a, b in zip(a_ , a_ ): self.assertAlmostEqual(a_ , a_ , delta=a_ , msg=a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = {"num_warmup_steps": 2, "num_training_steps": 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _UpperCAmelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {"num_warmup_steps": 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, "num_cycles": 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, "power": 2.0, "lr_end": 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {"num_warmup_steps": 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _UpperCAmelCase , _UpperCAmelCase = data _UpperCAmelCase = scheduler_func(self.optimizer , **a_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _UpperCAmelCase = unwrap_schedule(a_ , self.num_steps ) self.assertListAlmostEqual( a_ , a_ , tol=1e-2 , msg=f"failed for {scheduler_func} in normal scheduler" , ) _UpperCAmelCase = scheduler_func(self.optimizer , **a_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(a_ ) # wrap to test picklability of the schedule _UpperCAmelCase = unwrap_and_save_reload_schedule(a_ , self.num_steps ) self.assertListEqual(a_ , a_ , msg=f"failed for {scheduler_func} in save and reload" ) class _lowerCAmelCase : def __init__( self , a_ ) -> Union[str, Any]: _UpperCAmelCase = fn def __call__( self , *a_ , **a_ ) -> Union[str, Any]: return self.fn(*a_ , **a_ ) @classmethod def _a ( self , a_ ) -> Dict: _UpperCAmelCase = list(map(self , scheduler.lr_lambdas ) )
657
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) UpperCamelCase__ = { 'configuration_speech_to_text': ['SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Speech2TextConfig'], 'processing_speech_to_text': ['Speech2TextProcessor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ['Speech2TextTokenizer'] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ['Speech2TextFeatureExtractor'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ 'TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFSpeech2TextForConditionalGeneration', 'TFSpeech2TextModel', 'TFSpeech2TextPreTrainedModel', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ 'SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Speech2TextForConditionalGeneration', 'Speech2TextModel', 'Speech2TextPreTrainedModel', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
620
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __lowerCamelCase ( UpperCamelCase__=None ): """simple docstring""" if subparsers is not None: _UpperCAmelCase = subparsers.add_parser("test" ) else: _UpperCAmelCase = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=UpperCamelCase__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=UpperCamelCase__ ) return parser def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: _UpperCAmelCase = script_name else: _UpperCAmelCase = f"--config_file={args.config_file} {script_name}" _UpperCAmelCase = ["accelerate-launch"] + test_args.split() _UpperCAmelCase = execute_subprocess_async(UpperCamelCase__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = test_command_parser() _UpperCAmelCase = parser.parse_args() test_command(UpperCamelCase__ ) if __name__ == "__main__": main()
657
0
class A__ : """simple docstring""" def __init__( self) -> Any: '''simple docstring''' a__ : Any = {} def __lowercase ( self) -> None: '''simple docstring''' print(self.vertex) for i in self.vertex: print(a_ , ' -> ' , ' -> '.join([str(a_) for j in self.vertex[i]])) def __lowercase ( self , lowercase , lowercase) -> None: '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(a_) else: # else make a new vertex a__ : Optional[Any] = [to_vertex] def __lowercase ( self) -> None: '''simple docstring''' a__ : int = [False] * len(self.vertex) # call the recursive helper function for i in range(len(self.vertex)): if not visited[i]: self.dfs_recursive(a_ , a_) def __lowercase ( self , lowercase , lowercase) -> None: '''simple docstring''' a__ : Any = True print(a_ , end=' ') # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(a_ , a_) if __name__ == "__main__": lowercase : Union[str, Any] = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("""DFS:""") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
302
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" return 10 - x * x def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) >= 0: raise ValueError("Wrong space!" ) _UpperCAmelCase = a while (b - a) >= 0.01: # Find middle point _UpperCAmelCase = (a + b) / 2 # Check if middle point is root if equation(UpperCamelCase__ ) == 0.0: break # Decide the side to repeat the steps if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) < 0: _UpperCAmelCase = c else: _UpperCAmelCase = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
657
0
'''simple docstring''' from sklearn.metrics import fa_score import datasets UpperCAmelCase_ : List[str] = '\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n' UpperCAmelCase_ : int = '\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {\'f1\': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results[\'f1\'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results[\'f1\'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")\n >>> print(round(results[\'f1\'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {\'f1\': array([0.8, 0. , 0. ])}\n' UpperCAmelCase_ : Any = '\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCamelCase ( datasets.Metric ): '''simple docstring''' def snake_case__ ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'] , ) def snake_case__ ( self , __lowercase , __lowercase , __lowercase=None , __lowercase=1 , __lowercase="binary" , __lowercase=None ): """simple docstring""" __A : str = fa_score( a_ , a_ , labels=a_ , pos_label=a_ , average=a_ , sample_weight=a_ ) return {"f1": float(a_ ) if score.size == 1 else score}
365
"""simple docstring""" from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): lowercase_ : Tuple = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self , a_ , a_ , a_ = None , a_ = 50257 , a_ = 1024 , a_ = 768 , a_ = 12 , a_ = 12 , a_ = None , a_ = "gelu_new" , a_ = 0.1 , a_ = 0.1 , a_ = 0.1 , a_ = 1e-5 , a_ = 0.02 , a_ = True , a_ = True , a_ = False , a_ = False , ) -> List[str]: super().__init__() _UpperCAmelCase = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f"`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and" f" `n_embd`: {n_embd} are not equal." ) _UpperCAmelCase = prefix_inner_dim _UpperCAmelCase = prefix_hidden_dim _UpperCAmelCase = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) _UpperCAmelCase = ( nn.Linear(self.prefix_hidden_dim , a_ ) if self.prefix_hidden_dim is not None else nn.Identity() ) _UpperCAmelCase = GPTaConfig( vocab_size=a_ , n_positions=a_ , n_embd=a_ , n_layer=a_ , n_head=a_ , n_inner=a_ , activation_function=a_ , resid_pdrop=a_ , embd_pdrop=a_ , attn_pdrop=a_ , layer_norm_epsilon=a_ , initializer_range=a_ , scale_attn_weights=a_ , use_cache=a_ , scale_attn_by_inverse_layer_idx=a_ , reorder_and_upcast_attn=a_ , ) _UpperCAmelCase = GPTaLMHeadModel(a_ ) def _a ( self , a_ , a_ , a_ = None , a_ = None , ) -> Tuple: _UpperCAmelCase = self.transformer.transformer.wte(a_ ) _UpperCAmelCase = self.encode_prefix(a_ ) _UpperCAmelCase = self.decode_prefix(a_ ) _UpperCAmelCase = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: _UpperCAmelCase = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) _UpperCAmelCase = torch.cat((dummy_token, input_ids) , dim=1 ) _UpperCAmelCase = self.transformer(inputs_embeds=a_ , labels=a_ , attention_mask=a_ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def _a ( self , a_ , a_ ) -> torch.Tensor: return torch.zeros(a_ , self.prefix_length , dtype=torch.intaa , device=a_ ) def _a ( self , a_ ) -> Union[str, Any]: return self.encode_prefix(a_ ) @torch.no_grad() def _a ( self , a_ , a_ , a_ ) -> Union[str, Any]: _UpperCAmelCase = torch.split(a_ , 1 , dim=0 ) _UpperCAmelCase = [] _UpperCAmelCase = [] for feature in features: _UpperCAmelCase = self.decode_prefix(feature.to(a_ ) ) # back to the clip feature # Only support beam search for now _UpperCAmelCase , _UpperCAmelCase = self.generate_beam( input_embeds=a_ , device=a_ , eos_token_id=a_ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) _UpperCAmelCase = torch.stack(a_ ) _UpperCAmelCase = torch.stack(a_ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def _a ( self , a_=None , a_=None , a_=None , a_ = 5 , a_ = 67 , a_ = 1.0 , a_ = None , ) -> Optional[Any]: _UpperCAmelCase = eos_token_id _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = torch.ones(a_ , device=a_ , dtype=torch.int ) _UpperCAmelCase = torch.zeros(a_ , device=a_ , dtype=torch.bool ) if input_embeds is not None: _UpperCAmelCase = input_embeds else: _UpperCAmelCase = self.transformer.transformer.wte(a_ ) for i in range(a_ ): _UpperCAmelCase = self.transformer(inputs_embeds=a_ ) _UpperCAmelCase = outputs.logits _UpperCAmelCase = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) _UpperCAmelCase = logits.softmax(-1 ).log() if scores is None: _UpperCAmelCase , _UpperCAmelCase = logits.topk(a_ , -1 ) _UpperCAmelCase = generated.expand(a_ , *generated.shape[1:] ) _UpperCAmelCase , _UpperCAmelCase = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: _UpperCAmelCase = next_tokens else: _UpperCAmelCase = tokens.expand(a_ , *tokens.shape[1:] ) _UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) else: _UpperCAmelCase = -float(np.inf ) _UpperCAmelCase = 0 _UpperCAmelCase = scores[:, None] + logits seq_lengths[~is_stopped] += 1 _UpperCAmelCase = scores_sum / seq_lengths[:, None] _UpperCAmelCase , _UpperCAmelCase = scores_sum_average.view(-1 ).topk(a_ , -1 ) _UpperCAmelCase = next_tokens // scores_sum.shape[1] _UpperCAmelCase = seq_lengths[next_tokens_source] _UpperCAmelCase = next_tokens % scores_sum.shape[1] _UpperCAmelCase = next_tokens.unsqueeze(1 ) _UpperCAmelCase = tokens[next_tokens_source] _UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) _UpperCAmelCase = generated[next_tokens_source] _UpperCAmelCase = scores_sum_average * seq_lengths _UpperCAmelCase = is_stopped[next_tokens_source] _UpperCAmelCase = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) _UpperCAmelCase = torch.cat((generated, next_token_embed) , dim=1 ) _UpperCAmelCase = is_stopped + next_tokens.eq(a_ ).squeeze() if is_stopped.all(): break _UpperCAmelCase = scores / seq_lengths _UpperCAmelCase = scores.argsort(descending=a_ ) # tokens tensors are already padded to max_seq_length _UpperCAmelCase = [tokens[i] for i in order] _UpperCAmelCase = torch.stack(a_ , dim=0 ) _UpperCAmelCase = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
657
0
'''simple docstring''' import fcntl import os import socket import torch import torch.distributed as dist def lowerCamelCase__ ( *A : Union[str, Any] ): '''simple docstring''' with open(UpperCamelCase__ , '''r''' ) as fh: fcntl.flock(UpperCamelCase__ , fcntl.LOCK_EX ) try: print(*UpperCamelCase__ ) finally: fcntl.flock(UpperCamelCase__ , fcntl.LOCK_UN ) _lowercase : Optional[int] = int(os.environ["""LOCAL_RANK"""]) torch.cuda.set_device(local_rank) _lowercase : Dict = torch.device("""cuda""", local_rank) _lowercase : str = socket.gethostname() _lowercase : Union[str, Any] = F"""[{hostname}-{local_rank}]""" try: # test distributed dist.init_process_group("""nccl""") dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank _lowercase : Optional[int] = dist.get_rank() _lowercase : str = dist.get_world_size() printflock(F"""{gpu} is OK (global rank: {rank}/{world_size})""") dist.barrier() if rank == 0: printflock(F"""pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}""") except Exception: printflock(F"""{gpu} is broken""") raise
210
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable __magic_name__ = {'''configuration_gpt_neox''': ['''GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXConfig''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''GPTNeoXTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXForCausalLM''', '''GPTNeoXForQuestionAnswering''', '''GPTNeoXForSequenceClassification''', '''GPTNeoXForTokenClassification''', '''GPTNeoXLayer''', '''GPTNeoXModel''', '''GPTNeoXPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
657
0
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable snake_case_ : Any = {"configuration_gpt_neox": ["GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXConfig"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : int = ["GPTNeoXTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Dict = [ "GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXForCausalLM", "GPTNeoXForQuestionAnswering", "GPTNeoXForSequenceClassification", "GPTNeoXForTokenClassification", "GPTNeoXLayer", "GPTNeoXModel", "GPTNeoXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys snake_case_ : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
488
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''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 _lowerCAmelCase ( lowerCamelCase ): lowercase_ : Union[str, Any] = '''convbert''' def __init__( self , a_=30522 , 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_=768 , a_=2 , a_=9 , a_=1 , a_=None , **a_ , ) -> Tuple: super().__init__( pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ , ) _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = embedding_size _UpperCAmelCase = head_ratio _UpperCAmelCase = conv_kernel_size _UpperCAmelCase = num_groups _UpperCAmelCase = classifier_dropout class _lowerCAmelCase ( lowerCamelCase ): @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _UpperCAmelCase = {0: "batch", 1: "choice", 2: "sequence"} else: _UpperCAmelCase = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
657
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer snake_case = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} snake_case = { """vocab_file""": { """google/electra-small-generator""": ( """https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt""" ), """google/electra-base-generator""": """https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt""", """google/electra-large-generator""": ( """https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt""" ), """google/electra-small-discriminator""": ( """https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt""" ), """google/electra-base-discriminator""": ( """https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt""" ), """google/electra-large-discriminator""": ( """https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """google/electra-small-generator""": ( """https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json""" ), """google/electra-base-generator""": ( """https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json""" ), """google/electra-large-generator""": ( """https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json""" ), """google/electra-small-discriminator""": ( """https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json""" ), """google/electra-base-discriminator""": ( """https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json""" ), """google/electra-large-discriminator""": ( """https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json""" ), }, } snake_case = { """google/electra-small-generator""": 512, """google/electra-base-generator""": 512, """google/electra-large-generator""": 512, """google/electra-small-discriminator""": 512, """google/electra-base-discriminator""": 512, """google/electra-large-discriminator""": 512, } snake_case = { """google/electra-small-generator""": {"""do_lower_case""": True}, """google/electra-base-generator""": {"""do_lower_case""": True}, """google/electra-large-generator""": {"""do_lower_case""": True}, """google/electra-small-discriminator""": {"""do_lower_case""": True}, """google/electra-base-discriminator""": {"""do_lower_case""": True}, """google/electra-large-discriminator""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[Any] = VOCAB_FILES_NAMES UpperCamelCase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : List[str] = PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Any = ElectraTokenizer def __init__( self : Optional[int] , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Optional[int]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : List[Any]="[PAD]" , UpperCAmelCase_ : Optional[Any]="[CLS]" , UpperCAmelCase_ : Optional[Any]="[MASK]" , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Any , ): super().__init__( a_ , tokenizer_file=a_ , do_lower_case=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , tokenize_chinese_chars=a_ , strip_accents=a_ , **a_ , ) SCREAMING_SNAKE_CASE : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , a_ ) != do_lower_case or normalizer_state.get("strip_accents" , a_ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , a_ ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : List[str] = getattr(a_ , normalizer_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = do_lower_case SCREAMING_SNAKE_CASE : int = strip_accents SCREAMING_SNAKE_CASE : List[str] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : List[Any] = normalizer_class(**a_ ) SCREAMING_SNAKE_CASE : Tuple = do_lower_case def _A ( self : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE : Tuple = [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 _A ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple = None ): SCREAMING_SNAKE_CASE : int = [self.sep_token_id] SCREAMING_SNAKE_CASE : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _A ( self : Any , UpperCAmelCase_ : Any , UpperCAmelCase_ : int = None ): SCREAMING_SNAKE_CASE : int = self._tokenizer.model.save(a_ , name=a_ ) return tuple(a_ )
62
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" return "".join([hex(UpperCamelCase__ )[2:].zfill(2 ).upper() for byte in list(UpperCamelCase__ )] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if (len(UpperCamelCase__ ) % 2) != 0: raise ValueError( "Base16 encoded data is invalid:\nData does not have an even number of hex digits." ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(UpperCamelCase__ ) <= set("0123456789ABCDEF" ): raise ValueError( "Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters." ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(UpperCamelCase__ ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
657
0
def lowercase__( A ): snake_case__ : Optional[Any] = len(UpperCamelCase__ ) snake_case__ : Any = len(matrix[0] ) snake_case__ : Tuple = min(UpperCamelCase__ , UpperCamelCase__ ) for row in range(UpperCamelCase__ ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , UpperCamelCase__ ): snake_case__ : Any = matrix[col][row] / matrix[row][row] for i in range(UpperCamelCase__ , UpperCamelCase__ ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows snake_case__ : List[Any] = True for i in range(row + 1 , UpperCamelCase__ ): if matrix[i][row] != 0: snake_case__ , snake_case__ : Union[str, Any] = matrix[i], matrix[row] snake_case__ : List[Any] = False break if reduce: rank -= 1 for i in range(UpperCamelCase__ ): snake_case__ : List[Any] = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
170
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" try: _UpperCAmelCase = float(UpperCamelCase__ ) except ValueError: raise ValueError("Please enter a valid number" ) _UpperCAmelCase = decimal - int(UpperCamelCase__ ) if fractional_part == 0: return int(UpperCamelCase__ ), 1 else: _UpperCAmelCase = len(str(UpperCamelCase__ ).split("." )[1] ) _UpperCAmelCase = int(decimal * (10**number_of_frac_digits) ) _UpperCAmelCase = 10**number_of_frac_digits _UpperCAmelCase , _UpperCAmelCase = denominator, numerator while True: _UpperCAmelCase = dividend % divisor if remainder == 0: break _UpperCAmelCase , _UpperCAmelCase = divisor, remainder _UpperCAmelCase , _UpperCAmelCase = numerator / divisor, denominator / divisor return int(UpperCamelCase__ ), int(UpperCamelCase__ ) if __name__ == "__main__": print(f'''{decimal_to_fraction(2) = }''') print(f'''{decimal_to_fraction(89.0) = }''') print(f'''{decimal_to_fraction("67") = }''') print(f'''{decimal_to_fraction("45.0") = }''') print(f'''{decimal_to_fraction(1.5) = }''') print(f'''{decimal_to_fraction("6.25") = }''') print(f'''{decimal_to_fraction("78td") = }''')
657
0
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ : List[str] = params snake_case_ : Dict = np.array(a_ ) snake_case_ : Optional[int] = np.array([len(a_ ) 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 , _SCREAMING_SNAKE_CASE ) -> Any: return (self.token_ids[index], self.lengths[index]) def __len__( self ) -> List[Any]: return len(self.lengths ) def _lowerCAmelCase ( self ) -> Optional[int]: 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 _lowerCAmelCase ( self ) -> Union[str, Any]: snake_case_ : str = self.params.max_model_input_size snake_case_ : Optional[Any] = self.lengths > max_len logger.info(f'''Splitting {sum(a_ )} too long sequences.''' ) def divide_chunks(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return [l[i : i + n] for i in range(0 , len(a_ ) , a_ )] snake_case_ : Union[str, Any] = [] snake_case_ : int = [] if self.params.mlm: snake_case_ , snake_case_ : Tuple = self.params.special_tok_ids["cls_token"], self.params.special_tok_ids["sep_token"] else: snake_case_ , snake_case_ : List[Any] = 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: snake_case_ : Any = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: snake_case_ : str = np.insert(a_ , 0 , a_ ) if sub_s[-1] != sep_id: snake_case_ : Tuple = np.insert(a_ , len(a_ ) , a_ ) assert len(a_ ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(a_ ) new_tok_ids.extend(a_ ) new_lengths.extend([len(a_ ) for l in sub_seqs] ) snake_case_ : int = np.array(a_ ) snake_case_ : Optional[Any] = np.array(a_ ) def _lowerCAmelCase ( self ) -> List[Any]: snake_case_ : List[Any] = len(self ) snake_case_ : Tuple = self.lengths > 11 snake_case_ : Optional[Any] = self.token_ids[indices] snake_case_ : str = self.lengths[indices] snake_case_ : Any = len(self ) logger.info(f'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def _lowerCAmelCase ( self ) -> Dict: if "unk_token" not in self.params.special_tok_ids: return else: snake_case_ : int = self.params.special_tok_ids["unk_token"] snake_case_ : List[str] = len(self ) snake_case_ : int = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) snake_case_ : List[str] = (unk_occs / self.lengths) < 0.5 snake_case_ : Dict = self.token_ids[indices] snake_case_ : Optional[int] = self.lengths[indices] snake_case_ : List[Any] = len(self ) logger.info(f'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def _lowerCAmelCase ( self ) -> Optional[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 _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE ) -> Dict: snake_case_ : Union[str, Any] = [t[0] for t in batch] snake_case_ : Optional[int] = [t[1] for t in batch] assert len(a_ ) == len(a_ ) # Max for paddings snake_case_ : Union[str, Any] = max(a_ ) # Pad token ids if self.params.mlm: snake_case_ : int = self.params.special_tok_ids["pad_token"] else: snake_case_ : Any = self.params.special_tok_ids["unk_token"] snake_case_ : List[Any] = [list(t.astype(a_ ) ) + [pad_idx] * (max_seq_len_ - len(a_ )) for t in token_ids] assert len(tk_ ) == len(a_ ) assert all(len(a_ ) == max_seq_len_ for t in tk_ ) snake_case_ : int = torch.tensor(tk_ ) # (bs, max_seq_len_) snake_case_ : List[str] = torch.tensor(a_ ) # (bs) return tk_t, lg_t
568
"""simple docstring""" # Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, nicht wahr?", } # BLUE scores as follows: # "pair": [fairseq, transformers] _UpperCAmelCase = { "wmt16-en-de-dist-12-1": [28.3, 27.52], "wmt16-en-de-dist-6-1": [27.4, 27.11], "wmt16-en-de-12-1": [26.9, 25.75], } _UpperCAmelCase = f"{src_lang}-{tgt_lang}" _UpperCAmelCase = f"\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"allenai/{model_name}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel | fairseq | transformers\n-------|---------|----------\n{model_name} | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don't use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n year={{2020}},\n eprint={{2006.10369}},\n archivePrefix={{arXiv}},\n primaryClass={{cs.CL}}\n}}\n```\n\n" model_card_dir.mkdir(parents=UpperCamelCase__ , exist_ok=UpperCamelCase__ ) _UpperCAmelCase = os.path.join(UpperCamelCase__ , "README.md" ) print(f"Generating {path}" ) with open(UpperCamelCase__ , "w" , encoding="utf-8" ) as f: f.write(UpperCamelCase__ ) # make sure we are under the root of the project __magic_name__ = Path(__file__).resolve().parent.parent.parent __magic_name__ = repo_dir / '''model_cards''' for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: __magic_name__ = model_cards_dir / '''allenai''' / model_name write_model_card(model_card_dir, src_lang='''en''', tgt_lang='''de''', model_name=model_name)
657
0
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging UpperCAmelCase__ = logging.get_logger(__name__) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = ['''input_features''', '''is_longer'''] def __init__( self : Union[str, Any] , __UpperCAmelCase : int=64 , __UpperCAmelCase : Any=48_000 , __UpperCAmelCase : Optional[Any]=480 , __UpperCAmelCase : Optional[int]=10 , __UpperCAmelCase : List[str]=1_024 , __UpperCAmelCase : List[Any]=0.0 , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Union[str, Any] = 0 , __UpperCAmelCase : Optional[Any] = 14_000 , __UpperCAmelCase : List[Any] = None , __UpperCAmelCase : Tuple = "fusion" , __UpperCAmelCase : Union[str, Any] = "repeatpad" , **__UpperCAmelCase : List[str] , ) ->Optional[Any]: """simple docstring""" super().__init__( feature_size=a_ , sampling_rate=a_ , padding_value=a_ , return_attention_mask=a_ , **a_ , ) a = top_db a = truncation a = padding a = fft_window_size a = (fft_window_size >> 1) + 1 a = hop_length a = max_length_s a = max_length_s * sampling_rate a = sampling_rate a = frequency_min a = frequency_max a = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=a_ , min_frequency=a_ , max_frequency=a_ , sampling_rate=a_ , norm=a_ , mel_scale='''htk''' , ) a = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=a_ , min_frequency=a_ , max_frequency=a_ , sampling_rate=a_ , norm='''slaney''' , mel_scale='''slaney''' , ) def __lowerCAmelCase ( self : Optional[int] ) ->Dict[str, Any]: """simple docstring""" a = copy.deepcopy(self.__dict__ ) a = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def __lowerCAmelCase ( self : str , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[int] = None ) ->np.ndarray: """simple docstring""" a = spectrogram( a_ , window_function(self.fft_window_size , '''hann''' ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=a_ , log_mel='''dB''' , ) return log_mel_spectrogram.T def __lowerCAmelCase ( self : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[int] ) ->Tuple: """simple docstring""" a = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk a = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk a = [0] # randomly choose index for each part a = np.random.choice(ranges[0] ) a = np.random.choice(ranges[1] ) a = np.random.choice(ranges[2] ) a = mel[idx_front : idx_front + chunk_frames, :] a = mel[idx_middle : idx_middle + chunk_frames, :] a = mel[idx_back : idx_back + chunk_frames, :] a = torch.tensor(mel[None, None, :] ) a = torch.nn.functional.interpolate( a_ , size=[chunk_frames, 64] , mode='''bilinear''' , align_corners=a_ ) a = mel_shrink[0][0].numpy() a = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str] ) ->np.array: """simple docstring""" if waveform.shape[0] > max_length: if truncation == "rand_trunc": a = True # random crop to max_length (for compatibility) -> this should be handled by self.pad a = len(a_ ) - max_length a = np.random.randint(0 , overflow + 1 ) a = waveform[idx : idx + max_length] a = self._np_extract_fbank_features(a_ , self.mel_filters_slaney )[None, :] elif truncation == "fusion": a = self._np_extract_fbank_features(a_ , self.mel_filters ) a = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed a = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. a = np.stack([mel, mel, mel, mel] , axis=0 ) a = False else: a = self._random_mel_fusion(a_ , a_ , a_ ) a = True else: raise NotImplementedError(F"""data_truncating {truncation} not implemented""" ) else: a = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": a = int(max_length / len(a_ ) ) a = np.stack(np.tile(a_ , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": a = int(max_length / len(a_ ) ) a = np.stack(np.tile(a_ , a_ ) ) a = np.pad(a_ , (0, max_length - waveform.shape[0]) , mode='''constant''' , constant_values=0 ) if truncation == "fusion": a = self._np_extract_fbank_features(a_ , self.mel_filters ) a = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: a = self._np_extract_fbank_features(a_ , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self : List[str] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Tuple = None , __UpperCAmelCase : Union[str, Any] = None , __UpperCAmelCase : Any = None , __UpperCAmelCase : Optional[Any] = None , __UpperCAmelCase : Optional[Any] = None , **__UpperCAmelCase : Optional[int] , ) ->BatchFeature: """simple docstring""" a = truncation if truncation is not None else self.truncation a = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a""" F""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input""" F""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) a = isinstance(a_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F"""Only mono-channel audio is supported for input to {self}""" ) a = is_batched_numpy or ( isinstance(a_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: a = [np.asarray(a_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(a_ , np.ndarray ): a = np.asarray(a_ , dtype=np.floataa ) elif isinstance(a_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): a = raw_speech.astype(np.floataa ) # always return batch if not is_batched: a = [np.asarray(a_ )] # convert to mel spectrogram, truncate and pad if needed. a = [ self._get_input_mel(a_ , max_length if max_length else self.nb_max_samples , a_ , a_ ) for waveform in raw_speech ] a = [] a = [] for mel, longer in padded_inputs: input_mel.append(a_ ) is_longer.append(a_ ) if truncation == "fusion" and sum(a_ ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer a = np.random.randint(0 , len(a_ ) ) a = True if isinstance(input_mel[0] , a_ ): a = [np.asarray(a_ , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool a = [[longer] for longer in is_longer] a = {'''input_features''': input_mel, '''is_longer''': is_longer} a = BatchFeature(a_ ) if return_tensors is not None: a = input_features.convert_to_tensors(a_ ) return input_features
117
"""simple docstring""" from ..utils import DummyObject, requires_backends class _lowerCAmelCase ( metaclass=lowerCamelCase ): lowercase_ : Dict = ['''torch''', '''torchsde'''] def __init__( self , *a_ , **a_ ) -> Optional[int]: requires_backends(self , ["torch", "torchsde"] ) @classmethod def _a ( cls , *a_ , **a_ ) -> Optional[Any]: requires_backends(cls , ["torch", "torchsde"] ) @classmethod def _a ( cls , *a_ , **a_ ) -> List[Any]: requires_backends(cls , ["torch", "torchsde"] )
657
0
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging A = logging.get_logger(__name__) def __UpperCAmelCase ( __A=None , __A=None ) -> str: '''simple docstring''' return field(default_factory=lambda: default , metadata=UpperCamelCase__ ) @dataclass class lowercase__ : A__= list_field( default=[] , metadata={ 'help': ( 'Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version' ' of all available models' ) } , ) A__= list_field( default=[8] , metadata={'help': 'List of batch sizes for which memory and time performance will be evaluated'} ) A__= list_field( default=[8, 32, 128, 512] , metadata={'help': 'List of sequence lengths for which memory and time performance will be evaluated'} , ) A__= field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to benchmark inference of model. Inference can be disabled via --no-inference.'} , ) A__= field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'} , ) A__= field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'} ) A__= field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Use FP16 to accelerate inference.'} ) A__= field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Benchmark training of model'} ) A__= field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Verbose memory tracing'} ) A__= field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'} , ) A__= field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': 'Whether to perform memory measurements. Memory measurements can be disabled via --no-memory' } , ) A__= field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Trace memory line by line'} ) A__= field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Save result to a CSV file'} ) A__= field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Save all print statements in a log file'} ) A__= field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to print environment information'} ) A__= field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use' ' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled' ' for debugging / testing and on TPU.' ) } , ) A__= field( default=f'inference_time_{round(time() )}.csv' , metadata={'help': 'CSV filename used if saving time results to csv.'} , ) A__= field( default=f'inference_memory_{round(time() )}.csv' , metadata={'help': 'CSV filename used if saving memory results to csv.'} , ) A__= field( default=f'train_time_{round(time() )}.csv' , metadata={'help': 'CSV filename used if saving time results to csv for training.'} , ) A__= field( default=f'train_memory_{round(time() )}.csv' , metadata={'help': 'CSV filename used if saving memory results to csv for training.'} , ) A__= field( default=f'env_info_{round(time() )}.csv' , metadata={'help': 'CSV filename used if saving environment information.'} , ) A__= field( default=f'log_{round(time() )}.csv' , metadata={'help': 'Log filename used if print statements are saved in log.'} , ) A__= field(default=3 , metadata={'help': 'Times an experiment will be run.'} ) A__= field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain' ' model weights.' ) } , ) def _UpperCAmelCase ( self : str ): """simple docstring""" warnings.warn( F"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils""" " are deprecated in general and it is advised to use external Benchmarking libraries " " to benchmark Transformer models." , a_ , ) def _UpperCAmelCase ( self : Dict ): """simple docstring""" return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def _UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" if len(self.models ) <= 0: raise ValueError( "Please make sure you provide at least one model name / model identifier, *e.g.* `--models" " bert-base-cased` or `args.models = ['bert-base-cased']." ) return self.models @property def _UpperCAmelCase ( self : int ): """simple docstring""" if not self.multi_process: return False elif self.is_tpu: logger.info("Multiprocessing is currently not possible on TPU." ) return False else: return True
475
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __magic_name__ = logging.get_logger(__name__) class _lowerCAmelCase ( lowerCamelCase ): lowercase_ : Optional[Any] = '''upernet''' def __init__( self , a_=None , a_=512 , a_=0.02 , a_=[1, 2, 3, 6] , a_=True , a_=0.4 , a_=384 , a_=256 , a_=1 , a_=False , a_=255 , **a_ , ) -> List[Any]: super().__init__(**a_ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) _UpperCAmelCase = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(a_ , a_ ): _UpperCAmelCase = backbone_config.get("model_type" ) _UpperCAmelCase = CONFIG_MAPPING[backbone_model_type] _UpperCAmelCase = config_class.from_dict(a_ ) _UpperCAmelCase = backbone_config _UpperCAmelCase = hidden_size _UpperCAmelCase = initializer_range _UpperCAmelCase = pool_scales _UpperCAmelCase = use_auxiliary_head _UpperCAmelCase = auxiliary_loss_weight _UpperCAmelCase = auxiliary_in_channels _UpperCAmelCase = auxiliary_channels _UpperCAmelCase = auxiliary_num_convs _UpperCAmelCase = auxiliary_concat_input _UpperCAmelCase = loss_ignore_index def _a ( self ) -> int: _UpperCAmelCase = copy.deepcopy(self.__dict__ ) _UpperCAmelCase = self.backbone_config.to_dict() _UpperCAmelCase = self.__class__.model_type return output
657
0
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _a : Dict = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class __A (__magic_name__ , unittest.TestCase ): snake_case :str = XLNetTokenizer snake_case :Optional[int] = XLNetTokenizerFast snake_case :Tuple = True snake_case :Optional[Any] = True def _snake_case ( self ): super().setUp() # We have a SentencePiece fixture for testing __UpperCAmelCase : Optional[int] = XLNetTokenizer(a_ , keep_accents=a_ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self ): __UpperCAmelCase : List[Any] = "<s>" __UpperCAmelCase : Dict = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def _snake_case ( self ): __UpperCAmelCase : Dict = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(a_ ) , 10_06 ) def _snake_case ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 10_00 ) def _snake_case ( self ): __UpperCAmelCase : List[str] = XLNetTokenizer(a_ , keep_accents=a_ ) __UpperCAmelCase : str = tokenizer.tokenize("This is a test" ) self.assertListEqual(a_ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [2_85, 46, 10, 1_70, 3_82] ) __UpperCAmelCase : Dict = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( a_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) __UpperCAmelCase : int = tokenizer.convert_tokens_to_ids(a_ ) self.assertListEqual(a_ , [8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) __UpperCAmelCase : List[Any] = tokenizer.convert_ids_to_tokens(a_ ) self.assertListEqual( a_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def _snake_case ( self ): __UpperCAmelCase : Optional[Any] = XLNetTokenizer(a_ , do_lower_case=a_ ) __UpperCAmelCase : Optional[int] = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( a_ , [ SPIECE_UNDERLINE + "", "i", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def _snake_case ( self ): __UpperCAmelCase : Dict = XLNetTokenizer(a_ , do_lower_case=a_ ) __UpperCAmelCase : Tuple = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( a_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "se", ".", ] , ) @slow def _snake_case ( self ): __UpperCAmelCase : str = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) __UpperCAmelCase : Tuple = tokenizer.encode("sequence builders" , add_special_tokens=a_ ) __UpperCAmelCase : List[str] = tokenizer.encode("multi-sequence build" , add_special_tokens=a_ ) __UpperCAmelCase : Dict = tokenizer.build_inputs_with_special_tokens(a_ ) __UpperCAmelCase : Optional[int] = tokenizer.build_inputs_with_special_tokens(a_ , a_ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def _snake_case ( self ): # fmt: off __UpperCAmelCase : Any = {"input_ids": [[17, 2_14_42, 2_70, 17, 10, 1_46_45, 3_18, 34, 17, 45_46, 31_45, 7_87, 13, 77_52, 2_20_18, 23, 21, 17, 45_46, 31_45, 7_87, 13, 33_52, 1_44_31, 13, 55_00, 11, 11_76, 5_80, 13, 1_68_19, 47_97, 23, 17, 10, 1_71_35, 6_58, 19, 4_57, 79_32, 13, 1_84, 19, 31_54, 1_71_35, 64_68, 19, 14_04, 1_22_69, 19, 42_29, 53_56, 1_62_64, 46, 19, 17, 2_05_45, 1_03_95, 9, 9, 9, 11, 28, 64_21, 95_31, 2_07_29, 17, 10, 3_53, 1_70_22, 11, 21, 64_21, 95_31, 1_69_49, 17, 10, 1_15_09, 7_53, 11, 33, 95, 24_21, 73_85, 9_56, 1_44_31, 26_26, 25, 8_42, 73_85, 48_36, 21, 14_29, 22_72, 98_55, 31_20, 1_61, 2_47_38, 19, 1_32_03, 6_58, 2_18, 7_87, 21, 4_30, 1_84_82, 8_47, 26_37, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3_22, 2_21_78, 27, 10_64, 22, 9_56, 13, 1_11_01, 14_29, 58_54, 2_43_13, 1_89_53, 40, 4_22, 2_43_66, 68, 17_58, 37, 1_04_83, 1_42_57, 31, 2_07, 2_63, 21, 2_03, 37_73, 25, 71, 97_35, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 20_49, 34_42, 17, 1_38_94, 33_80, 23, 95, 18, 1_76_34, 22_88, 9, 4, 3]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
168
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import _LazyModule __magic_name__ = {'''tokenization_tapex''': ['''TapexTokenizer''']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
657
0
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand UpperCamelCase__ = ( '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__ = ( ('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__ = ( ('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__ = ( ('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__ = ( ('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__ = ( ('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__ = ( ('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 __SCREAMING_SNAKE_CASE ( ): """simple docstring""" lowercase_ , lowercase_ : Union[str, Any] = randrange(len(UpperCamelCase__ ) ), randrange(len(UpperCamelCase__ ) ) lowercase_ : Optional[int] = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] lowercase_ , lowercase_ : Tuple = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def __SCREAMING_SNAKE_CASE ( _UpperCamelCase = 100 ): """simple docstring""" return (generate_random_hand() for _ in range(UpperCamelCase__ )) @pytest.mark.parametrize("hand, expected" , UpperCamelCase__ ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" assert PokerHand(UpperCamelCase__ )._is_flush() == expected @pytest.mark.parametrize("hand, expected" , UpperCamelCase__ ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" assert PokerHand(UpperCamelCase__ )._is_straight() == expected @pytest.mark.parametrize("hand, expected, card_values" , UpperCamelCase__ ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" lowercase_ : List[Any] = PokerHand(UpperCamelCase__ ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("hand, expected" , UpperCamelCase__ ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" assert PokerHand(UpperCamelCase__ )._is_same_kind() == expected @pytest.mark.parametrize("hand, expected" , UpperCamelCase__ ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase ): """simple docstring""" assert PokerHand(UpperCamelCase__ )._hand_type == expected @pytest.mark.parametrize("hand, other, expected" , UpperCamelCase__ ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" assert PokerHand(UpperCamelCase__ ).compare_with(PokerHand(UpperCamelCase__ ) ) == expected @pytest.mark.parametrize("hand, other, expected" , generate_random_hands() ) def __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" assert PokerHand(UpperCamelCase__ ).compare_with(PokerHand(UpperCamelCase__ ) ) == expected def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" lowercase_ : str = [PokerHand(UpperCamelCase__ ) for hand in SORTED_HANDS] lowercase_ : Any = poker_hands.copy() shuffle(UpperCamelCase__ ) lowercase_ : Optional[int] = chain(sorted(UpperCamelCase__ ) ) for index, hand in enumerate(UpperCamelCase__ ): assert hand == poker_hands[index] def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" lowercase_ : List[str] = [PokerHand("2D AC 3H 4H 5S" ), PokerHand("2S 3H 4H 5S 6C" )] pokerhands.sort(reverse=UpperCamelCase__ ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" lowercase_ : Tuple = PokerHand("2C 4S AS 3D 5C" ) lowercase_ : List[str] = True lowercase_ : Tuple = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" lowercase_ : Optional[int] = 0 lowercase_ : Optional[int] = os.path.abspath(os.path.dirname(UpperCamelCase__ ) ) lowercase_ : Dict = os.path.join(UpperCamelCase__ , "poker_hands.txt" ) with open(UpperCamelCase__ ) as file_hand: for line in file_hand: lowercase_ : List[str] = line[:14].strip() lowercase_ : Any = line[15:].strip() lowercase_ , lowercase_ : Any = PokerHand(UpperCamelCase__ ), PokerHand(UpperCamelCase__ ) lowercase_ : Optional[int] = player.compare_with(UpperCamelCase__ ) if output == "Win": answer += 1 assert answer == 376
620
"""simple docstring""" import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase : def __init__( self , a_ , a_=2 , a_=3 , a_=4 , a_=2 , a_=7 , a_=True , a_=True , a_=True , a_=True , a_=99 , a_=36 , a_=3 , a_=4 , a_=37 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=16 , a_=2 , a_=0.02 , a_=6 , a_=6 , a_=3 , a_=4 , a_=None , a_=1000 , ) -> Optional[Any]: _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = text_seq_length _UpperCAmelCase = is_training _UpperCAmelCase = use_input_mask _UpperCAmelCase = use_token_type_ids _UpperCAmelCase = use_labels _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = coordinate_size _UpperCAmelCase = shape_size _UpperCAmelCase = num_labels _UpperCAmelCase = num_choices _UpperCAmelCase = scope _UpperCAmelCase = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) _UpperCAmelCase = text_seq_length _UpperCAmelCase = (image_size // patch_size) ** 2 + 1 _UpperCAmelCase = self.text_seq_length + self.image_seq_length def _a ( self ) -> Dict: _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_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]: _UpperCAmelCase = bbox[i, j, 3] _UpperCAmelCase = bbox[i, j, 1] _UpperCAmelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: _UpperCAmelCase = bbox[i, j, 2] _UpperCAmelCase = bbox[i, j, 0] _UpperCAmelCase = t _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_input_mask: _UpperCAmelCase = random_attention_mask([self.batch_size, self.text_seq_length] ) _UpperCAmelCase = None if self.use_token_type_ids: _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) _UpperCAmelCase = None _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) _UpperCAmelCase = LayoutLMvaConfig( 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 , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Tuple: _UpperCAmelCase = LayoutLMvaModel(config=a_ ) model.to(a_ ) model.eval() # text + image _UpperCAmelCase = model(a_ , pixel_values=a_ ) _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ , bbox=a_ , pixel_values=a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ , bbox=a_ , pixel_values=a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only _UpperCAmelCase = model(a_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only _UpperCAmelCase = model(pixel_values=a_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Optional[Any]: _UpperCAmelCase = self.num_labels _UpperCAmelCase = LayoutLMvaForSequenceClassification(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Union[str, Any]: _UpperCAmelCase = self.num_labels _UpperCAmelCase = LayoutLMvaForTokenClassification(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Dict: _UpperCAmelCase = LayoutLMvaForQuestionAnswering(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , start_positions=a_ , end_positions=a_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _a ( self ) -> Optional[int]: _UpperCAmelCase = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = config_and_inputs _UpperCAmelCase = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase_ : Any = False lowercase_ : Dict = False lowercase_ : List[str] = False lowercase_ : str = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) lowercase_ : int = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def _a ( self , a_ , a_ , a_ , a_ , a_ ) -> List[str]: # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = LayoutLMvaModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=a_ , hidden_size=37 ) def _a ( self , a_ , a_ , a_=False ) -> List[str]: _UpperCAmelCase = copy.deepcopy(a_ ) if model_class in get_values(a_ ): _UpperCAmelCase = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(a_ , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a_ ): _UpperCAmelCase = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in get_values(a_ ): _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in [ *get_values(a_ ), ]: _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in [ *get_values(a_ ), ]: _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=a_ , ) return inputs_dict def _a ( self ) -> int: self.config_tester.run_common_tests() def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _UpperCAmelCase = type self.model_tester.create_and_check_model(*a_ ) def _a ( self ) -> int: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a_ ) def _a ( self ) -> Any: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) @slow def _a ( self ) -> List[str]: for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = LayoutLMvaModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class _lowerCAmelCase ( unittest.TestCase ): @cached_property def _a ( self ) -> List[Any]: return LayoutLMvaImageProcessor(apply_ocr=a_ ) if is_vision_available() else None @slow def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ).to(a_ ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=a_ , return_tensors="pt" ).pixel_values.to(a_ ) _UpperCAmelCase = torch.tensor([[1, 2]] ) _UpperCAmelCase = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass _UpperCAmelCase = model( input_ids=input_ids.to(a_ ) , bbox=bbox.to(a_ ) , pixel_values=pixel_values.to(a_ ) , ) # verify the logits _UpperCAmelCase = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , a_ ) _UpperCAmelCase = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(a_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , a_ , atol=1e-4 ) )
657
0
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor lowercase : Any = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def A_ ( A__ ) -> Optional[Any]: if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): a__ : List[str] = [image] a__ : str = [trans(img.convert('RGB' ) ) for img in image] a__ : str = torch.stack(UpperCamelCase__ ) return image class A__ ( __UpperCAmelCase ): """simple docstring""" def __init__( self , lowercase , lowercase) -> List[str]: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM a__ : List[Any] = DDIMScheduler.from_config(scheduler.config) self.register_modules(unet=a_ , scheduler=a_) def __lowercase ( self , lowercase) -> str: '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F'The value of strength should in [0.0, 1.0] but is {strength}') def __lowercase ( self , lowercase , lowercase , lowercase) -> str: '''simple docstring''' a__ : Optional[Any] = min(int(num_inference_steps * strength) , a_) a__ : Dict = max(num_inference_steps - init_timestep , 0) a__ : Optional[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase=None) -> Optional[Any]: '''simple docstring''' if not isinstance(a_ , (torch.Tensor, PIL.Image.Image, list)): raise ValueError( F'`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(a_)}') a__ : Any = image.to(device=a_ , dtype=a_) if isinstance(a_ , a_) and len(a_) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(a_)}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.') a__ : Dict = init_latents.shape a__ : Optional[int] = randn_tensor(a_ , generator=a_ , device=a_ , dtype=a_) # get latents print('add noise to latents at timestep' , a_) a__ : Optional[int] = self.scheduler.add_noise(a_ , a_ , a_) a__ : Tuple = init_latents return latents @torch.no_grad() def __call__( self , lowercase = None , lowercase = 0.8 , lowercase = 1 , lowercase = None , lowercase = 0.0 , lowercase = 50 , lowercase = None , lowercase = "pil" , lowercase = True , ) -> Union[ImagePipelineOutput, Tuple]: '''simple docstring''' self.check_inputs(a_) # 2. Preprocess image a__ : List[str] = preprocess(a_) # 3. set timesteps self.scheduler.set_timesteps(a_ , device=self.device) a__ , a__ : Dict = self.get_timesteps(a_ , a_ , self.device) a__ : Dict = timesteps[:1].repeat(a_) # 4. Prepare latent variables a__ : str = self.prepare_latents(a_ , a_ , a_ , self.unet.dtype , self.device , a_) a__ : str = latents # 5. Denoising loop for t in self.progress_bar(a_): # 1. predict noise model_output a__ : int = self.unet(a_ , a_).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 a__ : List[str] = self.scheduler.step( a_ , a_ , a_ , eta=a_ , use_clipped_model_output=a_ , generator=a_ , ).prev_sample a__ : List[Any] = (image / 2 + 0.5).clamp(0 , 1) a__ : Dict = image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": a__ : List[Any] = self.numpy_to_pil(a_) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=a_)
302
"""simple docstring""" import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class _lowerCAmelCase ( unittest.TestCase ): lowercase_ : str = MODEL_FOR_MASKED_LM_MAPPING lowercase_ : List[str] = TF_MODEL_FOR_MASKED_LM_MAPPING def _a ( self ) -> Optional[Any]: super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def _a ( self ) -> str: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="tf" ) _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is grouped", "score": 2.1e-05, "token": 38015, "token_str": " grouped"}, {"sequence": "My name is accuser", "score": 2.1e-05, "token": 25506, "token_str": " accuser"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ { "sequence": "The largest city in France is grouped", "score": 2.1e-05, "token": 38015, "token_str": " grouped", }, { "sequence": "The largest city in France is accuser", "score": 2.1e-05, "token": 25506, "token_str": " accuser", }, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, {"sequence": "My name is Patrick", "score": 2e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 1.9e-05, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="pt" ) _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul"}, {"sequence": "My name isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ { "sequence": "The largest city in France is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul", }, {"sequence": "The largest city in France isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Patrick", "score": 2.1e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 2e-05, "token": 2941, "token_str": " Te"}, {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, ] , ) _UpperCAmelCase = unmasker("My name is <mask> <mask>" , top_k=2 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ [ { "score": 2.2e-05, "token": 35676, "token_str": " Maul", "sequence": "<s>My name is Maul<mask></s>", }, {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name isELS<mask></s>"}, ], [ { "score": 2.2e-05, "token": 35676, "token_str": " Maul", "sequence": "<s>My name is<mask> Maul</s>", }, {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name is<mask>ELS</s>"}, ], ] , ) @require_torch_gpu def _a ( self ) -> int: _UpperCAmelCase = pipeline("fill-mask" , model="hf-internal-testing/tiny-random-distilbert" , device=0 , framework="pt" ) # convert model to fp16 pipe.model.half() _UpperCAmelCase = pipe("Paris is the [MASK] of France." ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(a_ , a_ ) @slow @require_torch def _a ( self ) -> int: _UpperCAmelCase = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="pt" ) self.run_large_test(a_ ) @slow @require_tf def _a ( self ) -> int: _UpperCAmelCase = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="tf" ) self.run_large_test(a_ ) def _a ( self , a_ ) -> int: _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ ) , [ {"sequence": "My name is John", "score": 0.008, "token": 610, "token_str": " John"}, {"sequence": "My name is Chris", "score": 0.007, "token": 1573, "token_str": " Chris"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ ) , [ { "sequence": "The largest city in France is Paris", "score": 0.251, "token": 2201, "token_str": " Paris", }, { "sequence": "The largest city in France is Lyon", "score": 0.214, "token": 12790, "token_str": " Lyon", }, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ ) , [ {"sequence": "My name is Patrick", "score": 0.005, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Clara", "score": 0.000, "token": 13606, "token_str": " Clara"}, {"sequence": "My name is Te", "score": 0.000, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _a ( self ) -> Any: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="pt" ) _UpperCAmelCase = None _UpperCAmelCase = None self.run_pipeline_test(a_ , [] ) @require_tf def _a ( self ) -> List[Any]: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="tf" ) _UpperCAmelCase = None _UpperCAmelCase = None self.run_pipeline_test(a_ , [] ) def _a ( self , a_ , a_ , a_ ) -> Optional[Any]: if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("The provided tokenizer has no mask token, (probably reformer or wav2vec2)" ) _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = [ f"This is another {tokenizer.mask_token} test", ] return fill_masker, examples def _a ( self , a_ , a_ ) -> List[str]: _UpperCAmelCase = fill_masker.tokenizer _UpperCAmelCase = fill_masker.model _UpperCAmelCase = fill_masker( f"This is a {tokenizer.mask_token}" , ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = fill_masker([f"This is a {tokenizer.mask_token}"] ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = fill_masker([f"This is a {tokenizer.mask_token}", f"Another {tokenizer.mask_token} great test."] ) self.assertEqual( a_ , [ [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], ] , ) with self.assertRaises(a_ ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(a_ ): fill_masker("This is" ) self.run_test_top_k(a_ , a_ ) self.run_test_targets(a_ , a_ ) self.run_test_top_k_targets(a_ , a_ ) self.fill_mask_with_duplicate_targets_and_top_k(a_ , a_ ) self.fill_mask_with_multiple_masks(a_ , a_ ) def _a ( self , a_ , a_ ) -> Optional[int]: _UpperCAmelCase = tokenizer.get_vocab() _UpperCAmelCase = sorted(vocab.keys() )[:2] # Pipeline argument _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ , targets=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , a_ ) _UpperCAmelCase = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(a_ ) ) # Call argument _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , a_ ) _UpperCAmelCase = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(a_ ) ) # Score equivalence _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) _UpperCAmelCase = [top_mask["token_str"] for top_mask in outputs] _UpperCAmelCase = [top_mask["score"] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(a_ ) == set(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) _UpperCAmelCase = [top_mask["score"] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) # Raises with invalid with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=[""] ) with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets="" ) def _a ( self , a_ , a_ ) -> str: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ , top_k=2 ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=2 ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) def _a ( self , a_ , a_ ) -> List[Any]: _UpperCAmelCase = tokenizer.get_vocab() _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) # top_k=2, ntargets=3 _UpperCAmelCase = sorted(vocab.keys() )[:3] _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=2 , targets=a_ ) # If we use the most probably targets, and filter differently, we should still # have the same results _UpperCAmelCase = [el["token_str"] for el in sorted(a_ , key=lambda a_ : x["score"] , reverse=a_ )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(a_ ).issubset(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=3 , targets=a_ ) # They should yield exactly the same result self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) def _a ( self , a_ , a_ ) -> Optional[Any]: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = tokenizer.get_vocab() # String duplicates + id duplicates _UpperCAmelCase = sorted(vocab.keys() )[:3] _UpperCAmelCase = [targets[0], targets[1], targets[0], targets[2], targets[1]] _UpperCAmelCase = fill_masker(f"My name is {tokenizer.mask_token}" , targets=a_ , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(a_ ) , 3 ) def _a ( self , a_ , a_ ) -> Any: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker( f"This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}" , top_k=2 ) self.assertEqual( a_ , [ [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], ] , )
657
0
'''simple docstring''' from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run UpperCAmelCase_ : Tuple = True except (ImportError, AttributeError): UpperCAmelCase_ : List[str] = object def _lowercase ( *UpperCamelCase__ : Union[str, Any], **UpperCamelCase__ : Optional[Any] ): pass UpperCAmelCase_ : Optional[int] = False UpperCAmelCase_ : Dict = logging.get_logger('transformers-cli/serving') def _lowercase ( UpperCamelCase__ : str ): __A : List[str] = pipeline( task=args.task, model=args.model if args.model else None, config=args.config, tokenizer=args.tokenizer, device=args.device, ) return ServeCommand(UpperCamelCase__, args.host, args.port, args.workers ) class _lowerCamelCase ( snake_case_ ): '''simple docstring''' __lowercase : dict class _lowerCamelCase ( snake_case_ ): '''simple docstring''' __lowercase : List[str] __lowercase : Optional[List[int]] class _lowerCamelCase ( snake_case_ ): '''simple docstring''' __lowercase : str class _lowerCamelCase ( snake_case_ ): '''simple docstring''' __lowercase : Any class _lowerCamelCase ( snake_case_ ): '''simple docstring''' @staticmethod def snake_case__ ( __lowercase ): """simple docstring""" __A : Any = parser.add_parser( 'serve' , help='CLI tool to run inference requests through REST and GraphQL endpoints.' ) serve_parser.add_argument( '--task' , type=a_ , choices=get_supported_tasks() , help='The task to run the pipeline on' , ) serve_parser.add_argument('--host' , type=a_ , default='localhost' , help='Interface the server will listen on.' ) serve_parser.add_argument('--port' , type=a_ , default=8_888 , help='Port the serving will listen to.' ) serve_parser.add_argument('--workers' , type=a_ , default=1 , help='Number of http workers' ) serve_parser.add_argument('--model' , type=a_ , help='Model\'s name or path to stored model.' ) serve_parser.add_argument('--config' , type=a_ , help='Model\'s config name or path to stored model.' ) serve_parser.add_argument('--tokenizer' , type=a_ , help='Tokenizer name to use.' ) serve_parser.add_argument( '--device' , type=a_ , default=-1 , help='Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)' , ) serve_parser.set_defaults(func=a_ ) def __init__( self , __lowercase , __lowercase , __lowercase , __lowercase ): """simple docstring""" __A : List[Any] = pipeline __A : str = host __A : List[Any] = port __A : Union[str, Any] = workers if not _serve_dependencies_installed: raise RuntimeError( 'Using serve command requires FastAPI and uvicorn. ' 'Please install transformers with [serving]: pip install \"transformers[serving]\".' 'Or install FastAPI and uvicorn separately.' ) else: logger.info(F"""Serving model over {host}:{port}""" ) __A : str = FastAPI( routes=[ APIRoute( '/' , self.model_info , response_model=a_ , response_class=a_ , methods=['GET'] , ), APIRoute( '/tokenize' , self.tokenize , response_model=a_ , response_class=a_ , methods=['POST'] , ), APIRoute( '/detokenize' , self.detokenize , response_model=a_ , response_class=a_ , methods=['POST'] , ), APIRoute( '/forward' , self.forward , response_model=a_ , response_class=a_ , methods=['POST'] , ), ] , timeout=600 , ) def snake_case__ ( self ): """simple docstring""" run(self._app , host=self.host , port=self.port , workers=self.workers ) def snake_case__ ( self ): """simple docstring""" return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def snake_case__ ( self , __lowercase = Body(a_ , embed=a_ ) , __lowercase = Body(a_ , embed=a_ ) ): """simple docstring""" try: __A : Optional[int] = self._pipeline.tokenizer.tokenize(a_ ) if return_ids: __A : Any = self._pipeline.tokenizer.convert_tokens_to_ids(a_ ) return ServeTokenizeResult(tokens=a_ , tokens_ids=a_ ) else: return ServeTokenizeResult(tokens=a_ ) except Exception as e: raise HTTPException(status_code=500 , detail={'model': '', 'error': str(a_ )} ) def snake_case__ ( self , __lowercase = Body(a_ , embed=a_ ) , __lowercase = Body(a_ , embed=a_ ) , __lowercase = Body(a_ , embed=a_ ) , ): """simple docstring""" try: __A : Dict = self._pipeline.tokenizer.decode(a_ , a_ , a_ ) return ServeDeTokenizeResult(model='' , text=a_ ) except Exception as e: raise HTTPException(status_code=500 , detail={'model': '', 'error': str(a_ )} ) async def snake_case__ ( self , __lowercase=Body(a_ , embed=a_ ) ): """simple docstring""" if len(a_ ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model __A : List[Any] = self._pipeline(a_ ) return ServeForwardResult(output=a_ ) except Exception as e: raise HTTPException(500 , {'error': str(a_ )} )
365
"""simple docstring""" import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class _lowerCAmelCase ( lowerCamelCase ): def _a ( self ) -> List[str]: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> Optional[int]: with self.assertRaises(a_ ): _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def _a ( self ) -> int: with self.assertRaises(a_ ): _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("bool" ) , type=Value("int64" ) ) ) def _a ( self ) -> Optional[Any]: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> int: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , type=Value("int64" ) ) ) def _a ( self ) -> Dict: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , try_type=Value("int64" ) ) ) self.assertEqual(arr.type , pa.string() ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def _a ( self ) -> Tuple: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , type=ArrayaD((1, 3) , "int64" ) ) ) def _a ( self ) -> str: _UpperCAmelCase = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def _a ( self ) -> Tuple: _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def _a ( self ) -> List[str]: import PIL.Image _UpperCAmelCase = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( "datasets.arrow_writer.cast_to_python_objects" , side_effect=a_ ) as mock_cast_to_python_objects: _UpperCAmelCase = pa.array(TypedSequence([{"path": None, "bytes": B"image_bytes"}, pil_image] , type=Image() ) ) _UpperCAmelCase , _UpperCAmelCase = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("optimize_list_casting" , a_ ) self.assertFalse(kwargs["optimize_list_casting"] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferReader(UpperCamelCase__ ) if isinstance(UpperCamelCase__ , pa.Buffer ) else pa.memory_map(UpperCamelCase__ ) _UpperCAmelCase = pa.ipc.open_stream(UpperCamelCase__ ) _UpperCAmelCase = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = Features({"labels": ClassLabel(names=["neg", "pos"] )} ) with ArrowWriter(stream=UpperCamelCase__ , features=UpperCamelCase__ ) as writer: writer.write({"labels": 0} ) writer.write({"labels": 1} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pa.ipc.open_stream(UpperCamelCase__ ) _UpperCAmelCase = f.read_all() _UpperCAmelCase = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(UpperCamelCase__ ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: with pytest.raises(UpperCamelCase__ ): writer.write({"col_1": "foo", "col_2": 1} , key=[1, 2] ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: with pytest.raises(UpperCamelCase__ ): writer.write({"col_1": "foo", "col_2": 1} , key=10 ) writer.write({"col_1": "bar", "col_2": 2} , key=10 ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: writer.write({"col_1": "foo", "col_2": 1} , key=1 ) writer.write({"col_1": "bar", "col_2": 2} , key=2 ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) writer.write_batch({"col_1": [], "col_2": []} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_table(pa.Table.from_pydict({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_row(pa.Table.from_pydict({"col_1": ["foo"], "col_2": [1]} ) ) writer.write_row(pa.Table.from_pydict({"col_1": ["bar"], "col_2": [2]} ) ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __lowerCamelCase ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} _UpperCAmelCase = os.path.join(UpperCamelCase__ , "test.arrow" ) with ArrowWriter(path=UpperCamelCase__ , schema=pa.schema(UpperCamelCase__ ) ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(UpperCamelCase__ , 1 ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if pa.types.is_list(UpperCamelCase__ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if isinstance(lst[0] , UpperCamelCase__ ): change_first_primitive_element_in_list(lst[0] , UpperCamelCase__ ) else: _UpperCAmelCase = value @pytest.mark.parametrize("optimized_int_type, expected_dtype" , [(None, pa.intaa()), (Value("int32" ), pa.intaa())] ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.array(TypedSequence(UpperCamelCase__ , optimized_int_type=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( "col, expected_dtype" , [ ("attention_mask", pa.inta()), ("special_tokens_mask", pa.inta()), ("token_type_ids", pa.inta()), ("input_ids", pa.intaa()), ("other", pa.intaa()), ] , ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.array(OptimizedTypedSequence(UpperCamelCase__ , col=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications _UpperCAmelCase = copy.deepcopy(UpperCamelCase__ ) _UpperCAmelCase = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(UpperCamelCase__ , UpperCamelCase__ ) _UpperCAmelCase = pa.array(OptimizedTypedSequence(UpperCamelCase__ , col=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("raise_exception" , [False, True] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = str(tmp_path / "dataset-train.arrow" ) try: with ArrowWriter(path=UpperCamelCase__ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = "mock://dataset-train.arrow" with ArrowWriter(path=UpperCamelCase__ , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(UpperCamelCase__ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(UpperCamelCase__ ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ParquetWriter(stream=UpperCamelCase__ ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pq.read_table(UpperCamelCase__ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("embed_local_files" , [False, True] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" import PIL.Image _UpperCAmelCase = str(tmp_path / "test_image_rgb.jpg" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(UpperCamelCase__ , format="png" ) _UpperCAmelCase = pa.BufferOutputStream() with ParquetWriter( stream=UpperCamelCase__ , features=Features({"image": Image()} ) , embed_local_files=UpperCamelCase__ ) as writer: writer.write({"image": image_path} ) writer.finalize() _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pq.read_table(UpperCamelCase__ ) _UpperCAmelCase = pa_table.to_pydict() if embed_local_files: assert isinstance(out["image"][0]["path"] , UpperCamelCase__ ) with open(UpperCamelCase__ , "rb" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.schema([pa.field("col_1" , pa.string() , nullable=UpperCamelCase__ )] ) _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter(stream=UpperCamelCase__ ) as writer: writer._build_writer(inferred_schema=UpperCamelCase__ ) assert writer._schema == pa.schema([pa.field("col_1" , pa.string() )] )
657
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : Tuple = logging.get_logger(__name__) _lowercase : List[Any] = { """microsoft/resnet-50""": """https://huggingface.co/microsoft/resnet-50/blob/main/config.json""", } class UpperCamelCase__( lowerCAmelCase , lowerCAmelCase ): __magic_name__ : Any = '''resnet''' __magic_name__ : Dict = ['''basic''', '''bottleneck'''] def __init__( self : List[str] , lowerCAmelCase : Any=3 , lowerCAmelCase : Tuple=64 , lowerCAmelCase : List[str]=[256, 512, 1024, 2048] , lowerCAmelCase : List[Any]=[3, 4, 6, 3] , lowerCAmelCase : Union[str, Any]="bottleneck" , lowerCAmelCase : Optional[Any]="relu" , lowerCAmelCase : Optional[Any]=False , lowerCAmelCase : int=None , lowerCAmelCase : Dict=None , **lowerCAmelCase : str , )-> Tuple: """simple docstring""" super().__init__(**a_ ) if layer_type not in self.layer_types: raise ValueError(F"""layer_type={layer_type} is not one of {",".join(self.layer_types )}""" ) UpperCAmelCase = num_channels UpperCAmelCase = embedding_size UpperCAmelCase = hidden_sizes UpperCAmelCase = depths UpperCAmelCase = layer_type UpperCAmelCase = hidden_act UpperCAmelCase = downsample_in_first_stage UpperCAmelCase = ['''stem'''] + [F"""stage{idx}""" for idx in range(1 , len(a_ ) + 1 )] UpperCAmelCase , UpperCAmelCase = get_aligned_output_features_output_indices( out_features=a_ , out_indices=a_ , stage_names=self.stage_names ) class UpperCamelCase__( lowerCAmelCase ): __magic_name__ : Optional[Any] = version.parse("1.11" ) @property def a__( self : Optional[int] )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def a__( self : int )-> float: """simple docstring""" return 1E-3
210
"""simple docstring""" import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class _lowerCAmelCase ( unittest.TestCase ): def _a ( self ) -> Optional[Any]: _UpperCAmelCase = ["a", "b", "c"] # Defaults to last layer if both are None _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , a_ , a_ ) self.assertEqual(a_ , ["c"] ) self.assertEqual(a_ , [2] ) # Out indices set to match out features _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(["a", "c"] , a_ , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features set to match out indices _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , [0, 2] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features selected from negative indices _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , [-3, -1] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [-3, -1] ) def _a ( self ) -> Optional[int]: # Stage names must be set with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , a_ ) # Out features must be a list with self.assertRaises(a_ ): verify_out_features_out_indices(("a", "b") , (0, 1) , ["a", "b"] ) # Out features must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , ["a"] ) # Out indices must be a list or tuple with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , 0 , ["a", "b"] ) # Out indices must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , (0, 1) , ["a"] ) # Out features and out indices must be the same length with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0,) , ["a", "b", "c"] ) # Out features should match out indices with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 2) , ["a", "b", "c"] ) # Out features and out indices should be in order with self.assertRaises(a_ ): verify_out_features_out_indices(["b", "a"] , (0, 1) , ["a", "b"] ) # Check passes with valid inputs verify_out_features_out_indices(["a", "b", "d"] , (0, 1, -1) , ["a", "b", "c", "d"] ) def _a ( self ) -> int: _UpperCAmelCase = BackboneMixin() _UpperCAmelCase = ["a", "b", "c"] _UpperCAmelCase = ["a", "c"] _UpperCAmelCase = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly _UpperCAmelCase = ["a", "b"] self.assertEqual(backbone.out_features , ["a", "b"] ) self.assertEqual(backbone.out_indices , [0, 1] ) _UpperCAmelCase = [-3, -1] self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [-3, -1] )
657
0
from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .modules import *
488
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = { '''configuration_electra''': ['''ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ElectraConfig''', '''ElectraOnnxConfig'''], '''tokenization_electra''': ['''ElectraTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''ElectraTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''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: __magic_name__ = [ '''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: __magic_name__ = [ '''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 __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
657
0
import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class SCREAMING_SNAKE_CASE : '''simple docstring''' @staticmethod def _A ( *UpperCAmelCase_ : int , **UpperCAmelCase_ : str ): pass def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Any = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def _A ( self : Tuple , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : int = DepthEstimationPipeline(model=a_ , image_processor=a_ ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def _A ( self : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : Optional[Any] = depth_estimator("./tests/fixtures/tests_samples/COCO/000000039769.png" ) self.assertEqual({"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )} , a_ ) import datasets SCREAMING_SNAKE_CASE : Union[str, Any] = datasets.load_dataset("hf-internal-testing/fixtures_image_utils" , "image" , split="test" ) SCREAMING_SNAKE_CASE : Any = depth_estimator( [ Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ), "http://images.cocodataset.org/val2017/000000039769.jpg", # RGBA dataset[0]["file"], # LA dataset[1]["file"], # L dataset[2]["file"], ] ) self.assertEqual( [ {"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )}, {"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )}, {"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )}, {"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )}, {"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )}, ] , a_ , ) @require_tf @unittest.skip("Depth estimation is not implemented in TF" ) def _A ( self : Tuple ): pass @slow @require_torch def _A ( self : str ): SCREAMING_SNAKE_CASE : int = "Intel/dpt-large" SCREAMING_SNAKE_CASE : Tuple = pipeline("depth-estimation" , model=a_ ) SCREAMING_SNAKE_CASE : Any = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg" ) SCREAMING_SNAKE_CASE : List[str] = hashimage(outputs["depth"] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs["predicted_depth"].max().item() ) , 29.304 ) self.assertEqual(nested_simplify(outputs["predicted_depth"].min().item() ) , 2.662 ) @require_torch def _A ( self : Dict ): # This is highly irregular to have no small tests. self.skipTest("There is not hf-internal-testing tiny model for either GLPN nor DPT" )
62
"""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 _lowerCAmelCase ( lowerCamelCase , unittest.TestCase ): lowercase_ : Tuple = BarthezTokenizer lowercase_ : List[Any] = BarthezTokenizerFast lowercase_ : Dict = True lowercase_ : int = True def _a ( self ) -> Any: super().setUp() _UpperCAmelCase = BarthezTokenizerFast.from_pretrained("moussaKam/mbarthez" ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=a_ ) _UpperCAmelCase = tokenizer def _a ( self ) -> List[Any]: _UpperCAmelCase = "<pad>" _UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = 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(a_ ) , 101122 ) def _a ( self ) -> Union[str, Any]: self.assertEqual(self.get_tokenizer().vocab_size , 101122 ) @require_torch def _a ( self ) -> List[Any]: _UpperCAmelCase = ["A long paragraph for summarization.", "Another paragraph for summarization."] _UpperCAmelCase = [0, 57, 3018, 70307, 91, 2] _UpperCAmelCase = self.tokenizer( a_ , max_length=len(a_ ) , padding=a_ , truncation=a_ , return_tensors="pt" ) self.assertIsInstance(a_ , a_ ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) _UpperCAmelCase = batch.input_ids.tolist()[0] self.assertListEqual(a_ , a_ ) def _a ( self ) -> str: if not self.test_rust_tokenizer: return _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = self.get_rust_tokenizer() _UpperCAmelCase = "I was born in 92000, and this is falsé." _UpperCAmelCase = tokenizer.tokenize(a_ ) _UpperCAmelCase = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) _UpperCAmelCase = tokenizer.encode(a_ , add_special_tokens=a_ ) _UpperCAmelCase = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) _UpperCAmelCase = self.get_rust_tokenizer() _UpperCAmelCase = tokenizer.encode(a_ ) _UpperCAmelCase = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def _a ( self ) -> Dict: # fmt: off _UpperCAmelCase = {"input_ids": [[0, 490, 14328, 4507, 354, 47, 43669, 95, 25, 78117, 20215, 19779, 190, 22, 400, 4, 35343, 80310, 603, 86, 24937, 105, 33438, 94762, 196, 39642, 7, 15, 15933, 173, 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, 10534, 87, 25, 66, 3358, 196, 55289, 8, 82961, 81, 2204, 75203, 7, 15, 763, 12956, 216, 178, 14328, 9595, 1377, 69693, 7, 448, 71021, 196, 18106, 1437, 13974, 108, 9083, 4, 49315, 7, 39, 86, 1326, 2793, 46333, 4, 448, 196, 74588, 7, 49315, 7, 39, 21, 822, 38470, 74, 21, 66723, 62480, 8, 22050, 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. _UpperCAmelCase = [ "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=a_ , model_name="moussaKam/mbarthez" , revision="c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6" , sequences=a_ , )
657
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Optional[int] = logging.get_logger(__name__) lowerCamelCase : Optional[int] = { '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 snake_case__ ( UpperCamelCase_ ): _lowerCAmelCase ='''vivit''' def __init__( self : Dict , _lowerCamelCase : str=2_2_4 , _lowerCamelCase : Any=3_2 , _lowerCamelCase : int=[2, 1_6, 1_6] , _lowerCamelCase : List[Any]=3 , _lowerCamelCase : Optional[int]=7_6_8 , _lowerCamelCase : int=1_2 , _lowerCamelCase : int=1_2 , _lowerCamelCase : List[str]=3_0_7_2 , _lowerCamelCase : Dict="gelu_fast" , _lowerCamelCase : List[Any]=0.0 , _lowerCamelCase : Any=0.0 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : List[Any]=1E-06 , _lowerCamelCase : Union[str, Any]=True , **_lowerCamelCase : List[Any] , ): snake_case__ : Optional[int] = hidden_size snake_case__ : Optional[Any] = num_hidden_layers snake_case__ : Optional[Any] = num_attention_heads snake_case__ : int = intermediate_size snake_case__ : Optional[Any] = hidden_act snake_case__ : str = hidden_dropout_prob snake_case__ : int = attention_probs_dropout_prob snake_case__ : List[str] = initializer_range snake_case__ : List[str] = layer_norm_eps snake_case__ : Dict = image_size snake_case__ : List[str] = num_frames snake_case__ : Optional[int] = tubelet_size snake_case__ : Any = num_channels snake_case__ : int = qkv_bias super().__init__(**a_ )
170
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): _UpperCAmelCase = f"Input value of [number={number}] must be an integer" raise TypeError(UpperCamelCase__ ) if number < 0: return False _UpperCAmelCase = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
657
0
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging lowercase : Optional[int] = logging.get_logger(__name__) def lowerCAmelCase__ ( _a : Optional[Any] , _a : int , _a : str ): snake_case_ : Any = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ), F'''{len(UpperCamelCase__ )} != {len(UpperCamelCase__ )}''' dest_layers.load_state_dict(layers_to_copy.state_dict() ) lowercase : List[Any] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } lowercase : str = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def lowerCAmelCase__ ( _a : str , _a : Any ): try: snake_case_ : List[Any] = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F'''no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first''' F''' {n_student}''' ) return list(range(UpperCamelCase__ ) ) def lowerCAmelCase__ ( _a : Tuple , _a : Union[str, Any] ): if n_student > n_teacher: raise ValueError(F'''Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}''' ) elif n_teacher == n_student: return list(range(UpperCamelCase__ ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def lowerCAmelCase__ ( _a : str , _a : Optional[Any] = "student" , _a : int = None , _a : List[Any] = None , _a : Any=False , _a : Tuple=None , _a : Optional[Any]=None , **_a : Any , ): snake_case_ : List[Any] = "encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher." assert (e is not None) or (d is not None), _msg if isinstance(UpperCamelCase__ , UpperCamelCase__ ): AutoTokenizer.from_pretrained(UpperCamelCase__ ).save_pretrained(UpperCamelCase__ ) # purely for convenience snake_case_ : Optional[Any] = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ ).eval() else: assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), F'''teacher must be a model or string got type {type(UpperCamelCase__ )}''' snake_case_ : List[str] = teacher.config.to_diff_dict() try: snake_case_ , snake_case_ : Optional[int] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: snake_case_ : Any = teacher_e if d is None: snake_case_ : Dict = teacher_d init_kwargs.update({"encoder_layers": e, "decoder_layers": d} ) except AttributeError: # T5 if hasattr(teacher.config , "num_encoder_layers" ): snake_case_ , snake_case_ : Optional[int] = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: snake_case_ , snake_case_ : Tuple = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: snake_case_ : Tuple = teacher_e if d is None: snake_case_ : Dict = teacher_d if hasattr(teacher.config , "num_encoder_layers" ): init_kwargs.update({"num_encoder_layers": e, "num_decoder_layers": d} ) else: init_kwargs.update({"num_layers": e, "num_decoder_layers": d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(UpperCamelCase__ ) # Copy weights snake_case_ : Optional[Any] = teacher.config_class(**UpperCamelCase__ ) snake_case_ : Union[str, Any] = AutoModelForSeqaSeqLM.from_config(UpperCamelCase__ ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. snake_case_ : str = student.load_state_dict(teacher.state_dict() , strict=UpperCamelCase__ ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save snake_case_ , snake_case_ : Any = list(range(UpperCamelCase__ ) ), list(range(UpperCamelCase__ ) ) logger.info( F'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to''' F''' {save_path}''' ) student.save_pretrained(UpperCamelCase__ ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: snake_case_ : List[str] = pick_layers_to_copy(UpperCamelCase__ , UpperCamelCase__ ) if d_layers_to_copy is None: snake_case_ : Optional[int] = pick_layers_to_copy(UpperCamelCase__ , UpperCamelCase__ ) try: if hasattr( UpperCamelCase__ , "prophetnet" ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , UpperCamelCase__ ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , UpperCamelCase__ ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , UpperCamelCase__ ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , UpperCamelCase__ ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , UpperCamelCase__ ) copy_layers(teacher.decoder.block , student.decoder.block , UpperCamelCase__ ) logger.info( F'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}''' ) snake_case_ : Optional[int] = { "teacher_type": teacher.config.model_type, "copied_encoder_layers": e_layers_to_copy, "copied_decoder_layers": d_layers_to_copy, } student.save_pretrained(UpperCamelCase__ ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
568
"""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(lowerCamelCase ) class _lowerCAmelCase ( lowerCamelCase ): def __init__( self , *a_ , **a_ ) -> Optional[int]: super().__init__(*a_ , **a_ ) 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 _a ( self , **a_ ) -> List[str]: _UpperCAmelCase = {} if "threshold" in kwargs: _UpperCAmelCase = kwargs["threshold"] return {}, {}, postprocess_kwargs def __call__( self , *a_ , **a_ ) -> Union[Predictions, List[Prediction]]: return super().__call__(*a_ , **a_ ) def _a ( self , a_ ) -> Optional[Any]: _UpperCAmelCase = load_image(a_ ) _UpperCAmelCase = torch.IntTensor([[image.height, image.width]] ) _UpperCAmelCase = self.image_processor(images=[image] , return_tensors="pt" ) if self.tokenizer is not None: _UpperCAmelCase = self.tokenizer(text=inputs["words"] , boxes=inputs["boxes"] , return_tensors="pt" ) _UpperCAmelCase = target_size return inputs def _a ( self , a_ ) -> Optional[Any]: _UpperCAmelCase = model_inputs.pop("target_size" ) _UpperCAmelCase = self.model(**a_ ) _UpperCAmelCase = outputs.__class__({"target_size": target_size, **outputs} ) if self.tokenizer is not None: _UpperCAmelCase = model_inputs["bbox"] return model_outputs def _a ( self , a_ , a_=0.9 ) -> int: _UpperCAmelCase = 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. _UpperCAmelCase , _UpperCAmelCase = target_size[0].tolist() def unnormalize(a_ ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) _UpperCAmelCase , _UpperCAmelCase = model_outputs["logits"].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) _UpperCAmelCase = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] _UpperCAmelCase = [unnormalize(a_ ) for bbox in model_outputs["bbox"].squeeze(0 )] _UpperCAmelCase = ["score", "label", "box"] _UpperCAmelCase = [dict(zip(a_ , a_ ) ) for vals in zip(scores.tolist() , a_ , a_ ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel _UpperCAmelCase = self.image_processor.post_process_object_detection(a_ , a_ , a_ ) _UpperCAmelCase = raw_annotations[0] _UpperCAmelCase = raw_annotation["scores"] _UpperCAmelCase = raw_annotation["labels"] _UpperCAmelCase = raw_annotation["boxes"] _UpperCAmelCase = scores.tolist() _UpperCAmelCase = [self.model.config.idalabel[label.item()] for label in labels] _UpperCAmelCase = [self._get_bounding_box(a_ ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] _UpperCAmelCase = ["score", "label", "box"] _UpperCAmelCase = [ dict(zip(a_ , a_ ) ) for vals in zip(raw_annotation["scores"] , raw_annotation["labels"] , raw_annotation["boxes"] ) ] return annotation def _a ( self , a_ ) -> Dict[str, int]: if self.framework != "pt": raise ValueError("The ObjectDetectionPipeline is only available in PyTorch." ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = box.int().tolist() _UpperCAmelCase = { "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax, } return bbox
657
0
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def __lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" with self.assertRaises(a_ ): a = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" with self.assertRaises(a_ ): a = pa.array(TypedSequence([1, 2, 3] , try_type=Value('''bool''' ) , type=Value('''int64''' ) ) ) def __lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" a = pa.array(TypedSequence([1, 2, 3] , type=Value('''int32''' ) ) ) self.assertEqual(arr.type , pa.intaa() ) def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): a = pa.array(TypedSequence(['''foo''', '''bar'''] , type=Value('''int64''' ) ) ) def __lowerCAmelCase ( self : Dict ) ->Dict: """simple docstring""" a = pa.array(TypedSequence([1, 2, 3] , try_type=Value('''int32''' ) ) ) self.assertEqual(arr.type , pa.intaa() ) def __lowerCAmelCase ( self : Tuple ) ->Union[str, Any]: """simple docstring""" a = pa.array(TypedSequence(['''foo''', '''bar'''] , try_type=Value('''int64''' ) ) ) self.assertEqual(arr.type , pa.string() ) def __lowerCAmelCase ( self : str ) ->Union[str, Any]: """simple docstring""" a = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , '''int64''' ) ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): a = pa.array(TypedSequence(['''foo''', '''bar'''] , type=ArrayaD((1, 3) , '''int64''' ) ) ) def __lowerCAmelCase ( self : str ) ->str: """simple docstring""" a = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , '''int64''' ) ) def __lowerCAmelCase ( self : List[str] ) ->Tuple: """simple docstring""" a = pa.array(TypedSequence(['''foo''', '''bar'''] , try_type=ArrayaD((1, 3) , '''int64''' ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" import PIL.Image a = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( '''datasets.arrow_writer.cast_to_python_objects''' , side_effect=a_ ) as mock_cast_to_python_objects: a = pa.array(TypedSequence([{'''path''': None, '''bytes''': b'''image_bytes'''}, pil_image] , type=Image() ) ) a , a = mock_cast_to_python_objects.call_args_list[-1] self.assertIn('''optimize_list_casting''' , a_ ) self.assertFalse(kwargs['''optimize_list_casting'''] ) def _a ( a :List[Any] , a :Dict ) -> Dict: a = pa.BufferReader(UpperCamelCase__ ) if isinstance(UpperCamelCase__ , pa.Buffer ) else pa.memory_map(UpperCamelCase__ ) a = pa.ipc.open_stream(UpperCamelCase__ ) a = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def _a ( a :Dict , a :Any ) -> Optional[int]: a = pa.BufferOutputStream() a = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) a , a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: a = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def _a ( ) -> int: a = pa.BufferOutputStream() a = Features({'''labels''': ClassLabel(names=['''neg''', '''pos'''] )} ) with ArrowWriter(stream=UpperCamelCase__ , features=UpperCamelCase__ ) as writer: writer.write({'''labels''': 0} ) writer.write({'''labels''': 1} ) a , a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata a = pa.BufferReader(output.getvalue() ) a = pa.ipc.open_stream(UpperCamelCase__ ) a = f.read_all() a = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(UpperCamelCase__ ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) def _a ( a :Optional[Any] ) -> str: a = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt='''split_name''' , check_duplicates=UpperCamelCase__ , ) as writer: with pytest.raises(UpperCamelCase__ ): writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=[1, 2] ) a , a = writer.finalize() @pytest.mark.parametrize('''writer_batch_size''' , [None, 2, 10] ) def _a ( a :Union[str, Any] ) -> Optional[Any]: a = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt='''split_name''' , check_duplicates=UpperCamelCase__ , ) as writer: with pytest.raises(UpperCamelCase__ ): writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=10 ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} , key=10 ) a , a = writer.finalize() @pytest.mark.parametrize('''writer_batch_size''' , [None, 2, 10] ) def _a ( a :Optional[Any] ) -> Optional[int]: a = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt='''split_name''' , check_duplicates=UpperCamelCase__ , ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} , key=1 ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} , key=2 ) a , a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def _a ( a :Union[str, Any] , a :Tuple ) -> Dict: a = pa.BufferOutputStream() a = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) writer.write_batch({'''col_1''': [], '''col_2''': []} ) a , a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: a = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def _a ( a :Dict , a :Dict ) -> Any: a = pa.BufferOutputStream() a = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) ) a , a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: a = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('''writer_batch_size''' , [None, 1, 10] ) @pytest.mark.parametrize( '''fields''' , [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}] ) def _a ( a :Optional[Any] , a :Tuple ) -> Union[str, Any]: a = pa.BufferOutputStream() a = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]} ) ) writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]} ) ) a , a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: a = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def _a ( ) -> Tuple: with tempfile.TemporaryDirectory() as tmp_dir: a = {'''col_1''': pa.string(), '''col_2''': pa.intaa()} a = os.path.join(UpperCamelCase__ , '''test.arrow''' ) with ArrowWriter(path=UpperCamelCase__ , schema=pa.schema(UpperCamelCase__ ) ) as writer: writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]} ) a , a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(UpperCamelCase__ , 1 ) def _a ( a :int ) -> int: if pa.types.is_list(UpperCamelCase__ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def _a ( a :str , a :int ) -> List[Any]: if isinstance(lst[0] , UpperCamelCase__ ): change_first_primitive_element_in_list(lst[0] , UpperCamelCase__ ) else: a = value @pytest.mark.parametrize('''optimized_int_type, expected_dtype''' , [(None, pa.intaa()), (Value('''int32''' ), pa.intaa())] ) @pytest.mark.parametrize('''sequence''' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def _a ( a :List[Any] , a :int , a :List[Any] ) -> Optional[int]: a = pa.array(TypedSequence(UpperCamelCase__ , optimized_int_type=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( '''col, expected_dtype''' , [ ('''attention_mask''', pa.inta()), ('''special_tokens_mask''', pa.inta()), ('''token_type_ids''', pa.inta()), ('''input_ids''', pa.intaa()), ('''other''', pa.intaa()), ] , ) @pytest.mark.parametrize('''sequence''' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def _a ( a :Optional[Any] , a :List[Any] , a :List[Any] ) -> Optional[int]: a = pa.array(OptimizedTypedSequence(UpperCamelCase__ , col=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications a = copy.deepcopy(UpperCamelCase__ ) a = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(UpperCamelCase__ , UpperCamelCase__ ) a = pa.array(OptimizedTypedSequence(UpperCamelCase__ , col=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('''raise_exception''' , [False, True] ) def _a ( a :Optional[int] , a :Optional[int] ) -> Union[str, Any]: a = str(tmp_path / '''dataset-train.arrow''' ) try: with ArrowWriter(path=UpperCamelCase__ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def _a ( a :Union[str, Any] ) -> List[Any]: a = '''mock://dataset-train.arrow''' with ArrowWriter(path=UpperCamelCase__ , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(UpperCamelCase__ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) a , a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(UpperCamelCase__ ) def _a ( ) -> Optional[Any]: a = pa.BufferOutputStream() with ParquetWriter(stream=UpperCamelCase__ ) as writer: writer.write({'''col_1''': '''foo''', '''col_2''': 1} ) writer.write({'''col_1''': '''bar''', '''col_2''': 2} ) a , a = writer.finalize() assert num_examples == 2 assert num_bytes > 0 a = pa.BufferReader(output.getvalue() ) a = pq.read_table(UpperCamelCase__ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('''embed_local_files''' , [False, True] ) def _a ( a :Union[str, Any] , a :List[str] ) -> Any: import PIL.Image a = str(tmp_path / '''test_image_rgb.jpg''' ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(UpperCamelCase__ , format='''png''' ) a = pa.BufferOutputStream() with ParquetWriter( stream=UpperCamelCase__ , features=Features({'''image''': Image()} ) , embed_local_files=UpperCamelCase__ ) as writer: writer.write({'''image''': image_path} ) writer.finalize() a = pa.BufferReader(output.getvalue() ) a = pq.read_table(UpperCamelCase__ ) a = pa_table.to_pydict() if embed_local_files: assert isinstance(out['''image'''][0]['''path'''] , UpperCamelCase__ ) with open(UpperCamelCase__ , '''rb''' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def _a ( ) -> int: a = pa.schema([pa.field('''col_1''' , pa.string() , nullable=UpperCamelCase__ )] ) a = pa.BufferOutputStream() with ArrowWriter(stream=UpperCamelCase__ ) as writer: writer._build_writer(inferred_schema=UpperCamelCase__ ) assert writer._schema == pa.schema([pa.field('''col_1''' , pa.string() )] )
117
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def merge(UpperCamelCase__ , UpperCamelCase__ ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(UpperCamelCase__ ) <= 1: return collection _UpperCAmelCase = len(UpperCamelCase__ ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() __magic_name__ = input('''Enter numbers separated by a comma:\n''').strip() __magic_name__ = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
657
0
from typing import TYPE_CHECKING from ....utils import _LazyModule A = {"tokenization_tapex": ["TapexTokenizer"]} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys A = _LazyModule(__name__, globals()["__file__"], _import_structure)
475
"""simple docstring""" 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 _lowerCAmelCase : def __init__( self , a_ , a_=13 , a_=7 , a_=True , a_=True , a_=True , a_=99 , a_=32 , a_=5 , a_=4 , a_=37 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=16 , a_=2 , a_=0.02 , a_=3 , a_=4 , a_=None , ) -> List[str]: _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = seq_length _UpperCAmelCase = is_training _UpperCAmelCase = use_token_type_ids _UpperCAmelCase = use_labels _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = num_labels _UpperCAmelCase = num_choices _UpperCAmelCase = scope _UpperCAmelCase = self.vocab_size - 1 def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCAmelCase = None if self.use_token_type_ids: _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) _UpperCAmelCase = 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 , ) _UpperCAmelCase = 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 _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Optional[int]: _UpperCAmelCase = OpenAIGPTModel(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , head_mask=a_ ) _UpperCAmelCase = model(a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> List[Any]: _UpperCAmelCase = OpenAIGPTLMHeadModel(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Optional[Any]: _UpperCAmelCase = OpenAIGPTDoubleHeadsModel(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Dict: _UpperCAmelCase = self.num_labels _UpperCAmelCase = OpenAIGPTForSequenceClassification(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = config_and_inputs _UpperCAmelCase = { "input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask, } return config, inputs_dict @require_torch class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase_ : Any = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowercase_ : Optional[Any] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowercase_ : Union[str, Any] = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def _a ( self , a_ , a_ , a_ , a_ , a_ ) -> Any: 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 _a ( self , a_ , a_ , a_=False ) -> Optional[int]: _UpperCAmelCase = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=a_ , ) _UpperCAmelCase = inputs_dict["labels"] _UpperCAmelCase = inputs_dict["labels"] _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=a_ , ) _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) return inputs_dict def _a ( self ) -> Optional[int]: _UpperCAmelCase = OpenAIGPTModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=a_ , n_embd=37 ) def _a ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def _a ( self ) -> Any: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*a_ ) def _a ( self ) -> Tuple: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*a_ ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a_ ) @slow def _a ( self ) -> int: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = OpenAIGPTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) @require_torch class _lowerCAmelCase ( unittest.TestCase ): @slow def _a ( self ) -> Any: _UpperCAmelCase = OpenAIGPTLMHeadModel.from_pretrained("openai-gpt" ) model.to(a_ ) _UpperCAmelCase = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=a_ ) # the president is _UpperCAmelCase = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 40477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the _UpperCAmelCase = model.generate(a_ , do_sample=a_ ) self.assertListEqual(output_ids[0].tolist() , a_ )
657
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A (__magic_name__ , unittest.TestCase ): snake_case :Union[str, Any] = KandinskyVaaPipeline snake_case :Tuple = [ '''image_embeds''', '''negative_image_embeds''', ] snake_case :Tuple = ['''image_embeds''', '''negative_image_embeds'''] snake_case :Optional[Any] = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] snake_case :Tuple = False @property def _snake_case ( self ): return 32 @property def _snake_case ( self ): return 32 @property def _snake_case ( self ): return self.time_input_dim @property def _snake_case ( self ): return self.time_input_dim * 4 @property def _snake_case ( self ): return 1_00 @property def _snake_case ( self ): torch.manual_seed(0 ) __UpperCAmelCase : Any = { "in_channels": 4, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } __UpperCAmelCase : Union[str, Any] = UNetaDConditionModel(**a_ ) return model @property def _snake_case ( self ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _snake_case ( self ): torch.manual_seed(0 ) __UpperCAmelCase : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def _snake_case ( self ): __UpperCAmelCase : Optional[int] = self.dummy_unet __UpperCAmelCase : str = self.dummy_movq __UpperCAmelCase : Any = DDIMScheduler( num_train_timesteps=10_00 , beta_schedule="linear" , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , clip_sample=a_ , set_alpha_to_one=a_ , steps_offset=1 , prediction_type="epsilon" , thresholding=a_ , ) __UpperCAmelCase : Any = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_=0 ): __UpperCAmelCase : List[str] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(a_ ) ).to(a_ ) __UpperCAmelCase : Optional[int] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( a_ ) if str(a_ ).startswith("mps" ): __UpperCAmelCase : Optional[int] = torch.manual_seed(a_ ) else: __UpperCAmelCase : Dict = torch.Generator(device=a_ ).manual_seed(a_ ) __UpperCAmelCase : List[Any] = { "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def _snake_case ( self ): __UpperCAmelCase : Any = "cpu" __UpperCAmelCase : Union[str, Any] = self.get_dummy_components() __UpperCAmelCase : Union[str, Any] = self.pipeline_class(**a_ ) __UpperCAmelCase : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) __UpperCAmelCase : List[Any] = pipe(**self.get_dummy_inputs(a_ ) ) __UpperCAmelCase : Optional[Any] = output.images __UpperCAmelCase : int = pipe( **self.get_dummy_inputs(a_ ) , return_dict=a_ , )[0] __UpperCAmelCase : List[Any] = image[0, -3:, -3:, -1] __UpperCAmelCase : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __UpperCAmelCase : Dict = np.array( [0.6_2_3_7_9_7_6, 1.0, 0.3_6_4_4_1_3_3_2, 1.0, 0.7_0_6_3_9_6_3_4, 0.2_9_8_7_7_1_8_6, 0.8_5_6_5_2_1_2_5, 0.5_2_1_6_8_4_3, 0.5_4_4_5_4_0_4_6] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __A (unittest.TestCase ): def _snake_case ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self ): __UpperCAmelCase : Tuple = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy" ) __UpperCAmelCase : Tuple = KandinskyVaaPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa ) pipe_prior.to(a_ ) __UpperCAmelCase : Optional[Any] = KandinskyVaaPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-decoder" , torch_dtype=torch.floataa ) __UpperCAmelCase : str = pipeline.to(a_ ) pipeline.set_progress_bar_config(disable=a_ ) __UpperCAmelCase : str = "red cat, 4k photo" __UpperCAmelCase : int = torch.Generator(device="cuda" ).manual_seed(0 ) __UpperCAmelCase , __UpperCAmelCase : Optional[Any] = pipe_prior( a_ , generator=a_ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() __UpperCAmelCase : Tuple = torch.Generator(device="cuda" ).manual_seed(0 ) __UpperCAmelCase : List[str] = pipeline( image_embeds=a_ , negative_image_embeds=a_ , generator=a_ , num_inference_steps=1_00 , output_type="np" , ) __UpperCAmelCase : Union[str, Any] = output.images[0] assert image.shape == (5_12, 5_12, 3) assert_mean_pixel_difference(a_ , a_ )
168
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__=10 ): """simple docstring""" _UpperCAmelCase = [] for _ in range(UpperCamelCase__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__=10 ): """simple docstring""" _UpperCAmelCase = [] for step in range(UpperCamelCase__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase = os.path.join(UpperCamelCase__ , "schedule.bin" ) torch.save(scheduler.state_dict() , UpperCamelCase__ ) _UpperCAmelCase = torch.load(UpperCamelCase__ ) scheduler.load_state_dict(UpperCamelCase__ ) return lrs @require_torch class _lowerCAmelCase ( unittest.TestCase ): def _a ( self , a_ , a_ , a_ ) -> Optional[int]: self.assertEqual(len(a_ ) , len(a_ ) ) for a, b in zip(a_ , a_ ): self.assertAlmostEqual(a_ , a_ , delta=a_ ) def _a ( self ) -> str: _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=a_ ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(100 ): _UpperCAmelCase = criterion(a_ , a_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=a_ ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = Adafactor( params=[w] , lr=1e-2 , eps=(1e-30, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=a_ , weight_decay=0.0 , relative_step=a_ , scale_parameter=a_ , warmup_init=a_ , ) for _ in range(1000 ): _UpperCAmelCase = criterion(a_ , a_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class _lowerCAmelCase ( unittest.TestCase ): lowercase_ : List[Any] = nn.Linear(50 , 50 ) if is_torch_available() else None lowercase_ : Tuple = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None lowercase_ : Dict = 10 def _a ( self , a_ , a_ , a_ , a_=None ) -> Union[str, Any]: self.assertEqual(len(a_ ) , len(a_ ) ) for a, b in zip(a_ , a_ ): self.assertAlmostEqual(a_ , a_ , delta=a_ , msg=a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = {"num_warmup_steps": 2, "num_training_steps": 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _UpperCAmelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {"num_warmup_steps": 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, "num_cycles": 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, "power": 2.0, "lr_end": 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {"num_warmup_steps": 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _UpperCAmelCase , _UpperCAmelCase = data _UpperCAmelCase = scheduler_func(self.optimizer , **a_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _UpperCAmelCase = unwrap_schedule(a_ , self.num_steps ) self.assertListAlmostEqual( a_ , a_ , tol=1e-2 , msg=f"failed for {scheduler_func} in normal scheduler" , ) _UpperCAmelCase = scheduler_func(self.optimizer , **a_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(a_ ) # wrap to test picklability of the schedule _UpperCAmelCase = unwrap_and_save_reload_schedule(a_ , self.num_steps ) self.assertListEqual(a_ , a_ , msg=f"failed for {scheduler_func} in save and reload" ) class _lowerCAmelCase : def __init__( self , a_ ) -> Union[str, Any]: _UpperCAmelCase = fn def __call__( self , *a_ , **a_ ) -> Union[str, Any]: return self.fn(*a_ , **a_ ) @classmethod def _a ( self , a_ ) -> Dict: _UpperCAmelCase = list(map(self , scheduler.lr_lambdas ) )
657
0
'''simple docstring''' from __future__ import annotations from collections.abc import Generator def __SCREAMING_SNAKE_CASE ( ): """simple docstring""" lowercase_ : Optional[int] = {} lowercase_ : List[Any] = 2 while True: lowercase_ : Any = factor_map.pop(UpperCamelCase__ , UpperCamelCase__ ) if factor: lowercase_ : Dict = factor + prime while x in factor_map: x += factor lowercase_ : List[str] = factor else: lowercase_ : Any = prime yield prime prime += 1 def __SCREAMING_SNAKE_CASE ( _UpperCamelCase = 1e10 ): """simple docstring""" lowercase_ : Dict = sieve() lowercase_ : Any = 1 while True: lowercase_ : List[str] = next(UpperCamelCase__ ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(UpperCamelCase__ ) n += 2 if __name__ == "__main__": print(solution())
620
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __lowerCamelCase ( UpperCamelCase__=None ): """simple docstring""" if subparsers is not None: _UpperCAmelCase = subparsers.add_parser("test" ) else: _UpperCAmelCase = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=UpperCamelCase__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=UpperCamelCase__ ) return parser def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: _UpperCAmelCase = script_name else: _UpperCAmelCase = f"--config_file={args.config_file} {script_name}" _UpperCAmelCase = ["accelerate-launch"] + test_args.split() _UpperCAmelCase = execute_subprocess_async(UpperCamelCase__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = test_command_parser() _UpperCAmelCase = parser.parse_args() test_command(UpperCamelCase__ ) if __name__ == "__main__": main()
657
0
from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def A_ ( ) -> Any: a__ : str = ArgumentParser('Accelerate CLI tool' , usage='accelerate <command> [<args>]' , allow_abbrev=UpperCamelCase__ ) a__ : Tuple = parser.add_subparsers(help='accelerate command helpers' ) # Register commands get_config_parser(subparsers=UpperCamelCase__ ) env_command_parser(subparsers=UpperCamelCase__ ) launch_command_parser(subparsers=UpperCamelCase__ ) tpu_command_parser(subparsers=UpperCamelCase__ ) test_command_parser(subparsers=UpperCamelCase__ ) # Let's go a__ : Dict = parser.parse_args() if not hasattr(UpperCamelCase__ , 'func' ): parser.print_help() exit(1 ) # Run args.func(UpperCamelCase__ ) if __name__ == "__main__": main()
302
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" return 10 - x * x def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) >= 0: raise ValueError("Wrong space!" ) _UpperCAmelCase = a while (b - a) >= 0.01: # Find middle point _UpperCAmelCase = (a + b) / 2 # Check if middle point is root if equation(UpperCamelCase__ ) == 0.0: break # Decide the side to repeat the steps if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) < 0: _UpperCAmelCase = c else: _UpperCAmelCase = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
657
0
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : List[Any] = { 'Visual-Attention-Network/van-base': ( 'https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json' ), } class _lowerCamelCase ( snake_case_ ): '''simple docstring''' __lowercase : Dict = '''van''' def __init__( self , __lowercase=224 , __lowercase=3 , __lowercase=[7, 3, 3, 3] , __lowercase=[4, 2, 2, 2] , __lowercase=[64, 128, 320, 512] , __lowercase=[3, 3, 12, 3] , __lowercase=[8, 8, 4, 4] , __lowercase="gelu" , __lowercase=0.0_2 , __lowercase=1E-6 , __lowercase=1E-2 , __lowercase=0.0 , __lowercase=0.0 , **__lowercase , ): """simple docstring""" super().__init__(**a_ ) __A : Optional[Any] = image_size __A : Optional[Any] = num_channels __A : List[str] = patch_sizes __A : Optional[Any] = strides __A : int = hidden_sizes __A : Optional[int] = depths __A : List[str] = mlp_ratios __A : int = hidden_act __A : List[str] = initializer_range __A : str = layer_norm_eps __A : Union[str, Any] = layer_scale_init_value __A : int = drop_path_rate __A : Tuple = dropout_rate
365
"""simple docstring""" from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): lowercase_ : Tuple = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self , a_ , a_ , a_ = None , a_ = 50257 , a_ = 1024 , a_ = 768 , a_ = 12 , a_ = 12 , a_ = None , a_ = "gelu_new" , a_ = 0.1 , a_ = 0.1 , a_ = 0.1 , a_ = 1e-5 , a_ = 0.02 , a_ = True , a_ = True , a_ = False , a_ = False , ) -> List[str]: super().__init__() _UpperCAmelCase = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f"`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and" f" `n_embd`: {n_embd} are not equal." ) _UpperCAmelCase = prefix_inner_dim _UpperCAmelCase = prefix_hidden_dim _UpperCAmelCase = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) _UpperCAmelCase = ( nn.Linear(self.prefix_hidden_dim , a_ ) if self.prefix_hidden_dim is not None else nn.Identity() ) _UpperCAmelCase = GPTaConfig( vocab_size=a_ , n_positions=a_ , n_embd=a_ , n_layer=a_ , n_head=a_ , n_inner=a_ , activation_function=a_ , resid_pdrop=a_ , embd_pdrop=a_ , attn_pdrop=a_ , layer_norm_epsilon=a_ , initializer_range=a_ , scale_attn_weights=a_ , use_cache=a_ , scale_attn_by_inverse_layer_idx=a_ , reorder_and_upcast_attn=a_ , ) _UpperCAmelCase = GPTaLMHeadModel(a_ ) def _a ( self , a_ , a_ , a_ = None , a_ = None , ) -> Tuple: _UpperCAmelCase = self.transformer.transformer.wte(a_ ) _UpperCAmelCase = self.encode_prefix(a_ ) _UpperCAmelCase = self.decode_prefix(a_ ) _UpperCAmelCase = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: _UpperCAmelCase = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) _UpperCAmelCase = torch.cat((dummy_token, input_ids) , dim=1 ) _UpperCAmelCase = self.transformer(inputs_embeds=a_ , labels=a_ , attention_mask=a_ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def _a ( self , a_ , a_ ) -> torch.Tensor: return torch.zeros(a_ , self.prefix_length , dtype=torch.intaa , device=a_ ) def _a ( self , a_ ) -> Union[str, Any]: return self.encode_prefix(a_ ) @torch.no_grad() def _a ( self , a_ , a_ , a_ ) -> Union[str, Any]: _UpperCAmelCase = torch.split(a_ , 1 , dim=0 ) _UpperCAmelCase = [] _UpperCAmelCase = [] for feature in features: _UpperCAmelCase = self.decode_prefix(feature.to(a_ ) ) # back to the clip feature # Only support beam search for now _UpperCAmelCase , _UpperCAmelCase = self.generate_beam( input_embeds=a_ , device=a_ , eos_token_id=a_ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) _UpperCAmelCase = torch.stack(a_ ) _UpperCAmelCase = torch.stack(a_ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def _a ( self , a_=None , a_=None , a_=None , a_ = 5 , a_ = 67 , a_ = 1.0 , a_ = None , ) -> Optional[Any]: _UpperCAmelCase = eos_token_id _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = torch.ones(a_ , device=a_ , dtype=torch.int ) _UpperCAmelCase = torch.zeros(a_ , device=a_ , dtype=torch.bool ) if input_embeds is not None: _UpperCAmelCase = input_embeds else: _UpperCAmelCase = self.transformer.transformer.wte(a_ ) for i in range(a_ ): _UpperCAmelCase = self.transformer(inputs_embeds=a_ ) _UpperCAmelCase = outputs.logits _UpperCAmelCase = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) _UpperCAmelCase = logits.softmax(-1 ).log() if scores is None: _UpperCAmelCase , _UpperCAmelCase = logits.topk(a_ , -1 ) _UpperCAmelCase = generated.expand(a_ , *generated.shape[1:] ) _UpperCAmelCase , _UpperCAmelCase = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: _UpperCAmelCase = next_tokens else: _UpperCAmelCase = tokens.expand(a_ , *tokens.shape[1:] ) _UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) else: _UpperCAmelCase = -float(np.inf ) _UpperCAmelCase = 0 _UpperCAmelCase = scores[:, None] + logits seq_lengths[~is_stopped] += 1 _UpperCAmelCase = scores_sum / seq_lengths[:, None] _UpperCAmelCase , _UpperCAmelCase = scores_sum_average.view(-1 ).topk(a_ , -1 ) _UpperCAmelCase = next_tokens // scores_sum.shape[1] _UpperCAmelCase = seq_lengths[next_tokens_source] _UpperCAmelCase = next_tokens % scores_sum.shape[1] _UpperCAmelCase = next_tokens.unsqueeze(1 ) _UpperCAmelCase = tokens[next_tokens_source] _UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) _UpperCAmelCase = generated[next_tokens_source] _UpperCAmelCase = scores_sum_average * seq_lengths _UpperCAmelCase = is_stopped[next_tokens_source] _UpperCAmelCase = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) _UpperCAmelCase = torch.cat((generated, next_token_embed) , dim=1 ) _UpperCAmelCase = is_stopped + next_tokens.eq(a_ ).squeeze() if is_stopped.all(): break _UpperCAmelCase = scores / seq_lengths _UpperCAmelCase = scores.argsort(descending=a_ ) # tokens tensors are already padded to max_seq_length _UpperCAmelCase = [tokens[i] for i in order] _UpperCAmelCase = torch.stack(a_ , dim=0 ) _UpperCAmelCase = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
657
0
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCamelCase__( lowerCAmelCase ): @staticmethod @abstractmethod def a__( lowerCAmelCase : Union[str, Any] )-> str: """simple docstring""" raise NotImplementedError() @abstractmethod def a__( self : int )-> Tuple: """simple docstring""" raise NotImplementedError()
210
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable __magic_name__ = {'''configuration_gpt_neox''': ['''GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXConfig''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''GPTNeoXTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXForCausalLM''', '''GPTNeoXForQuestionAnswering''', '''GPTNeoXForSequenceClassification''', '''GPTNeoXForTokenClassification''', '''GPTNeoXLayer''', '''GPTNeoXModel''', '''GPTNeoXPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
657
0
def __a ( __UpperCAmelCase : str ) -> Optional[int]: # noqa: E741 """simple docstring""" lowerCamelCase_ : Optional[int] = len(UpperCamelCase__ ) lowerCamelCase_ : Tuple = 0 lowerCamelCase_ : Dict = [0] * n lowerCamelCase_ : int = [False] * n lowerCamelCase_ : Union[str, Any] = [False] * n def dfs(__UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : str , __UpperCAmelCase : Any ): if parent == root: out_edge_count += 1 lowerCamelCase_ : Dict = True lowerCamelCase_ : Optional[Any] = at for to in l[at]: if to == parent: pass elif not visited[to]: lowerCamelCase_ : str = dfs(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase_ : Union[str, Any] = min(low[at] , low[to] ) # AP found via bridge if at < low[to]: lowerCamelCase_ : int = True # AP found via cycle if at == low[to]: lowerCamelCase_ : str = True else: lowerCamelCase_ : List[str] = min(low[at] , UpperCamelCase__ ) return out_edge_count for i in range(UpperCamelCase__ ): if not visited[i]: lowerCamelCase_ : str = 0 lowerCamelCase_ : Optional[int] = dfs(UpperCamelCase__ , UpperCamelCase__ , -1 , UpperCamelCase__ ) lowerCamelCase_ : List[str] = out_edge_count > 1 for x in range(len(UpperCamelCase__ ) ): if is_art[x] is True: print(UpperCamelCase__ ) # Adjacency list of graph snake_case_ : List[str] = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
488
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''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 _lowerCAmelCase ( lowerCamelCase ): lowercase_ : Union[str, Any] = '''convbert''' def __init__( self , a_=30522 , 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_=768 , a_=2 , a_=9 , a_=1 , a_=None , **a_ , ) -> Tuple: super().__init__( pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ , ) _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = embedding_size _UpperCAmelCase = head_ratio _UpperCAmelCase = conv_kernel_size _UpperCAmelCase = num_groups _UpperCAmelCase = classifier_dropout class _lowerCAmelCase ( lowerCamelCase ): @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _UpperCAmelCase = {0: "batch", 1: "choice", 2: "sequence"} else: _UpperCAmelCase = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
657
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case = {"""configuration_opt""": ["""OPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OPTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """OPT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OPTForCausalLM""", """OPTModel""", """OPTPreTrainedModel""", """OPTForSequenceClassification""", """OPTForQuestionAnswering""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = ["""TFOPTForCausalLM""", """TFOPTModel""", """TFOPTPreTrainedModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """FlaxOPTForCausalLM""", """FlaxOPTModel""", """FlaxOPTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" return "".join([hex(UpperCamelCase__ )[2:].zfill(2 ).upper() for byte in list(UpperCamelCase__ )] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if (len(UpperCamelCase__ ) % 2) != 0: raise ValueError( "Base16 encoded data is invalid:\nData does not have an even number of hex digits." ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(UpperCamelCase__ ) <= set("0123456789ABCDEF" ): raise ValueError( "Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters." ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(UpperCamelCase__ ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
657
0
from statistics import mean import numpy as np def lowercase__( A , A , A , A ): snake_case__ : Tuple = 0 # Number of processes finished snake_case__ : Optional[Any] = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. snake_case__ : Dict = [0] * no_of_process # List to include calculation results snake_case__ : Optional[Any] = [0] * no_of_process # Sort by arrival time. snake_case__ : int = [burst_time[i] for i in np.argsort(UpperCamelCase__ )] snake_case__ : int = [process_name[i] for i in np.argsort(UpperCamelCase__ )] arrival_time.sort() while no_of_process > finished_process_count: snake_case__ : List[Any] = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: snake_case__ : List[Any] = arrival_time[i] snake_case__ : Union[str, Any] = 0 # Index showing the location of the process being performed snake_case__ : Optional[int] = 0 # Saves the current response ratio. snake_case__ : List[Any] = 0 for i in range(0 , UpperCamelCase__ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: snake_case__ : Optional[int] = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: snake_case__ : Tuple = temp snake_case__ : Union[str, Any] = i # Calculate the turn around time snake_case__ : Union[str, Any] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. snake_case__ : int = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def lowercase__( A , A , A , A ): snake_case__ : Union[str, Any] = [0] * no_of_process for i in range(0 , UpperCamelCase__ ): snake_case__ : Optional[int] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": lowerCamelCase : Any = 5 lowerCamelCase : str = ['A', 'B', 'C', 'D', 'E'] lowerCamelCase : Tuple = [1, 2, 3, 4, 5] lowerCamelCase : Tuple = [1, 2, 3, 4, 5] lowerCamelCase : Optional[Any] = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) lowerCamelCase : Optional[Any] = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print('Process name \tArrival time \tBurst time \tTurn around time \tWaiting time') for i in range(0, no_of_process): print( F"""{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t""" F"""{turn_around_time[i]}\t\t\t{waiting_time[i]}""" ) print(F"""average waiting time : {mean(waiting_time):.5f}""") print(F"""average turn around time : {mean(turn_around_time):.5f}""")
170
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" try: _UpperCAmelCase = float(UpperCamelCase__ ) except ValueError: raise ValueError("Please enter a valid number" ) _UpperCAmelCase = decimal - int(UpperCamelCase__ ) if fractional_part == 0: return int(UpperCamelCase__ ), 1 else: _UpperCAmelCase = len(str(UpperCamelCase__ ).split("." )[1] ) _UpperCAmelCase = int(decimal * (10**number_of_frac_digits) ) _UpperCAmelCase = 10**number_of_frac_digits _UpperCAmelCase , _UpperCAmelCase = denominator, numerator while True: _UpperCAmelCase = dividend % divisor if remainder == 0: break _UpperCAmelCase , _UpperCAmelCase = divisor, remainder _UpperCAmelCase , _UpperCAmelCase = numerator / divisor, denominator / divisor return int(UpperCamelCase__ ), int(UpperCamelCase__ ) if __name__ == "__main__": print(f'''{decimal_to_fraction(2) = }''') print(f'''{decimal_to_fraction(89.0) = }''') print(f'''{decimal_to_fraction("67") = }''') print(f'''{decimal_to_fraction("45.0") = }''') print(f'''{decimal_to_fraction(1.5) = }''') print(f'''{decimal_to_fraction("6.25") = }''') print(f'''{decimal_to_fraction("78td") = }''')
657
0
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _lowerCAmelCase ( self ) -> Any: snake_case_ : List[Any] = TFXLMRobertaModel.from_pretrained("jplu/tf-xlm-roberta-base" ) snake_case_ : str = { "input_ids": tf.convert_to_tensor([[0, 2646, 1_0269, 83, 9_9942, 2]] , dtype=tf.intaa ), # "My dog is cute" "attention_mask": tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } snake_case_ : Any = model(a_ )["last_hidden_state"] snake_case_ : Union[str, Any] = tf.TensorShape((1, 6, 768) ) self.assertEqual(output.shape , a_ ) # compare the actual values for a slice. snake_case_ : int = tf.convert_to_tensor( [ [ [0.068_1762, 0.1089_4451, 0.0677_2504], [-0.0642_3668, 0.0236_6615, 0.0432_9344], [-0.0605_7295, 0.0997_4135, -0.0007_0584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
568
"""simple docstring""" # Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, nicht wahr?", } # BLUE scores as follows: # "pair": [fairseq, transformers] _UpperCAmelCase = { "wmt16-en-de-dist-12-1": [28.3, 27.52], "wmt16-en-de-dist-6-1": [27.4, 27.11], "wmt16-en-de-12-1": [26.9, 25.75], } _UpperCAmelCase = f"{src_lang}-{tgt_lang}" _UpperCAmelCase = f"\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"allenai/{model_name}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel | fairseq | transformers\n-------|---------|----------\n{model_name} | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don't use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n year={{2020}},\n eprint={{2006.10369}},\n archivePrefix={{arXiv}},\n primaryClass={{cs.CL}}\n}}\n```\n\n" model_card_dir.mkdir(parents=UpperCamelCase__ , exist_ok=UpperCamelCase__ ) _UpperCAmelCase = os.path.join(UpperCamelCase__ , "README.md" ) print(f"Generating {path}" ) with open(UpperCamelCase__ , "w" , encoding="utf-8" ) as f: f.write(UpperCamelCase__ ) # make sure we are under the root of the project __magic_name__ = Path(__file__).resolve().parent.parent.parent __magic_name__ = repo_dir / '''model_cards''' for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: __magic_name__ = model_cards_dir / '''allenai''' / model_name write_model_card(model_card_dir, src_lang='''en''', tgt_lang='''de''', model_name=model_name)
657
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
117
"""simple docstring""" from ..utils import DummyObject, requires_backends class _lowerCAmelCase ( metaclass=lowerCamelCase ): lowercase_ : Dict = ['''torch''', '''torchsde'''] def __init__( self , *a_ , **a_ ) -> Optional[int]: requires_backends(self , ["torch", "torchsde"] ) @classmethod def _a ( cls , *a_ , **a_ ) -> Optional[Any]: requires_backends(cls , ["torch", "torchsde"] ) @classmethod def _a ( cls , *a_ , **a_ ) -> List[Any]: requires_backends(cls , ["torch", "torchsde"] )
657
0
def __UpperCAmelCase ( __A = 1_0_0_0 ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase__ = -1 UpperCAmelCase__ = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c UpperCAmelCase__ = (n * n - 2 * a * n) // (2 * n - 2 * a) UpperCAmelCase__ = n - a - b if c * c == (a * a + b * b): UpperCAmelCase__ = a * b * c if candidate >= product: UpperCAmelCase__ = candidate return product if __name__ == "__main__": print(f"{solution() = }")
475
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __magic_name__ = logging.get_logger(__name__) class _lowerCAmelCase ( lowerCamelCase ): lowercase_ : Optional[Any] = '''upernet''' def __init__( self , a_=None , a_=512 , a_=0.02 , a_=[1, 2, 3, 6] , a_=True , a_=0.4 , a_=384 , a_=256 , a_=1 , a_=False , a_=255 , **a_ , ) -> List[Any]: super().__init__(**a_ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) _UpperCAmelCase = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(a_ , a_ ): _UpperCAmelCase = backbone_config.get("model_type" ) _UpperCAmelCase = CONFIG_MAPPING[backbone_model_type] _UpperCAmelCase = config_class.from_dict(a_ ) _UpperCAmelCase = backbone_config _UpperCAmelCase = hidden_size _UpperCAmelCase = initializer_range _UpperCAmelCase = pool_scales _UpperCAmelCase = use_auxiliary_head _UpperCAmelCase = auxiliary_loss_weight _UpperCAmelCase = auxiliary_in_channels _UpperCAmelCase = auxiliary_channels _UpperCAmelCase = auxiliary_num_convs _UpperCAmelCase = auxiliary_concat_input _UpperCAmelCase = loss_ignore_index def _a ( self ) -> int: _UpperCAmelCase = copy.deepcopy(self.__dict__ ) _UpperCAmelCase = self.backbone_config.to_dict() _UpperCAmelCase = self.__class__.model_type return output
657
0
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __A (unittest.TestCase ): def _snake_case ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _snake_case ( self ): torch.manual_seed(0 ) __UpperCAmelCase : int = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return model @property def _snake_case ( self ): torch.manual_seed(0 ) __UpperCAmelCase : Any = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , cross_attention_dim=10 , ) return model @property def _snake_case ( self ): torch.manual_seed(0 ) __UpperCAmelCase : int = AutoencoderKL( sample_size=(1_28, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=("DownEncoderBlock2D", "DownEncoderBlock2D") , up_block_types=("UpDecoderBlock2D", "UpDecoderBlock2D") , ) __UpperCAmelCase : List[str] = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return vqvae, unet @slow def _snake_case ( self ): __UpperCAmelCase : List[str] = "cpu" # ensure determinism for the device-dependent torch.Generator __UpperCAmelCase : Tuple = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) __UpperCAmelCase : int = DDPMScheduler() __UpperCAmelCase : List[str] = AudioDiffusionPipeline(vqvae=a_ , unet=self.dummy_unet , mel=a_ , scheduler=a_ ) __UpperCAmelCase : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) __UpperCAmelCase : str = torch.Generator(device=a_ ).manual_seed(42 ) __UpperCAmelCase : Dict = pipe(generator=a_ , steps=4 ) __UpperCAmelCase : Optional[int] = output.audios[0] __UpperCAmelCase : str = output.images[0] __UpperCAmelCase : List[Any] = torch.Generator(device=a_ ).manual_seed(42 ) __UpperCAmelCase : Any = pipe(generator=a_ , steps=4 , return_dict=a_ ) __UpperCAmelCase : Any = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) __UpperCAmelCase : Union[str, Any] = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] __UpperCAmelCase : Tuple = np.frombuffer(image_from_tuple.tobytes() , dtype="uint8" )[:10] __UpperCAmelCase : Optional[int] = np.array([69, 2_55, 2_55, 2_55, 0, 0, 77, 1_81, 12, 1_27] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 __UpperCAmelCase : List[Any] = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) __UpperCAmelCase : Any = DDIMScheduler() __UpperCAmelCase : Tuple = self.dummy_vqvae_and_unet __UpperCAmelCase : int = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=a_ , scheduler=a_ ) __UpperCAmelCase : Union[str, Any] = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) np.random.seed(0 ) __UpperCAmelCase : Optional[Any] = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) __UpperCAmelCase : Optional[Any] = torch.Generator(device=a_ ).manual_seed(42 ) __UpperCAmelCase : Dict = pipe(raw_audio=a_ , generator=a_ , start_step=5 , steps=10 ) __UpperCAmelCase : Tuple = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) __UpperCAmelCase : Optional[int] = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] __UpperCAmelCase : Dict = np.array([1_20, 1_17, 1_10, 1_09, 1_38, 1_67, 1_38, 1_48, 1_32, 1_21] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 __UpperCAmelCase : Any = self.dummy_unet_condition __UpperCAmelCase : int = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=a_ , mel=a_ , scheduler=a_ ) __UpperCAmelCase : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) np.random.seed(0 ) __UpperCAmelCase : Optional[int] = torch.rand((1, 1, 10) ) __UpperCAmelCase : List[str] = pipe(generator=a_ , encoding=a_ ) __UpperCAmelCase : List[Any] = output.images[0] __UpperCAmelCase : List[str] = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] __UpperCAmelCase : List[str] = np.array([1_07, 1_03, 1_20, 1_27, 1_42, 1_22, 1_13, 1_22, 97, 1_11] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class __A (unittest.TestCase ): def _snake_case ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self ): __UpperCAmelCase : int = torch_device __UpperCAmelCase : Optional[int] = DiffusionPipeline.from_pretrained("teticio/audio-diffusion-ddim-256" ) __UpperCAmelCase : Union[str, Any] = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) __UpperCAmelCase : int = torch.Generator(device=a_ ).manual_seed(42 ) __UpperCAmelCase : int = pipe(generator=a_ ) __UpperCAmelCase : Optional[int] = output.audios[0] __UpperCAmelCase : Union[str, Any] = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] __UpperCAmelCase : Tuple = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] __UpperCAmelCase : Union[str, Any] = np.array([1_51, 1_67, 1_54, 1_44, 1_22, 1_34, 1_21, 1_05, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
168
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import _LazyModule __magic_name__ = {'''tokenization_tapex''': ['''TapexTokenizer''']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
657
0
'''simple docstring''' from math import ceil, sqrt def __SCREAMING_SNAKE_CASE ( _UpperCamelCase = 100_0000 ): """simple docstring""" lowercase_ : Tuple = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowercase_ : List[str] = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowercase_ : Tuple = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"""{solution() = }""")
620
"""simple docstring""" import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase : def __init__( self , a_ , a_=2 , a_=3 , a_=4 , a_=2 , a_=7 , a_=True , a_=True , a_=True , a_=True , a_=99 , a_=36 , a_=3 , a_=4 , a_=37 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=16 , a_=2 , a_=0.02 , a_=6 , a_=6 , a_=3 , a_=4 , a_=None , a_=1000 , ) -> Optional[Any]: _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = text_seq_length _UpperCAmelCase = is_training _UpperCAmelCase = use_input_mask _UpperCAmelCase = use_token_type_ids _UpperCAmelCase = use_labels _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = coordinate_size _UpperCAmelCase = shape_size _UpperCAmelCase = num_labels _UpperCAmelCase = num_choices _UpperCAmelCase = scope _UpperCAmelCase = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) _UpperCAmelCase = text_seq_length _UpperCAmelCase = (image_size // patch_size) ** 2 + 1 _UpperCAmelCase = self.text_seq_length + self.image_seq_length def _a ( self ) -> Dict: _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_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]: _UpperCAmelCase = bbox[i, j, 3] _UpperCAmelCase = bbox[i, j, 1] _UpperCAmelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: _UpperCAmelCase = bbox[i, j, 2] _UpperCAmelCase = bbox[i, j, 0] _UpperCAmelCase = t _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_input_mask: _UpperCAmelCase = random_attention_mask([self.batch_size, self.text_seq_length] ) _UpperCAmelCase = None if self.use_token_type_ids: _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) _UpperCAmelCase = None _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) _UpperCAmelCase = LayoutLMvaConfig( 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 , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Tuple: _UpperCAmelCase = LayoutLMvaModel(config=a_ ) model.to(a_ ) model.eval() # text + image _UpperCAmelCase = model(a_ , pixel_values=a_ ) _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ , bbox=a_ , pixel_values=a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ , bbox=a_ , pixel_values=a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only _UpperCAmelCase = model(a_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only _UpperCAmelCase = model(pixel_values=a_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Optional[Any]: _UpperCAmelCase = self.num_labels _UpperCAmelCase = LayoutLMvaForSequenceClassification(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Union[str, Any]: _UpperCAmelCase = self.num_labels _UpperCAmelCase = LayoutLMvaForTokenClassification(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Dict: _UpperCAmelCase = LayoutLMvaForQuestionAnswering(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , start_positions=a_ , end_positions=a_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _a ( self ) -> Optional[int]: _UpperCAmelCase = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = config_and_inputs _UpperCAmelCase = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase_ : Any = False lowercase_ : Dict = False lowercase_ : List[str] = False lowercase_ : str = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) lowercase_ : int = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def _a ( self , a_ , a_ , a_ , a_ , a_ ) -> List[str]: # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = LayoutLMvaModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=a_ , hidden_size=37 ) def _a ( self , a_ , a_ , a_=False ) -> List[str]: _UpperCAmelCase = copy.deepcopy(a_ ) if model_class in get_values(a_ ): _UpperCAmelCase = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(a_ , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a_ ): _UpperCAmelCase = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in get_values(a_ ): _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in [ *get_values(a_ ), ]: _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in [ *get_values(a_ ), ]: _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=a_ , ) return inputs_dict def _a ( self ) -> int: self.config_tester.run_common_tests() def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _UpperCAmelCase = type self.model_tester.create_and_check_model(*a_ ) def _a ( self ) -> int: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a_ ) def _a ( self ) -> Any: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) @slow def _a ( self ) -> List[str]: for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = LayoutLMvaModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class _lowerCAmelCase ( unittest.TestCase ): @cached_property def _a ( self ) -> List[Any]: return LayoutLMvaImageProcessor(apply_ocr=a_ ) if is_vision_available() else None @slow def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ).to(a_ ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=a_ , return_tensors="pt" ).pixel_values.to(a_ ) _UpperCAmelCase = torch.tensor([[1, 2]] ) _UpperCAmelCase = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass _UpperCAmelCase = model( input_ids=input_ids.to(a_ ) , bbox=bbox.to(a_ ) , pixel_values=pixel_values.to(a_ ) , ) # verify the logits _UpperCAmelCase = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , a_ ) _UpperCAmelCase = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(a_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , a_ , atol=1e-4 ) )
657
0
def A_ ( A__ ) -> int: def merge(A__ , A__ ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(UpperCamelCase__ ) <= 1: return collection a__ : Any = len(UpperCamelCase__ ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() lowercase : Union[str, Any] = input("""Enter numbers separated by a comma:\n""").strip() lowercase : Optional[int] = [int(item) for item in user_input.split(""",""")] print(*merge_sort(unsorted), sep=""",""")
302
"""simple docstring""" import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class _lowerCAmelCase ( unittest.TestCase ): lowercase_ : str = MODEL_FOR_MASKED_LM_MAPPING lowercase_ : List[str] = TF_MODEL_FOR_MASKED_LM_MAPPING def _a ( self ) -> Optional[Any]: super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def _a ( self ) -> str: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="tf" ) _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is grouped", "score": 2.1e-05, "token": 38015, "token_str": " grouped"}, {"sequence": "My name is accuser", "score": 2.1e-05, "token": 25506, "token_str": " accuser"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ { "sequence": "The largest city in France is grouped", "score": 2.1e-05, "token": 38015, "token_str": " grouped", }, { "sequence": "The largest city in France is accuser", "score": 2.1e-05, "token": 25506, "token_str": " accuser", }, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, {"sequence": "My name is Patrick", "score": 2e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 1.9e-05, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="pt" ) _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul"}, {"sequence": "My name isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ { "sequence": "The largest city in France is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul", }, {"sequence": "The largest city in France isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Patrick", "score": 2.1e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 2e-05, "token": 2941, "token_str": " Te"}, {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, ] , ) _UpperCAmelCase = unmasker("My name is <mask> <mask>" , top_k=2 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ [ { "score": 2.2e-05, "token": 35676, "token_str": " Maul", "sequence": "<s>My name is Maul<mask></s>", }, {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name isELS<mask></s>"}, ], [ { "score": 2.2e-05, "token": 35676, "token_str": " Maul", "sequence": "<s>My name is<mask> Maul</s>", }, {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name is<mask>ELS</s>"}, ], ] , ) @require_torch_gpu def _a ( self ) -> int: _UpperCAmelCase = pipeline("fill-mask" , model="hf-internal-testing/tiny-random-distilbert" , device=0 , framework="pt" ) # convert model to fp16 pipe.model.half() _UpperCAmelCase = pipe("Paris is the [MASK] of France." ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(a_ , a_ ) @slow @require_torch def _a ( self ) -> int: _UpperCAmelCase = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="pt" ) self.run_large_test(a_ ) @slow @require_tf def _a ( self ) -> int: _UpperCAmelCase = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="tf" ) self.run_large_test(a_ ) def _a ( self , a_ ) -> int: _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ ) , [ {"sequence": "My name is John", "score": 0.008, "token": 610, "token_str": " John"}, {"sequence": "My name is Chris", "score": 0.007, "token": 1573, "token_str": " Chris"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ ) , [ { "sequence": "The largest city in France is Paris", "score": 0.251, "token": 2201, "token_str": " Paris", }, { "sequence": "The largest city in France is Lyon", "score": 0.214, "token": 12790, "token_str": " Lyon", }, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ ) , [ {"sequence": "My name is Patrick", "score": 0.005, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Clara", "score": 0.000, "token": 13606, "token_str": " Clara"}, {"sequence": "My name is Te", "score": 0.000, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _a ( self ) -> Any: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="pt" ) _UpperCAmelCase = None _UpperCAmelCase = None self.run_pipeline_test(a_ , [] ) @require_tf def _a ( self ) -> List[Any]: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="tf" ) _UpperCAmelCase = None _UpperCAmelCase = None self.run_pipeline_test(a_ , [] ) def _a ( self , a_ , a_ , a_ ) -> Optional[Any]: if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("The provided tokenizer has no mask token, (probably reformer or wav2vec2)" ) _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = [ f"This is another {tokenizer.mask_token} test", ] return fill_masker, examples def _a ( self , a_ , a_ ) -> List[str]: _UpperCAmelCase = fill_masker.tokenizer _UpperCAmelCase = fill_masker.model _UpperCAmelCase = fill_masker( f"This is a {tokenizer.mask_token}" , ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = fill_masker([f"This is a {tokenizer.mask_token}"] ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = fill_masker([f"This is a {tokenizer.mask_token}", f"Another {tokenizer.mask_token} great test."] ) self.assertEqual( a_ , [ [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], ] , ) with self.assertRaises(a_ ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(a_ ): fill_masker("This is" ) self.run_test_top_k(a_ , a_ ) self.run_test_targets(a_ , a_ ) self.run_test_top_k_targets(a_ , a_ ) self.fill_mask_with_duplicate_targets_and_top_k(a_ , a_ ) self.fill_mask_with_multiple_masks(a_ , a_ ) def _a ( self , a_ , a_ ) -> Optional[int]: _UpperCAmelCase = tokenizer.get_vocab() _UpperCAmelCase = sorted(vocab.keys() )[:2] # Pipeline argument _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ , targets=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , a_ ) _UpperCAmelCase = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(a_ ) ) # Call argument _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , a_ ) _UpperCAmelCase = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(a_ ) ) # Score equivalence _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) _UpperCAmelCase = [top_mask["token_str"] for top_mask in outputs] _UpperCAmelCase = [top_mask["score"] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(a_ ) == set(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) _UpperCAmelCase = [top_mask["score"] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) # Raises with invalid with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=[""] ) with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets="" ) def _a ( self , a_ , a_ ) -> str: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ , top_k=2 ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=2 ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) def _a ( self , a_ , a_ ) -> List[Any]: _UpperCAmelCase = tokenizer.get_vocab() _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) # top_k=2, ntargets=3 _UpperCAmelCase = sorted(vocab.keys() )[:3] _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=2 , targets=a_ ) # If we use the most probably targets, and filter differently, we should still # have the same results _UpperCAmelCase = [el["token_str"] for el in sorted(a_ , key=lambda a_ : x["score"] , reverse=a_ )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(a_ ).issubset(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=3 , targets=a_ ) # They should yield exactly the same result self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) def _a ( self , a_ , a_ ) -> Optional[Any]: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = tokenizer.get_vocab() # String duplicates + id duplicates _UpperCAmelCase = sorted(vocab.keys() )[:3] _UpperCAmelCase = [targets[0], targets[1], targets[0], targets[2], targets[1]] _UpperCAmelCase = fill_masker(f"My name is {tokenizer.mask_token}" , targets=a_ , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(a_ ) , 3 ) def _a ( self , a_ , a_ ) -> Any: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker( f"This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}" , top_k=2 ) self.assertEqual( a_ , [ [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], ] , )
657
0
'''simple docstring''' import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever UpperCAmelCase_ : List[str] = logging.getLogger(__name__) class _lowerCamelCase ( snake_case_ ): '''simple docstring''' def __init__( self , __lowercase , __lowercase , __lowercase , __lowercase=None ): """simple docstring""" super().__init__( a_ , question_encoder_tokenizer=a_ , generator_tokenizer=a_ , index=a_ , init_retrieval=a_ , ) __A : int = None def snake_case__ ( self , __lowercase ): """simple docstring""" logger.info('initializing retrieval' ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info('dist initialized' ) # needs to be set manually __A : int = self._infer_socket_ifname() # avoid clash with the NCCL port __A : Union[str, Any] = str(distributed_port + 1 ) __A : Any = dist.new_group(ranks=a_ , backend='gloo' ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info('dist not initialized / main' ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def snake_case__ ( self ): """simple docstring""" return dist.get_rank(group=self.process_group ) == 0 def snake_case__ ( self , __lowercase , __lowercase , __lowercase=torch.floataa ): """simple docstring""" __A : Optional[int] = torch.empty(a_ , dtype=a_ ) dist.scatter(a_ , src=0 , scatter_list=a_ , group=self.process_group ) return target_tensor def snake_case__ ( self ): """simple docstring""" __A : List[str] = psutil.net_if_addrs() # a hacky way to deal with varying network interface names __A : Tuple = next((addr for addr in addrs if addr.startswith('e' )) , a_ ) return ifname def snake_case__ ( self , __lowercase , __lowercase ): """simple docstring""" if not dist.is_initialized(): __A ,__A : Any = self._main_retrieve(a_ , a_ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(a_ ) # distributed training __A : Any = dist.get_world_size(group=self.process_group ) # gather logic __A : Union[str, Any] = None if self._is_main(): __A : List[str] = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(a_ )] dist.gather(torch.tensor(a_ ) , dst=0 , gather_list=a_ , group=self.process_group ) # scatter logic __A : Dict = question_hidden_states.shape[0] __A : Any = [] __A : Optional[int] = [] if self._is_main(): assert len(a_ ) == world_size __A ,__A : int = self._main_retrieve(torch.cat(a_ ).numpy() , a_ ) __A ,__A : Union[str, Any] = torch.tensor(a_ ), torch.tensor(a_ ) __A : Union[str, Any] = self._chunk_tensor(a_ , a_ ) __A : Optional[Any] = self._chunk_tensor(a_ , a_ ) __A : Dict = self._scattered(a_ , [n_queries, n_docs] , target_type=torch.intaa ) __A : Optional[int] = self._scattered(a_ , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(a_ )
365
"""simple docstring""" import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class _lowerCAmelCase ( lowerCamelCase ): def _a ( self ) -> List[str]: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> Optional[int]: with self.assertRaises(a_ ): _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def _a ( self ) -> int: with self.assertRaises(a_ ): _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("bool" ) , type=Value("int64" ) ) ) def _a ( self ) -> Optional[Any]: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> int: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , type=Value("int64" ) ) ) def _a ( self ) -> Dict: _UpperCAmelCase = pa.array(TypedSequence([1, 2, 3] , try_type=Value("int32" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , try_type=Value("int64" ) ) ) self.assertEqual(arr.type , pa.string() ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def _a ( self ) -> Tuple: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , type=ArrayaD((1, 3) , "int64" ) ) ) def _a ( self ) -> str: _UpperCAmelCase = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , "int64" ) ) def _a ( self ) -> Tuple: _UpperCAmelCase = pa.array(TypedSequence(["foo", "bar"] , try_type=ArrayaD((1, 3) , "int64" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def _a ( self ) -> List[str]: import PIL.Image _UpperCAmelCase = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( "datasets.arrow_writer.cast_to_python_objects" , side_effect=a_ ) as mock_cast_to_python_objects: _UpperCAmelCase = pa.array(TypedSequence([{"path": None, "bytes": B"image_bytes"}, pil_image] , type=Image() ) ) _UpperCAmelCase , _UpperCAmelCase = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("optimize_list_casting" , a_ ) self.assertFalse(kwargs["optimize_list_casting"] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferReader(UpperCamelCase__ ) if isinstance(UpperCamelCase__ , pa.Buffer ) else pa.memory_map(UpperCamelCase__ ) _UpperCAmelCase = pa.ipc.open_stream(UpperCamelCase__ ) _UpperCAmelCase = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = Features({"labels": ClassLabel(names=["neg", "pos"] )} ) with ArrowWriter(stream=UpperCamelCase__ , features=UpperCamelCase__ ) as writer: writer.write({"labels": 0} ) writer.write({"labels": 1} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pa.ipc.open_stream(UpperCamelCase__ ) _UpperCAmelCase = f.read_all() _UpperCAmelCase = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(UpperCamelCase__ ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: with pytest.raises(UpperCamelCase__ ): writer.write({"col_1": "foo", "col_2": 1} , key=[1, 2] ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: with pytest.raises(UpperCamelCase__ ): writer.write({"col_1": "foo", "col_2": 1} , key=10 ) writer.write({"col_1": "bar", "col_2": 2} , key=10 ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() @pytest.mark.parametrize("writer_batch_size" , [None, 2, 10] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter( stream=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ , hash_salt="split_name" , check_duplicates=UpperCamelCase__ , ) as writer: writer.write({"col_1": "foo", "col_2": 1} , key=1 ) writer.write({"col_1": "bar", "col_2": 2} , key=2 ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) writer.write_batch({"col_1": [], "col_2": []} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_table(pa.Table.from_pydict({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("writer_batch_size" , [None, 1, 10] ) @pytest.mark.parametrize( "fields" , [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() _UpperCAmelCase = pa.schema(UpperCamelCase__ ) if fields else None with ArrowWriter(stream=UpperCamelCase__ , schema=UpperCamelCase__ , writer_batch_size=UpperCamelCase__ ) as writer: writer.write_row(pa.Table.from_pydict({"col_1": ["foo"], "col_2": [1]} ) ) writer.write_row(pa.Table.from_pydict({"col_1": ["bar"], "col_2": [2]} ) ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __lowerCamelCase ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase = {"col_1": pa.string(), "col_2": pa.intaa()} _UpperCAmelCase = os.path.join(UpperCamelCase__ , "test.arrow" ) with ArrowWriter(path=UpperCamelCase__ , schema=pa.schema(UpperCamelCase__ ) ) as writer: writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(UpperCamelCase__ , metadata=writer._schema.metadata ) _check_output(UpperCamelCase__ , 1 ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if pa.types.is_list(UpperCamelCase__ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if isinstance(lst[0] , UpperCamelCase__ ): change_first_primitive_element_in_list(lst[0] , UpperCamelCase__ ) else: _UpperCAmelCase = value @pytest.mark.parametrize("optimized_int_type, expected_dtype" , [(None, pa.intaa()), (Value("int32" ), pa.intaa())] ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.array(TypedSequence(UpperCamelCase__ , optimized_int_type=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( "col, expected_dtype" , [ ("attention_mask", pa.inta()), ("special_tokens_mask", pa.inta()), ("token_type_ids", pa.inta()), ("input_ids", pa.intaa()), ("other", pa.intaa()), ] , ) @pytest.mark.parametrize("sequence" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = pa.array(OptimizedTypedSequence(UpperCamelCase__ , col=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications _UpperCAmelCase = copy.deepcopy(UpperCamelCase__ ) _UpperCAmelCase = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(UpperCamelCase__ , UpperCamelCase__ ) _UpperCAmelCase = pa.array(OptimizedTypedSequence(UpperCamelCase__ , col=UpperCamelCase__ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("raise_exception" , [False, True] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = str(tmp_path / "dataset-train.arrow" ) try: with ArrowWriter(path=UpperCamelCase__ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = "mock://dataset-train.arrow" with ArrowWriter(path=UpperCamelCase__ , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(UpperCamelCase__ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(UpperCamelCase__ ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.BufferOutputStream() with ParquetWriter(stream=UpperCamelCase__ ) as writer: writer.write({"col_1": "foo", "col_2": 1} ) writer.write({"col_1": "bar", "col_2": 2} ) _UpperCAmelCase , _UpperCAmelCase = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pq.read_table(UpperCamelCase__ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("embed_local_files" , [False, True] ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" import PIL.Image _UpperCAmelCase = str(tmp_path / "test_image_rgb.jpg" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(UpperCamelCase__ , format="png" ) _UpperCAmelCase = pa.BufferOutputStream() with ParquetWriter( stream=UpperCamelCase__ , features=Features({"image": Image()} ) , embed_local_files=UpperCamelCase__ ) as writer: writer.write({"image": image_path} ) writer.finalize() _UpperCAmelCase = pa.BufferReader(output.getvalue() ) _UpperCAmelCase = pq.read_table(UpperCamelCase__ ) _UpperCAmelCase = pa_table.to_pydict() if embed_local_files: assert isinstance(out["image"][0]["path"] , UpperCamelCase__ ) with open(UpperCamelCase__ , "rb" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = pa.schema([pa.field("col_1" , pa.string() , nullable=UpperCamelCase__ )] ) _UpperCAmelCase = pa.BufferOutputStream() with ArrowWriter(stream=UpperCamelCase__ ) as writer: writer._build_writer(inferred_schema=UpperCamelCase__ ) assert writer._schema == pa.schema([pa.field("col_1" , pa.string() )] )
657
0
'''simple docstring''' import json import os import unittest from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class UpperCamelCase__( lowerCAmelCase , unittest.TestCase ): __magic_name__ : List[str] = XLMTokenizer __magic_name__ : Optional[int] = False def a__( self : List[str] )-> List[str]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCAmelCase = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] UpperCAmelCase = dict(zip(a_ , range(len(a_ ) ) ) ) UpperCAmelCase = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(a_ ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(a_ ) ) def a__( self : int , lowerCAmelCase : List[Any] )-> Tuple: """simple docstring""" UpperCAmelCase = '''lower newer''' UpperCAmelCase = '''lower newer''' return input_text, output_text def a__( self : Dict )-> int: """simple docstring""" UpperCAmelCase = XLMTokenizer(self.vocab_file , self.merges_file ) UpperCAmelCase = '''lower''' UpperCAmelCase = ['''low''', '''er</w>'''] UpperCAmelCase = tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) UpperCAmelCase = tokens + ['''<unk>'''] UpperCAmelCase = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , a_ ) @slow def a__( self : str )-> str: """simple docstring""" UpperCAmelCase = XLMTokenizer.from_pretrained('''xlm-mlm-en-2048''' ) UpperCAmelCase = tokenizer.encode('''sequence builders''' , add_special_tokens=a_ ) UpperCAmelCase = tokenizer.encode('''multi-sequence build''' , add_special_tokens=a_ ) UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(a_ ) UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(a_ , a_ ) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
210
"""simple docstring""" import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class _lowerCAmelCase ( unittest.TestCase ): def _a ( self ) -> Optional[Any]: _UpperCAmelCase = ["a", "b", "c"] # Defaults to last layer if both are None _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , a_ , a_ ) self.assertEqual(a_ , ["c"] ) self.assertEqual(a_ , [2] ) # Out indices set to match out features _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(["a", "c"] , a_ , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features set to match out indices _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , [0, 2] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [0, 2] ) # Out features selected from negative indices _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices(a_ , [-3, -1] , a_ ) self.assertEqual(a_ , ["a", "c"] ) self.assertEqual(a_ , [-3, -1] ) def _a ( self ) -> Optional[int]: # Stage names must be set with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , a_ ) # Out features must be a list with self.assertRaises(a_ ): verify_out_features_out_indices(("a", "b") , (0, 1) , ["a", "b"] ) # Out features must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 1) , ["a"] ) # Out indices must be a list or tuple with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , 0 , ["a", "b"] ) # Out indices must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , (0, 1) , ["a"] ) # Out features and out indices must be the same length with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0,) , ["a", "b", "c"] ) # Out features should match out indices with self.assertRaises(a_ ): verify_out_features_out_indices(["a", "b"] , (0, 2) , ["a", "b", "c"] ) # Out features and out indices should be in order with self.assertRaises(a_ ): verify_out_features_out_indices(["b", "a"] , (0, 1) , ["a", "b"] ) # Check passes with valid inputs verify_out_features_out_indices(["a", "b", "d"] , (0, 1, -1) , ["a", "b", "c", "d"] ) def _a ( self ) -> int: _UpperCAmelCase = BackboneMixin() _UpperCAmelCase = ["a", "b", "c"] _UpperCAmelCase = ["a", "c"] _UpperCAmelCase = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly _UpperCAmelCase = ["a", "b"] self.assertEqual(backbone.out_features , ["a", "b"] ) self.assertEqual(backbone.out_indices , [0, 1] ) _UpperCAmelCase = [-3, -1] self.assertEqual(backbone.out_features , ["a", "c"] ) self.assertEqual(backbone.out_indices , [-3, -1] )
657
0
from __future__ import annotations def __a ( __UpperCAmelCase : List[str] ) -> Any: # This function is recursive """simple docstring""" lowerCamelCase_ : int = len(UpperCamelCase__ ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else lowerCamelCase_ : Any = array[0] lowerCamelCase_ : str = False lowerCamelCase_ : List[str] = 1 lowerCamelCase_ : int = [] while not is_found and i < array_length: if array[i] < pivot: lowerCamelCase_ : int = True lowerCamelCase_ : Any = [element for element in array[i:] if element >= array[i]] lowerCamelCase_ : Union[str, Any] = longest_subsequence(UpperCamelCase__ ) if len(UpperCamelCase__ ) > len(UpperCamelCase__ ): lowerCamelCase_ : Union[str, Any] = temp_array else: i += 1 lowerCamelCase_ : Optional[int] = [element for element in array[1:] if element >= pivot] lowerCamelCase_ : List[str] = [pivot, *longest_subsequence(UpperCamelCase__ )] if len(UpperCamelCase__ ) > len(UpperCamelCase__ ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
488
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = { '''configuration_electra''': ['''ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ElectraConfig''', '''ElectraOnnxConfig'''], '''tokenization_electra''': ['''ElectraTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''ElectraTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''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: __magic_name__ = [ '''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: __magic_name__ = [ '''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 __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
657
0
import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Dict = VQModel UpperCamelCase_ : int = '''sample''' @property def _A ( self : Any , UpperCAmelCase_ : Tuple=(32, 32) ): SCREAMING_SNAKE_CASE : Union[str, Any] = 4 SCREAMING_SNAKE_CASE : Union[str, Any] = 3 SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((batch_size, num_channels) + sizes ).to(a_ ) return {"sample": image} @property def _A ( self : Dict ): return (3, 32, 32) @property def _A ( self : int ): return (3, 32, 32) def _A ( self : int ): SCREAMING_SNAKE_CASE : List[Any] = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 3, } SCREAMING_SNAKE_CASE : Dict = self.dummy_input return init_dict, inputs_dict def _A ( self : Dict ): pass def _A ( self : Dict ): pass def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = VQModel.from_pretrained("fusing/vqgan-dummy" , output_loading_info=a_ ) self.assertIsNotNone(a_ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(a_ ) SCREAMING_SNAKE_CASE : List[str] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = VQModel.from_pretrained("fusing/vqgan-dummy" ) model.to(a_ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE : Optional[int] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE : Optional[Any] = image.to(a_ ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Tuple = model(a_ ).sample SCREAMING_SNAKE_CASE : int = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE : List[str] = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(a_ , a_ , atol=1E-3 ) )
62
"""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 _lowerCAmelCase ( lowerCamelCase , unittest.TestCase ): lowercase_ : Tuple = BarthezTokenizer lowercase_ : List[Any] = BarthezTokenizerFast lowercase_ : Dict = True lowercase_ : int = True def _a ( self ) -> Any: super().setUp() _UpperCAmelCase = BarthezTokenizerFast.from_pretrained("moussaKam/mbarthez" ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=a_ ) _UpperCAmelCase = tokenizer def _a ( self ) -> List[Any]: _UpperCAmelCase = "<pad>" _UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = 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(a_ ) , 101122 ) def _a ( self ) -> Union[str, Any]: self.assertEqual(self.get_tokenizer().vocab_size , 101122 ) @require_torch def _a ( self ) -> List[Any]: _UpperCAmelCase = ["A long paragraph for summarization.", "Another paragraph for summarization."] _UpperCAmelCase = [0, 57, 3018, 70307, 91, 2] _UpperCAmelCase = self.tokenizer( a_ , max_length=len(a_ ) , padding=a_ , truncation=a_ , return_tensors="pt" ) self.assertIsInstance(a_ , a_ ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) _UpperCAmelCase = batch.input_ids.tolist()[0] self.assertListEqual(a_ , a_ ) def _a ( self ) -> str: if not self.test_rust_tokenizer: return _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = self.get_rust_tokenizer() _UpperCAmelCase = "I was born in 92000, and this is falsé." _UpperCAmelCase = tokenizer.tokenize(a_ ) _UpperCAmelCase = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) _UpperCAmelCase = tokenizer.encode(a_ , add_special_tokens=a_ ) _UpperCAmelCase = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) _UpperCAmelCase = self.get_rust_tokenizer() _UpperCAmelCase = tokenizer.encode(a_ ) _UpperCAmelCase = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def _a ( self ) -> Dict: # fmt: off _UpperCAmelCase = {"input_ids": [[0, 490, 14328, 4507, 354, 47, 43669, 95, 25, 78117, 20215, 19779, 190, 22, 400, 4, 35343, 80310, 603, 86, 24937, 105, 33438, 94762, 196, 39642, 7, 15, 15933, 173, 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, 10534, 87, 25, 66, 3358, 196, 55289, 8, 82961, 81, 2204, 75203, 7, 15, 763, 12956, 216, 178, 14328, 9595, 1377, 69693, 7, 448, 71021, 196, 18106, 1437, 13974, 108, 9083, 4, 49315, 7, 39, 86, 1326, 2793, 46333, 4, 448, 196, 74588, 7, 49315, 7, 39, 21, 822, 38470, 74, 21, 66723, 62480, 8, 22050, 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. _UpperCAmelCase = [ "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=a_ , model_name="moussaKam/mbarthez" , revision="c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6" , sequences=a_ , )
657
0
import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class snake_case__ ( UpperCamelCase_ ): _lowerCAmelCase ='''facebook/bart-large-mnli''' _lowerCAmelCase =( '''This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ''' '''should be the text to classify, and `labels`, which should be the list of labels to use for classification. ''' '''It returns the most likely label in the list of provided `labels` for the input text.''' ) _lowerCAmelCase ='''text_classifier''' _lowerCAmelCase =AutoTokenizer _lowerCAmelCase =AutoModelForSequenceClassification _lowerCAmelCase =['''text''', ['''text''']] _lowerCAmelCase =['''text'''] def UpperCAmelCase__ ( self : List[str] ): super().setup() snake_case__ : Dict = self.model.config snake_case__ : Tuple = -1 for idx, label in config.idalabel.items(): if label.lower().startswith('entail' ): snake_case__ : List[str] = int(a_ ) if self.entailment_id == -1: raise ValueError('Could not determine the entailment ID from the model config, please pass it at init.' ) def UpperCAmelCase__ ( self : int , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Union[str, Any] ): snake_case__ : Union[str, Any] = labels return self.pre_processor( [text] * len(a_ ) , [F'''This example is {label}''' for label in labels] , return_tensors='pt' , padding='max_length' , ) def UpperCAmelCase__ ( self : Optional[Any] , _lowerCamelCase : Tuple ): snake_case__ : Optional[Any] = outputs.logits snake_case__ : List[Any] = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
170
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): _UpperCAmelCase = f"Input value of [number={number}] must be an integer" raise TypeError(UpperCamelCase__ ) if number < 0: return False _UpperCAmelCase = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
657
0
import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging lowercase : List[Any] = logging.get_logger(__name__) class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def __init__( self , _SCREAMING_SNAKE_CASE ) -> List[Any]: super().__init__() snake_case_ : Optional[int] = nn.ModuleList(a_ ) def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = True , ) -> Union[ControlNetOutput, Tuple]: for i, (image, scale, controlnet) in enumerate(zip(a_ , a_ , self.nets ) ): snake_case_ , snake_case_ : Dict = controlnet( a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ) # merge samples if i == 0: snake_case_ , snake_case_ : int = down_samples, mid_sample else: snake_case_ : str = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(a_ , a_ ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def _lowerCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> str: snake_case_ : Union[str, Any] = 0 snake_case_ : Union[str, Any] = save_directory for controlnet in self.nets: controlnet.save_pretrained( a_ , is_main_process=a_ , save_function=a_ , safe_serialization=a_ , variant=a_ , ) idx += 1 snake_case_ : Tuple = model_path_to_save + f'''_{idx}''' @classmethod def _lowerCAmelCase ( cls , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Any: snake_case_ : List[str] = 0 snake_case_ : Any = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... snake_case_ : List[str] = pretrained_model_path while os.path.isdir(a_ ): snake_case_ : Union[str, Any] = ControlNetModel.from_pretrained(a_ , **a_ ) controlnets.append(a_ ) idx += 1 snake_case_ : str = pretrained_model_path + f'''_{idx}''' logger.info(f'''{len(a_ )} controlnets loaded from {pretrained_model_path}.''' ) if len(a_ ) == 0: raise ValueError( f'''No ControlNets found under {os.path.dirname(a_ )}. Expected at least {pretrained_model_path + '_0'}.''' ) return cls(a_ )
568
"""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(lowerCamelCase ) class _lowerCAmelCase ( lowerCamelCase ): def __init__( self , *a_ , **a_ ) -> Optional[int]: super().__init__(*a_ , **a_ ) 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 _a ( self , **a_ ) -> List[str]: _UpperCAmelCase = {} if "threshold" in kwargs: _UpperCAmelCase = kwargs["threshold"] return {}, {}, postprocess_kwargs def __call__( self , *a_ , **a_ ) -> Union[Predictions, List[Prediction]]: return super().__call__(*a_ , **a_ ) def _a ( self , a_ ) -> Optional[Any]: _UpperCAmelCase = load_image(a_ ) _UpperCAmelCase = torch.IntTensor([[image.height, image.width]] ) _UpperCAmelCase = self.image_processor(images=[image] , return_tensors="pt" ) if self.tokenizer is not None: _UpperCAmelCase = self.tokenizer(text=inputs["words"] , boxes=inputs["boxes"] , return_tensors="pt" ) _UpperCAmelCase = target_size return inputs def _a ( self , a_ ) -> Optional[Any]: _UpperCAmelCase = model_inputs.pop("target_size" ) _UpperCAmelCase = self.model(**a_ ) _UpperCAmelCase = outputs.__class__({"target_size": target_size, **outputs} ) if self.tokenizer is not None: _UpperCAmelCase = model_inputs["bbox"] return model_outputs def _a ( self , a_ , a_=0.9 ) -> int: _UpperCAmelCase = 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. _UpperCAmelCase , _UpperCAmelCase = target_size[0].tolist() def unnormalize(a_ ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) _UpperCAmelCase , _UpperCAmelCase = model_outputs["logits"].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) _UpperCAmelCase = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] _UpperCAmelCase = [unnormalize(a_ ) for bbox in model_outputs["bbox"].squeeze(0 )] _UpperCAmelCase = ["score", "label", "box"] _UpperCAmelCase = [dict(zip(a_ , a_ ) ) for vals in zip(scores.tolist() , a_ , a_ ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel _UpperCAmelCase = self.image_processor.post_process_object_detection(a_ , a_ , a_ ) _UpperCAmelCase = raw_annotations[0] _UpperCAmelCase = raw_annotation["scores"] _UpperCAmelCase = raw_annotation["labels"] _UpperCAmelCase = raw_annotation["boxes"] _UpperCAmelCase = scores.tolist() _UpperCAmelCase = [self.model.config.idalabel[label.item()] for label in labels] _UpperCAmelCase = [self._get_bounding_box(a_ ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] _UpperCAmelCase = ["score", "label", "box"] _UpperCAmelCase = [ dict(zip(a_ , a_ ) ) for vals in zip(raw_annotation["scores"] , raw_annotation["labels"] , raw_annotation["boxes"] ) ] return annotation def _a ( self , a_ ) -> Dict[str, int]: if self.framework != "pt": raise ValueError("The ObjectDetectionPipeline is only available in PyTorch." ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = box.int().tolist() _UpperCAmelCase = { "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax, } return bbox
657
0
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : Optional[Any]=13 , __UpperCAmelCase : Optional[Any]=7 , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : List[str]=True , __UpperCAmelCase : Any=True , __UpperCAmelCase : Optional[Any]=True , __UpperCAmelCase : Optional[Any]=99 , __UpperCAmelCase : Optional[int]=32 , __UpperCAmelCase : Optional[Any]=5 , __UpperCAmelCase : Union[str, Any]=4 , __UpperCAmelCase : Optional[int]=37 , __UpperCAmelCase : Optional[Any]="gelu" , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : Union[str, Any]=0.1 , __UpperCAmelCase : Any=512 , __UpperCAmelCase : Tuple=16 , __UpperCAmelCase : Dict=2 , __UpperCAmelCase : str=0.02 , __UpperCAmelCase : int=4 , ) ->Union[str, Any]: """simple docstring""" a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices def __lowerCAmelCase ( self : List[str] ) ->Tuple: """simple docstring""" a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , tie_weights_=a_ , ) return config, input_ids, attention_mask def __lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" a = self.prepare_config_and_inputs() a , a , a = config_and_inputs a = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def __lowerCAmelCase ( self : Tuple ) ->Union[str, Any]: """simple docstring""" a = FlaxDistilBertModelTester(self ) @slow def __lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained('''distilbert-base-uncased''' ) a = model(np.ones((1, 1) ) ) self.assertIsNotNone(a_ ) @require_flax class lowercase_ ( unittest.TestCase ): '''simple docstring''' @slow def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" a = FlaxDistilBertModel.from_pretrained('''distilbert-base-uncased''' ) a = np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) a = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) a = model(a_ , attention_mask=a_ )[0] a = (1, 11, 768) self.assertEqual(output.shape , a_ ) a = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , a_ , atol=1e-4 ) )
117
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def merge(UpperCamelCase__ , UpperCamelCase__ ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(UpperCamelCase__ ) <= 1: return collection _UpperCAmelCase = len(UpperCamelCase__ ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() __magic_name__ = input('''Enter numbers separated by a comma:\n''').strip() __magic_name__ = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
657
0
def __UpperCAmelCase ( __A = 1_0_0_0 ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ = 2**power UpperCAmelCase__ = 0 while n: UpperCAmelCase__ , UpperCAmelCase__ = r + n % 1_0, n // 1_0 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
475
"""simple docstring""" 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 _lowerCAmelCase : def __init__( self , a_ , a_=13 , a_=7 , a_=True , a_=True , a_=True , a_=99 , a_=32 , a_=5 , a_=4 , a_=37 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=16 , a_=2 , a_=0.02 , a_=3 , a_=4 , a_=None , ) -> List[str]: _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = seq_length _UpperCAmelCase = is_training _UpperCAmelCase = use_token_type_ids _UpperCAmelCase = use_labels _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = num_labels _UpperCAmelCase = num_choices _UpperCAmelCase = scope _UpperCAmelCase = self.vocab_size - 1 def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCAmelCase = None if self.use_token_type_ids: _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) _UpperCAmelCase = 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 , ) _UpperCAmelCase = 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 _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Optional[int]: _UpperCAmelCase = OpenAIGPTModel(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , head_mask=a_ ) _UpperCAmelCase = model(a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> List[Any]: _UpperCAmelCase = OpenAIGPTLMHeadModel(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Optional[Any]: _UpperCAmelCase = OpenAIGPTDoubleHeadsModel(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , a_ , a_ , a_ , a_ , *a_ ) -> Dict: _UpperCAmelCase = self.num_labels _UpperCAmelCase = OpenAIGPTForSequenceClassification(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = config_and_inputs _UpperCAmelCase = { "input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask, } return config, inputs_dict @require_torch class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase_ : Any = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowercase_ : Optional[Any] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowercase_ : Union[str, Any] = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def _a ( self , a_ , a_ , a_ , a_ , a_ ) -> Any: 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 _a ( self , a_ , a_ , a_=False ) -> Optional[int]: _UpperCAmelCase = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=a_ , ) _UpperCAmelCase = inputs_dict["labels"] _UpperCAmelCase = inputs_dict["labels"] _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=a_ , ) _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) return inputs_dict def _a ( self ) -> Optional[int]: _UpperCAmelCase = OpenAIGPTModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=a_ , n_embd=37 ) def _a ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def _a ( self ) -> Any: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*a_ ) def _a ( self ) -> Tuple: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*a_ ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a_ ) @slow def _a ( self ) -> int: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = OpenAIGPTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) @require_torch class _lowerCAmelCase ( unittest.TestCase ): @slow def _a ( self ) -> Any: _UpperCAmelCase = OpenAIGPTLMHeadModel.from_pretrained("openai-gpt" ) model.to(a_ ) _UpperCAmelCase = torch.tensor([[481, 4735, 544]] , dtype=torch.long , device=a_ ) # the president is _UpperCAmelCase = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 40477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the _UpperCAmelCase = model.generate(a_ , do_sample=a_ ) self.assertListEqual(output_ids[0].tolist() , a_ )
657
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _a : Union[str, Any] = logging.get_logger(__name__) _a : Any = "▁" _a : List[Any] = {"vocab_file": "spiece.model"} _a : Optional[Any] = { "vocab_file": { "google/reformer-crime-and-punishment": ( "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model" ) } } _a : Optional[Any] = { "google/reformer-crime-and-punishment": 524288, } class __A (__magic_name__ ): snake_case :str = VOCAB_FILES_NAMES snake_case :str = PRETRAINED_VOCAB_FILES_MAP snake_case :List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case :List[str] = ['''input_ids''', '''attention_mask'''] def __init__( self , UpperCamelCase_ , UpperCamelCase_="</s>" , UpperCamelCase_="<unk>" , UpperCamelCase_=[] , UpperCamelCase_ = None , **UpperCamelCase_ , ): __UpperCAmelCase : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=a_ , unk_token=a_ , additional_special_tokens=a_ , sp_model_kwargs=self.sp_model_kwargs , **a_ , ) __UpperCAmelCase : Optional[Any] = vocab_file __UpperCAmelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(a_ ) @property def _snake_case ( self ): return self.sp_model.get_piece_size() def _snake_case ( self ): __UpperCAmelCase : Optional[Any] = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): __UpperCAmelCase : Tuple = self.__dict__.copy() __UpperCAmelCase : int = None return state def __setstate__( self , UpperCamelCase_ ): __UpperCAmelCase : Optional[Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): __UpperCAmelCase : Union[str, Any] = {} __UpperCAmelCase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _snake_case ( self , UpperCamelCase_ ): return self.sp_model.encode(a_ , out_type=a_ ) def _snake_case ( self , UpperCamelCase_ ): return self.sp_model.piece_to_id(a_ ) def _snake_case ( self , UpperCamelCase_ ): if index < self.sp_model.get_piece_size(): __UpperCAmelCase : Any = self.sp_model.IdToPiece(a_ ) return token def _snake_case ( self , UpperCamelCase_ ): __UpperCAmelCase : Dict = [] __UpperCAmelCase : Dict = "" 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(a_ ) + token __UpperCAmelCase : List[str] = [] else: current_sub_tokens.append(a_ ) out_string += self.sp_model.decode(a_ ) return out_string.strip() def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): if not os.path.isdir(a_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __UpperCAmelCase : List[Any] = os.path.join( a_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_ , "wb" ) as fi: __UpperCAmelCase : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,)
168
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__=10 ): """simple docstring""" _UpperCAmelCase = [] for _ in range(UpperCamelCase__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__=10 ): """simple docstring""" _UpperCAmelCase = [] for step in range(UpperCamelCase__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase = os.path.join(UpperCamelCase__ , "schedule.bin" ) torch.save(scheduler.state_dict() , UpperCamelCase__ ) _UpperCAmelCase = torch.load(UpperCamelCase__ ) scheduler.load_state_dict(UpperCamelCase__ ) return lrs @require_torch class _lowerCAmelCase ( unittest.TestCase ): def _a ( self , a_ , a_ , a_ ) -> Optional[int]: self.assertEqual(len(a_ ) , len(a_ ) ) for a, b in zip(a_ , a_ ): self.assertAlmostEqual(a_ , a_ , delta=a_ ) def _a ( self ) -> str: _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=a_ ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(100 ): _UpperCAmelCase = criterion(a_ , a_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=a_ ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = Adafactor( params=[w] , lr=1e-2 , eps=(1e-30, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=a_ , weight_decay=0.0 , relative_step=a_ , scale_parameter=a_ , warmup_init=a_ , ) for _ in range(1000 ): _UpperCAmelCase = criterion(a_ , a_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class _lowerCAmelCase ( unittest.TestCase ): lowercase_ : List[Any] = nn.Linear(50 , 50 ) if is_torch_available() else None lowercase_ : Tuple = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None lowercase_ : Dict = 10 def _a ( self , a_ , a_ , a_ , a_=None ) -> Union[str, Any]: self.assertEqual(len(a_ ) , len(a_ ) ) for a, b in zip(a_ , a_ ): self.assertAlmostEqual(a_ , a_ , delta=a_ , msg=a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = {"num_warmup_steps": 2, "num_training_steps": 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _UpperCAmelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {"num_warmup_steps": 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, "num_cycles": 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, "power": 2.0, "lr_end": 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {"num_warmup_steps": 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _UpperCAmelCase , _UpperCAmelCase = data _UpperCAmelCase = scheduler_func(self.optimizer , **a_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _UpperCAmelCase = unwrap_schedule(a_ , self.num_steps ) self.assertListAlmostEqual( a_ , a_ , tol=1e-2 , msg=f"failed for {scheduler_func} in normal scheduler" , ) _UpperCAmelCase = scheduler_func(self.optimizer , **a_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(a_ ) # wrap to test picklability of the schedule _UpperCAmelCase = unwrap_and_save_reload_schedule(a_ , self.num_steps ) self.assertListEqual(a_ , a_ , msg=f"failed for {scheduler_func} in save and reload" ) class _lowerCAmelCase : def __init__( self , a_ ) -> Union[str, Any]: _UpperCAmelCase = fn def __call__( self , *a_ , **a_ ) -> Union[str, Any]: return self.fn(*a_ , **a_ ) @classmethod def _a ( self , a_ ) -> Dict: _UpperCAmelCase = list(map(self , scheduler.lr_lambdas ) )
657
0
'''simple docstring''' def __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): """simple docstring""" if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowercase_ : List[Any] = F"""Input value of [number={number}] must be an integer""" raise TypeError(UpperCamelCase__ ) if number < 0: return False lowercase_ : List[Any] = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
620
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def __lowerCamelCase ( UpperCamelCase__=None ): """simple docstring""" if subparsers is not None: _UpperCAmelCase = subparsers.add_parser("test" ) else: _UpperCAmelCase = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=UpperCamelCase__ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=UpperCamelCase__ ) return parser def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: _UpperCAmelCase = script_name else: _UpperCAmelCase = f"--config_file={args.config_file} {script_name}" _UpperCAmelCase = ["accelerate-launch"] + test_args.split() _UpperCAmelCase = execute_subprocess_async(UpperCamelCase__ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = test_command_parser() _UpperCAmelCase = parser.parse_args() test_command(UpperCamelCase__ ) if __name__ == "__main__": main()
657
0
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 lowercase : List[Any] = pytest.mark.integration @require_faiss class A__ ( __UpperCAmelCase ): """simple docstring""" def __lowercase ( self) -> Any: '''simple docstring''' a__ : List[str] = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(a_) for x in np.arange(30).tolist()]}) return dset def __lowercase ( self) -> List[Any]: '''simple docstring''' import faiss a__ : List[Any] = self._create_dummy_dataset() a__ : Dict = dset.map( lambda lowercase , lowercase: {"vecs": i * np.ones(5 , dtype=np.floataa)} , with_indices=a_ , keep_in_memory=a_) a__ : Optional[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT) a__ , a__ : Tuple = 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 __lowercase ( self) -> Union[str, Any]: '''simple docstring''' import faiss a__ : Dict = 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 , ) a__ , a__ : List[str] = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa)) self.assertEqual(examples['filename'][0] , 'my_name-train_29') def __lowercase ( self) -> Tuple: '''simple docstring''' import faiss a__ : int = 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=a_) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name) dset.load_faiss_index('vecs2' , tmp_file.name) os.unlink(tmp_file.name) a__ , a__ : Any = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa)) self.assertEqual(examples['filename'][0] , 'my_name-train_29') def __lowercase ( self) -> Any: '''simple docstring''' a__ : Dict = 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(a_ , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa))) def __lowercase ( self) -> Optional[int]: '''simple docstring''' from elasticsearch import Elasticsearch a__ : str = 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: a__ : str = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30) a__ : Tuple = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} a__ : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=a_) a__ , a__ : List[Any] = dset.get_nearest_examples('filename' , 'my_name-train_29') self.assertEqual(examples['filename'][0] , 'my_name-train_29') @require_faiss class A__ ( __UpperCAmelCase ): """simple docstring""" def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' import faiss a__ : Optional[Any] = 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 a__ : Optional[Any] = np.zeros(5 , dtype=np.floataa) a__ : str = 1 a__ , a__ : Tuple = index.search(a_) self.assertRaises(a_ , index.search , query.reshape(-1 , 1)) self.assertGreater(scores[0] , 0) self.assertEqual(indices[0] , 1) # batched queries a__ : str = np.eye(5 , dtype=np.floataa)[::-1] a__ , a__ : Tuple = index.search_batch(a_) self.assertRaises(a_ , index.search_batch , queries[0]) a__ : Optional[int] = [scores[0] for scores in total_scores] a__ : Any = [indices[0] for indices in total_indices] self.assertGreater(np.min(a_) , 0) self.assertListEqual([4, 3, 2, 1, 0] , a_) def __lowercase ( self) -> Any: '''simple docstring''' import faiss a__ : str = FaissIndex(string_factory='Flat') index.add_vectors(np.eye(5 , dtype=np.floataa)) self.assertIsInstance(index.faiss_index , faiss.IndexFlat) a__ : Dict = FaissIndex(string_factory='LSH') index.add_vectors(np.eye(5 , dtype=np.floataa)) self.assertIsInstance(index.faiss_index , faiss.IndexLSH) with self.assertRaises(a_): a__ : Optional[int] = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5)) def __lowercase ( self) -> List[str]: '''simple docstring''' import faiss a__ : Union[str, Any] = faiss.IndexFlat(5) a__ : List[str] = FaissIndex(custom_index=a_) index.add_vectors(np.eye(5 , dtype=np.floataa)) self.assertIsInstance(index.faiss_index , faiss.IndexFlat) def __lowercase ( self) -> int: '''simple docstring''' import faiss a__ : List[Any] = 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=a_) as tmp_file: index.save(tmp_file.name) a__ : Any = FaissIndex.load(tmp_file.name) os.unlink(tmp_file.name) a__ : Dict = np.zeros(5 , dtype=np.floataa) a__ : List[Any] = 1 a__ , a__ : List[Any] = index.search(a_) self.assertGreater(scores[0] , 0) self.assertEqual(indices[0] , 1) @require_faiss def A_ ( A__ ) -> Union[str, Any]: import faiss a__ : List[str] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) a__ : List[str] = 'index.faiss' a__ : Optional[int] = F'mock://{index_name}' index.save(UpperCamelCase__ , storage_options=mockfs.storage_options ) a__ : List[str] = FaissIndex.load(UpperCamelCase__ , storage_options=mockfs.storage_options ) a__ : List[Any] = np.zeros(5 , dtype=np.floataa ) a__ : Tuple = 1 a__ , a__ : Optional[Any] = index.search(UpperCamelCase__ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class A__ ( __UpperCAmelCase ): """simple docstring""" def __lowercase ( self) -> List[str]: '''simple docstring''' 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: a__ : Union[str, Any] = Elasticsearch() a__ : Optional[Any] = {'acknowledged': True} a__ : Optional[int] = ElasticSearchIndex(es_client=a_) mocked_bulk.return_value([(True, None)] * 3) index.add_documents(['foo', 'bar', 'foobar']) # single query a__ : int = 'foo' a__ : Optional[int] = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} a__ , a__ : int = index.search(a_) self.assertEqual(scores[0] , 1) self.assertEqual(indices[0] , 0) # single query with timeout a__ : Dict = 'foo' a__ : Optional[int] = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} a__ , a__ : int = index.search(a_ , request_timeout=30) self.assertEqual(scores[0] , 1) self.assertEqual(indices[0] , 0) # batched queries a__ : List[str] = ['foo', 'bar', 'foobar'] a__ : Dict = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} a__ , a__ : Union[str, Any] = index.search_batch(a_) a__ : Dict = [scores[0] for scores in total_scores] a__ : Union[str, Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(a_) , 0) self.assertListEqual([1, 1, 1] , a_) # batched queries with timeout a__ : Tuple = ['foo', 'bar', 'foobar'] a__ : Union[str, Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} a__ , a__ : Tuple = index.search_batch(a_ , request_timeout=30) a__ : Tuple = [scores[0] for scores in total_scores] a__ : Any = [indices[0] for indices in total_indices] self.assertGreater(np.min(a_) , 0) self.assertListEqual([1, 1, 1] , a_)
302
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" return 10 - x * x def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) >= 0: raise ValueError("Wrong space!" ) _UpperCAmelCase = a while (b - a) >= 0.01: # Find middle point _UpperCAmelCase = (a + b) / 2 # Check if middle point is root if equation(UpperCamelCase__ ) == 0.0: break # Decide the side to repeat the steps if equation(UpperCamelCase__ ) * equation(UpperCamelCase__ ) < 0: _UpperCAmelCase = c else: _UpperCAmelCase = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
657
0
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') UpperCAmelCase_ : Optional[int] = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) UpperCAmelCase_ : int = requests.get(url, headers={'UserAgent': UserAgent().random}) # res.raise_for_status() with open('project1a.html', 'wb') as out_file: # only for knowing the class for data in res.iter_content(1_0_0_0_0): out_file.write(data) UpperCAmelCase_ : str = BeautifulSoup(res.text, 'html.parser') UpperCAmelCase_ : Any = list(soup.select('.eZt8xd'))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('href')) else: webbrowser.open(f'''https://google.com{link.get("href")}''')
365
"""simple docstring""" from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): lowercase_ : Tuple = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self , a_ , a_ , a_ = None , a_ = 50257 , a_ = 1024 , a_ = 768 , a_ = 12 , a_ = 12 , a_ = None , a_ = "gelu_new" , a_ = 0.1 , a_ = 0.1 , a_ = 0.1 , a_ = 1e-5 , a_ = 0.02 , a_ = True , a_ = True , a_ = False , a_ = False , ) -> List[str]: super().__init__() _UpperCAmelCase = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f"`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and" f" `n_embd`: {n_embd} are not equal." ) _UpperCAmelCase = prefix_inner_dim _UpperCAmelCase = prefix_hidden_dim _UpperCAmelCase = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) _UpperCAmelCase = ( nn.Linear(self.prefix_hidden_dim , a_ ) if self.prefix_hidden_dim is not None else nn.Identity() ) _UpperCAmelCase = GPTaConfig( vocab_size=a_ , n_positions=a_ , n_embd=a_ , n_layer=a_ , n_head=a_ , n_inner=a_ , activation_function=a_ , resid_pdrop=a_ , embd_pdrop=a_ , attn_pdrop=a_ , layer_norm_epsilon=a_ , initializer_range=a_ , scale_attn_weights=a_ , use_cache=a_ , scale_attn_by_inverse_layer_idx=a_ , reorder_and_upcast_attn=a_ , ) _UpperCAmelCase = GPTaLMHeadModel(a_ ) def _a ( self , a_ , a_ , a_ = None , a_ = None , ) -> Tuple: _UpperCAmelCase = self.transformer.transformer.wte(a_ ) _UpperCAmelCase = self.encode_prefix(a_ ) _UpperCAmelCase = self.decode_prefix(a_ ) _UpperCAmelCase = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: _UpperCAmelCase = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) _UpperCAmelCase = torch.cat((dummy_token, input_ids) , dim=1 ) _UpperCAmelCase = self.transformer(inputs_embeds=a_ , labels=a_ , attention_mask=a_ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def _a ( self , a_ , a_ ) -> torch.Tensor: return torch.zeros(a_ , self.prefix_length , dtype=torch.intaa , device=a_ ) def _a ( self , a_ ) -> Union[str, Any]: return self.encode_prefix(a_ ) @torch.no_grad() def _a ( self , a_ , a_ , a_ ) -> Union[str, Any]: _UpperCAmelCase = torch.split(a_ , 1 , dim=0 ) _UpperCAmelCase = [] _UpperCAmelCase = [] for feature in features: _UpperCAmelCase = self.decode_prefix(feature.to(a_ ) ) # back to the clip feature # Only support beam search for now _UpperCAmelCase , _UpperCAmelCase = self.generate_beam( input_embeds=a_ , device=a_ , eos_token_id=a_ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) _UpperCAmelCase = torch.stack(a_ ) _UpperCAmelCase = torch.stack(a_ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def _a ( self , a_=None , a_=None , a_=None , a_ = 5 , a_ = 67 , a_ = 1.0 , a_ = None , ) -> Optional[Any]: _UpperCAmelCase = eos_token_id _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = torch.ones(a_ , device=a_ , dtype=torch.int ) _UpperCAmelCase = torch.zeros(a_ , device=a_ , dtype=torch.bool ) if input_embeds is not None: _UpperCAmelCase = input_embeds else: _UpperCAmelCase = self.transformer.transformer.wte(a_ ) for i in range(a_ ): _UpperCAmelCase = self.transformer(inputs_embeds=a_ ) _UpperCAmelCase = outputs.logits _UpperCAmelCase = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) _UpperCAmelCase = logits.softmax(-1 ).log() if scores is None: _UpperCAmelCase , _UpperCAmelCase = logits.topk(a_ , -1 ) _UpperCAmelCase = generated.expand(a_ , *generated.shape[1:] ) _UpperCAmelCase , _UpperCAmelCase = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: _UpperCAmelCase = next_tokens else: _UpperCAmelCase = tokens.expand(a_ , *tokens.shape[1:] ) _UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) else: _UpperCAmelCase = -float(np.inf ) _UpperCAmelCase = 0 _UpperCAmelCase = scores[:, None] + logits seq_lengths[~is_stopped] += 1 _UpperCAmelCase = scores_sum / seq_lengths[:, None] _UpperCAmelCase , _UpperCAmelCase = scores_sum_average.view(-1 ).topk(a_ , -1 ) _UpperCAmelCase = next_tokens // scores_sum.shape[1] _UpperCAmelCase = seq_lengths[next_tokens_source] _UpperCAmelCase = next_tokens % scores_sum.shape[1] _UpperCAmelCase = next_tokens.unsqueeze(1 ) _UpperCAmelCase = tokens[next_tokens_source] _UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) _UpperCAmelCase = generated[next_tokens_source] _UpperCAmelCase = scores_sum_average * seq_lengths _UpperCAmelCase = is_stopped[next_tokens_source] _UpperCAmelCase = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) _UpperCAmelCase = torch.cat((generated, next_token_embed) , dim=1 ) _UpperCAmelCase = is_stopped + next_tokens.eq(a_ ).squeeze() if is_stopped.all(): break _UpperCAmelCase = scores / seq_lengths _UpperCAmelCase = scores.argsort(descending=a_ ) # tokens tensors are already padded to max_seq_length _UpperCAmelCase = [tokens[i] for i in order] _UpperCAmelCase = torch.stack(a_ , dim=0 ) _UpperCAmelCase = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
657
0
'''simple docstring''' from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def lowerCamelCase__ ( ): '''simple docstring''' UpperCAmelCase = HfArgumentParser(UpperCamelCase__ ) UpperCAmelCase = parser.parse_args_into_dataclasses()[0] UpperCAmelCase = TensorFlowBenchmark(args=UpperCamelCase__ ) try: UpperCAmelCase = parser.parse_args_into_dataclasses()[0] except ValueError as e: UpperCAmelCase = '''Arg --no_{0} is no longer used, please use --no-{0} instead.''' UpperCAmelCase = ''' '''.join(str(UpperCamelCase__ ).split(''' ''' )[:-1] ) UpperCAmelCase = '''''' UpperCAmelCase = eval(str(UpperCamelCase__ ).split(''' ''' )[-1] ) UpperCAmelCase = [] 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(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: UpperCAmelCase = full_error_msg + begin_error_msg + str(UpperCamelCase__ ) raise ValueError(UpperCamelCase__ ) benchmark.run() if __name__ == "__main__": main()
210
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable __magic_name__ = {'''configuration_gpt_neox''': ['''GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXConfig''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''GPTNeoXTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXForCausalLM''', '''GPTNeoXForQuestionAnswering''', '''GPTNeoXForSequenceClassification''', '''GPTNeoXForTokenClassification''', '''GPTNeoXLayer''', '''GPTNeoXModel''', '''GPTNeoXPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
657
0
def __a ( __UpperCAmelCase : Dict ) -> Dict: """simple docstring""" lowerCamelCase_ : Optional[Any] = generate_pascal_triangle(UpperCamelCase__ ) for row_idx in range(UpperCamelCase__ ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=" " ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] , end=" " ) else: print(triangle[row_idx][col_idx] , end="" ) print() def __a ( __UpperCAmelCase : Optional[int] ) -> Dict: """simple docstring""" if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) lowerCamelCase_ : int = [] for current_row_idx in range(UpperCamelCase__ ): lowerCamelCase_ : List[str] = populate_current_row(UpperCamelCase__ , UpperCamelCase__ ) triangle.append(UpperCamelCase__ ) return triangle def __a ( __UpperCAmelCase : Optional[int] , __UpperCAmelCase : int ) -> Tuple: """simple docstring""" lowerCamelCase_ : int = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 lowerCamelCase_ , lowerCamelCase_ : Dict = 1, 1 for current_col_idx in range(1 , UpperCamelCase__ ): calculate_current_element( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return current_row def __a ( __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict , ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ : int = triangle[current_row_idx - 1][current_col_idx - 1] lowerCamelCase_ : Optional[int] = triangle[current_row_idx - 1][current_col_idx] lowerCamelCase_ : Any = above_to_left_elt + above_to_right_elt def __a ( __UpperCAmelCase : Dict ) -> Dict: """simple docstring""" if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) lowerCamelCase_ : List[str] = [[1]] for row_index in range(1 , UpperCamelCase__ ): lowerCamelCase_ : List[Any] = [0] + result[-1] + [0] lowerCamelCase_ : List[Any] = row_index + 1 # Calculate the number of distinct elements in a row lowerCamelCase_ : int = sum(divmod(UpperCamelCase__ , 2 ) ) lowerCamelCase_ : Optional[int] = [ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 ) ] lowerCamelCase_ : Union[str, Any] = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() lowerCamelCase_ : Optional[int] = row_first_half + row_second_half result.append(UpperCamelCase__ ) return result def __a ( ) -> int: """simple docstring""" from collections.abc import Callable from timeit import timeit def benchmark_a_function(__UpperCAmelCase : int , __UpperCAmelCase : str ) -> None: lowerCamelCase_ : str = f"{func.__name__}({value})" lowerCamelCase_ : Any = timeit(f"__main__.{call}" , setup="import __main__" ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f"{call:38} -- {timing:.4f} seconds" ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(UpperCamelCase__ , UpperCamelCase__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
488
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { '''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 _lowerCAmelCase ( lowerCamelCase ): lowercase_ : Union[str, Any] = '''convbert''' def __init__( self , a_=30522 , 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_=768 , a_=2 , a_=9 , a_=1 , a_=None , **a_ , ) -> Tuple: super().__init__( pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ , ) _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = embedding_size _UpperCAmelCase = head_ratio _UpperCAmelCase = conv_kernel_size _UpperCAmelCase = num_groups _UpperCAmelCase = classifier_dropout class _lowerCAmelCase ( lowerCamelCase ): @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _UpperCAmelCase = {0: "batch", 1: "choice", 2: "sequence"} else: _UpperCAmelCase = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
657
0
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] = None , UpperCAmelCase_ : List[Any] = 5_0257 , UpperCAmelCase_ : Union[str, Any] = 1024 , UpperCAmelCase_ : Any = 768 , UpperCAmelCase_ : int = 12 , UpperCAmelCase_ : Optional[Any] = 12 , UpperCAmelCase_ : List[str] = None , UpperCAmelCase_ : Optional[Any] = "gelu_new" , UpperCAmelCase_ : Tuple = 0.1 , UpperCAmelCase_ : Tuple = 0.1 , UpperCAmelCase_ : Any = 0.1 , UpperCAmelCase_ : Any = 1E-5 , UpperCAmelCase_ : Any = 0.02 , UpperCAmelCase_ : Tuple = True , UpperCAmelCase_ : Union[str, Any] = True , UpperCAmelCase_ : Dict = False , UpperCAmelCase_ : int = False , ): super().__init__() SCREAMING_SNAKE_CASE : Any = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'''`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and''' f''' `n_embd`: {n_embd} are not equal.''' ) SCREAMING_SNAKE_CASE : Dict = prefix_inner_dim SCREAMING_SNAKE_CASE : List[str] = prefix_hidden_dim SCREAMING_SNAKE_CASE : List[str] = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) SCREAMING_SNAKE_CASE : str = ( nn.Linear(self.prefix_hidden_dim , a_ ) if self.prefix_hidden_dim is not None else nn.Identity() ) SCREAMING_SNAKE_CASE : Dict = GPTaConfig( vocab_size=a_ , n_positions=a_ , n_embd=a_ , n_layer=a_ , n_head=a_ , n_inner=a_ , activation_function=a_ , resid_pdrop=a_ , embd_pdrop=a_ , attn_pdrop=a_ , layer_norm_epsilon=a_ , initializer_range=a_ , scale_attn_weights=a_ , use_cache=a_ , scale_attn_by_inverse_layer_idx=a_ , reorder_and_upcast_attn=a_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = GPTaLMHeadModel(a_ ) def _A ( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any] = None , UpperCAmelCase_ : int = None , ): SCREAMING_SNAKE_CASE : Any = self.transformer.transformer.wte(a_ ) SCREAMING_SNAKE_CASE : List[Any] = self.encode_prefix(a_ ) SCREAMING_SNAKE_CASE : Dict = self.decode_prefix(a_ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat((dummy_token, input_ids) , dim=1 ) SCREAMING_SNAKE_CASE : Optional[Any] = self.transformer(inputs_embeds=a_ , labels=a_ , attention_mask=a_ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def _A ( self : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int ): return torch.zeros(a_ , self.prefix_length , dtype=torch.intaa , device=a_ ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : int ): return self.encode_prefix(a_ ) @torch.no_grad() def _A ( self : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : List[str] = torch.split(a_ , 1 , dim=0 ) SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Union[str, Any] = [] for feature in features: SCREAMING_SNAKE_CASE : Any = self.decode_prefix(feature.to(a_ ) ) # back to the clip feature # Only support beam search for now SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.generate_beam( input_embeds=a_ , device=a_ , eos_token_id=a_ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.stack(a_ ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.stack(a_ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def _A ( self : List[str] , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : str = 5 , UpperCAmelCase_ : List[str] = 67 , UpperCAmelCase_ : int = 1.0 , UpperCAmelCase_ : int = None , ): SCREAMING_SNAKE_CASE : int = eos_token_id SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : List[str] = torch.ones(a_ , device=a_ , dtype=torch.int ) SCREAMING_SNAKE_CASE : Tuple = torch.zeros(a_ , device=a_ , dtype=torch.bool ) if input_embeds is not None: SCREAMING_SNAKE_CASE : Optional[Any] = input_embeds else: SCREAMING_SNAKE_CASE : Optional[Any] = self.transformer.transformer.wte(a_ ) for i in range(a_ ): SCREAMING_SNAKE_CASE : List[Any] = self.transformer(inputs_embeds=a_ ) SCREAMING_SNAKE_CASE : int = outputs.logits SCREAMING_SNAKE_CASE : Optional[int] = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) SCREAMING_SNAKE_CASE : Optional[int] = logits.softmax(-1 ).log() if scores is None: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = logits.topk(a_ , -1 ) SCREAMING_SNAKE_CASE : Any = generated.expand(a_ , *generated.shape[1:] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: SCREAMING_SNAKE_CASE : int = next_tokens else: SCREAMING_SNAKE_CASE : str = tokens.expand(a_ , *tokens.shape[1:] ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.cat((tokens, next_tokens) , dim=1 ) else: SCREAMING_SNAKE_CASE : str = -float(np.inf ) SCREAMING_SNAKE_CASE : List[str] = 0 SCREAMING_SNAKE_CASE : Dict = scores[:, None] + logits seq_lengths[~is_stopped] += 1 SCREAMING_SNAKE_CASE : Any = scores_sum / seq_lengths[:, None] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = scores_sum_average.view(-1 ).topk(a_ , -1 ) SCREAMING_SNAKE_CASE : Optional[int] = next_tokens // scores_sum.shape[1] SCREAMING_SNAKE_CASE : Union[str, Any] = seq_lengths[next_tokens_source] SCREAMING_SNAKE_CASE : List[str] = next_tokens % scores_sum.shape[1] SCREAMING_SNAKE_CASE : Any = next_tokens.unsqueeze(1 ) SCREAMING_SNAKE_CASE : Any = tokens[next_tokens_source] SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat((tokens, next_tokens) , dim=1 ) SCREAMING_SNAKE_CASE : Optional[Any] = generated[next_tokens_source] SCREAMING_SNAKE_CASE : List[str] = scores_sum_average * seq_lengths SCREAMING_SNAKE_CASE : Dict = is_stopped[next_tokens_source] SCREAMING_SNAKE_CASE : str = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) SCREAMING_SNAKE_CASE : Tuple = torch.cat((generated, next_token_embed) , dim=1 ) SCREAMING_SNAKE_CASE : Tuple = is_stopped + next_tokens.eq(a_ ).squeeze() if is_stopped.all(): break SCREAMING_SNAKE_CASE : Union[str, Any] = scores / seq_lengths SCREAMING_SNAKE_CASE : Dict = scores.argsort(descending=a_ ) # tokens tensors are already padded to max_seq_length SCREAMING_SNAKE_CASE : Dict = [tokens[i] for i in order] SCREAMING_SNAKE_CASE : Optional[int] = torch.stack(a_ , dim=0 ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
62
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" return "".join([hex(UpperCamelCase__ )[2:].zfill(2 ).upper() for byte in list(UpperCamelCase__ )] ) def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" if (len(UpperCamelCase__ ) % 2) != 0: raise ValueError( "Base16 encoded data is invalid:\nData does not have an even number of hex digits." ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(UpperCamelCase__ ) <= set("0123456789ABCDEF" ): raise ValueError( "Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters." ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(UpperCamelCase__ ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
657
0
import os def lowercase__( A ): snake_case__ : Any = len(grid[0] ) snake_case__ : Dict = len(UpperCamelCase__ ) snake_case__ : List[str] = 0 snake_case__ : Union[str, Any] = 0 snake_case__ : List[Any] = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(UpperCamelCase__ ): for j in range(n_rows - 3 ): snake_case__ : Optional[int] = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] snake_case__ : Optional[int] = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: snake_case__ : List[Any] = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: snake_case__ : Optional[Any] = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) snake_case__ : str = max( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if max_product > largest: snake_case__ : List[str] = max_product return largest def lowercase__( ): snake_case__ : Any = [] with open(os.path.dirname(UpperCamelCase__ ) + '/grid.txt' ) as file: for line in file: grid.append(line.strip('\n' ).split(' ' ) ) snake_case__ : Union[str, Any] = [[int(UpperCamelCase__ ) for i in grid[j]] for j in range(len(UpperCamelCase__ ) )] return largest_product(UpperCamelCase__ ) if __name__ == "__main__": print(solution())
170
"""simple docstring""" def __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" try: _UpperCAmelCase = float(UpperCamelCase__ ) except ValueError: raise ValueError("Please enter a valid number" ) _UpperCAmelCase = decimal - int(UpperCamelCase__ ) if fractional_part == 0: return int(UpperCamelCase__ ), 1 else: _UpperCAmelCase = len(str(UpperCamelCase__ ).split("." )[1] ) _UpperCAmelCase = int(decimal * (10**number_of_frac_digits) ) _UpperCAmelCase = 10**number_of_frac_digits _UpperCAmelCase , _UpperCAmelCase = denominator, numerator while True: _UpperCAmelCase = dividend % divisor if remainder == 0: break _UpperCAmelCase , _UpperCAmelCase = divisor, remainder _UpperCAmelCase , _UpperCAmelCase = numerator / divisor, denominator / divisor return int(UpperCamelCase__ ), int(UpperCamelCase__ ) if __name__ == "__main__": print(f'''{decimal_to_fraction(2) = }''') print(f'''{decimal_to_fraction(89.0) = }''') print(f'''{decimal_to_fraction("67") = }''') print(f'''{decimal_to_fraction("45.0") = }''') print(f'''{decimal_to_fraction(1.5) = }''') print(f'''{decimal_to_fraction("6.25") = }''') print(f'''{decimal_to_fraction("78td") = }''')
657
0
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput lowercase : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase__ ( _a : List[str] ): warnings.warn( "The preprocess method is deprecated and will be removed in a future version. Please" " use VaeImageProcessor.preprocess instead" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): snake_case_ : str = [image] if isinstance(image[0] , PIL.Image.Image ): snake_case_ , snake_case_ : Any = image[0].size snake_case_ , snake_case_ : Tuple = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 snake_case_ : Tuple = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) )[None, :] for i in image] snake_case_ : Tuple = np.concatenate(UpperCamelCase__ , axis=0 ) snake_case_ : str = np.array(UpperCamelCase__ ).astype(np.floataa ) / 255.0 snake_case_ : Union[str, Any] = image.transpose(0 , 3 , 1 , 2 ) snake_case_ : Optional[int] = 2.0 * image - 1.0 snake_case_ : Tuple = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): snake_case_ : List[str] = torch.cat(UpperCamelCase__ , dim=0 ) return image def lowerCAmelCase__ ( _a : str ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): snake_case_ : int = [mask] if isinstance(mask[0] , PIL.Image.Image ): snake_case_ , snake_case_ : Optional[Any] = mask[0].size snake_case_ , snake_case_ : Union[str, Any] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 snake_case_ : Optional[Any] = [np.array(m.convert("L" ).resize((w, h) , resample=PIL_INTERPOLATION["nearest"] ) )[None, :] for m in mask] snake_case_ : Tuple = np.concatenate(UpperCamelCase__ , axis=0 ) snake_case_ : Optional[int] = mask.astype(np.floataa ) / 255.0 snake_case_ : Optional[int] = 0 snake_case_ : int = 1 snake_case_ : int = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): snake_case_ : Any = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' A : UNetaDModel A : RePaintScheduler def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: super().__init__() self.register_modules(unet=a_ , scheduler=a_ ) @torch.no_grad() def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 250 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = 10 , _SCREAMING_SNAKE_CASE = 10 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , ) -> Union[ImagePipelineOutput, Tuple]: snake_case_ : Union[str, Any] = image snake_case_ : int = _preprocess_image(a_ ) snake_case_ : List[str] = original_image.to(device=self.device , dtype=self.unet.dtype ) snake_case_ : List[Any] = _preprocess_mask(a_ ) snake_case_ : Union[str, Any] = mask_image.to(device=self.device , dtype=self.unet.dtype ) snake_case_ : Union[str, Any] = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(a_ , a_ ) and len(a_ ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(a_ )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) snake_case_ : Dict = original_image.shape snake_case_ : List[str] = randn_tensor(a_ , generator=a_ , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(a_ , a_ , a_ , self.device ) snake_case_ : Dict = eta snake_case_ : str = self.scheduler.timesteps[0] + 1 snake_case_ : Union[str, Any] = generator[0] if isinstance(a_ , a_ ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual snake_case_ : Optional[Any] = self.unet(a_ , a_ ).sample # compute previous image: x_t -> x_t-1 snake_case_ : Optional[int] = self.scheduler.step(a_ , a_ , a_ , a_ , a_ , a_ ).prev_sample else: # compute the reverse: x_t-1 -> x_t snake_case_ : Optional[int] = self.scheduler.undo_step(a_ , a_ , a_ ) snake_case_ : Optional[int] = t snake_case_ : Dict = (image / 2 + 0.5).clamp(0 , 1 ) snake_case_ : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case_ : Union[str, Any] = self.numpy_to_pil(a_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a_ )
568
"""simple docstring""" # Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _UpperCAmelCase = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, nicht wahr?", } # BLUE scores as follows: # "pair": [fairseq, transformers] _UpperCAmelCase = { "wmt16-en-de-dist-12-1": [28.3, 27.52], "wmt16-en-de-dist-6-1": [27.4, 27.11], "wmt16-en-de-12-1": [26.9, 25.75], } _UpperCAmelCase = f"{src_lang}-{tgt_lang}" _UpperCAmelCase = f"\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"allenai/{model_name}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel | fairseq | transformers\n-------|---------|----------\n{model_name} | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don't use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n year={{2020}},\n eprint={{2006.10369}},\n archivePrefix={{arXiv}},\n primaryClass={{cs.CL}}\n}}\n```\n\n" model_card_dir.mkdir(parents=UpperCamelCase__ , exist_ok=UpperCamelCase__ ) _UpperCAmelCase = os.path.join(UpperCamelCase__ , "README.md" ) print(f"Generating {path}" ) with open(UpperCamelCase__ , "w" , encoding="utf-8" ) as f: f.write(UpperCamelCase__ ) # make sure we are under the root of the project __magic_name__ = Path(__file__).resolve().parent.parent.parent __magic_name__ = repo_dir / '''model_cards''' for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: __magic_name__ = model_cards_dir / '''allenai''' / model_name write_model_card(model_card_dir, src_lang='''en''', tgt_lang='''de''', model_name=model_name)
657
0
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def _a ( a :List[Any] , a :List[str] ) -> List[Any]: a = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg''' a = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ).convert('''RGB''' ) a = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48_145_466, 0.4_578_275, 0.40_821_073) , (0.26_862_954, 0.26_130_258, 0.27_577_711) ), ] ) a = transform(UpperCamelCase__ ).unsqueeze(0 ).to(UpperCamelCase__ ) return image def _a ( a :Any ) -> List[Any]: if "visual_encoder" in key: a = re.sub('''visual_encoder*''' , '''vision_model.encoder''' , UpperCamelCase__ ) if "blocks" in key: a = re.sub(r'''blocks''' , '''layers''' , UpperCamelCase__ ) if "attn" in key: a = re.sub(r'''attn''' , '''self_attn''' , UpperCamelCase__ ) if "norm1" in key: a = re.sub(r'''norm1''' , '''layer_norm1''' , UpperCamelCase__ ) if "norm2" in key: a = re.sub(r'''norm2''' , '''layer_norm2''' , UpperCamelCase__ ) if "encoder.norm" in key: a = re.sub(r'''encoder.norm''' , '''post_layernorm''' , UpperCamelCase__ ) if "encoder.patch_embed.proj" in key: a = re.sub(r'''encoder.patch_embed.proj''' , '''embeddings.patch_embedding''' , UpperCamelCase__ ) if "encoder.pos_embed" in key: a = re.sub(r'''encoder.pos_embed''' , '''embeddings.position_embedding''' , UpperCamelCase__ ) if "encoder.cls_token" in key: a = re.sub(r'''encoder.cls_token''' , '''embeddings.class_embedding''' , UpperCamelCase__ ) if "self_attn" in key: a = re.sub(r'''self_attn.proj''' , '''self_attn.projection''' , UpperCamelCase__ ) return key @torch.no_grad() def _a ( a :Optional[Any] , a :Optional[Any]=None ) -> Union[str, Any]: if config_path is not None: a = BlipConfig.from_pretrained(UpperCamelCase__ ) else: a = BlipConfig(projection_dim=512 , text_config={} , vision_config={} ) a = BlipForConditionalGeneration(UpperCamelCase__ ).eval() a = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth''' a = blip_decoder(pretrained=UpperCamelCase__ , image_size=384 , vit='''base''' ) a = pt_model.eval() a = pt_model.state_dict() for key in modified_state_dict.copy(): a = modified_state_dict.pop(UpperCamelCase__ ) a = rename_key(UpperCamelCase__ ) a = value hf_model.load_state_dict(UpperCamelCase__ ) a = 384 a = load_demo_image(image_size=UpperCamelCase__ , device='''cpu''' ) a = BertTokenizer.from_pretrained('''bert-base-uncased''' ) a = tokenizer(['''a picture of'''] ).input_ids a = hf_model.generate(UpperCamelCase__ , UpperCamelCase__ ) assert out[0].tolist() == [30_522, 1_037, 3_861, 1_997, 1_037, 2_450, 3_564, 2_006, 1_996, 3_509, 2_007, 2_014, 3_899, 102] a = hf_model.generate(UpperCamelCase__ ) assert out[0].tolist() == [30_522, 1_037, 2_450, 3_564, 2_006, 1_996, 3_509, 2_007, 2_014, 3_899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(UpperCamelCase__ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' a = ( '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth''' ) a = blip_vqa(pretrained=UpperCamelCase__ , image_size=UpperCamelCase__ , vit='''base''' ) vqa_model.eval() a = vqa_model.state_dict() for key in modified_state_dict.copy(): a = modified_state_dict.pop(UpperCamelCase__ ) a = rename_key(UpperCamelCase__ ) a = value a = BlipForQuestionAnswering(UpperCamelCase__ ) hf_vqa_model.load_state_dict(UpperCamelCase__ ) a = ['''How many dogs are in this image?'''] a = tokenizer(UpperCamelCase__ , return_tensors='''pt''' ).input_ids a = hf_vqa_model.generate(UpperCamelCase__ , UpperCamelCase__ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '''_vqa''' ) a = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth''' a = blip_itm(pretrained=UpperCamelCase__ , image_size=UpperCamelCase__ , vit='''base''' ) itm_model.eval() a = itm_model.state_dict() for key in modified_state_dict.copy(): a = modified_state_dict.pop(UpperCamelCase__ ) a = rename_key(UpperCamelCase__ ) a = value a = BlipForImageTextRetrieval(UpperCamelCase__ ) a = ['''A picture of a woman with a dog sitting in a beach'''] a = tokenizer( UpperCamelCase__ , return_tensors='''pt''' , padding='''max_length''' , truncation=UpperCamelCase__ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(UpperCamelCase__ ) hf_itm_model.eval() a = hf_itm_model(UpperCamelCase__ , UpperCamelCase__ , use_itm_head=UpperCamelCase__ ) a = hf_itm_model(UpperCamelCase__ , UpperCamelCase__ , use_itm_head=UpperCamelCase__ ) assert out[0].item() == 0.2_110_687_494_277_954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.45_698_845_386_505_127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '''_itm''' ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") UpperCAmelCase__ = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
117
"""simple docstring""" from ..utils import DummyObject, requires_backends class _lowerCAmelCase ( metaclass=lowerCamelCase ): lowercase_ : Dict = ['''torch''', '''torchsde'''] def __init__( self , *a_ , **a_ ) -> Optional[int]: requires_backends(self , ["torch", "torchsde"] ) @classmethod def _a ( cls , *a_ , **a_ ) -> Optional[Any]: requires_backends(cls , ["torch", "torchsde"] ) @classmethod def _a ( cls , *a_ , **a_ ) -> List[Any]: requires_backends(cls , ["torch", "torchsde"] )
657
0
def __UpperCAmelCase ( __A , __A ) -> Tuple: '''simple docstring''' UpperCAmelCase__ = 0 UpperCAmelCase__ = len(UpperCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None UpperCAmelCase__ = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None UpperCAmelCase__ = sorted_collection[point] if current_item == item: return point else: if point < left: UpperCAmelCase__ = left UpperCAmelCase__ = point elif point > right: UpperCAmelCase__ = right UpperCAmelCase__ = point else: if item < current_item: UpperCAmelCase__ = point - 1 else: UpperCAmelCase__ = point + 1 return None def __UpperCAmelCase ( __A , __A , __A , __A ) -> Tuple: '''simple docstring''' if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None UpperCAmelCase__ = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) elif point > right: return interpolation_search_by_recursion(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( UpperCamelCase__ , UpperCamelCase__ , point + 1 , UpperCamelCase__ ) def __UpperCAmelCase ( __A ) -> Optional[Any]: '''simple docstring''' if collection != sorted(UpperCamelCase__ ): raise ValueError("Collection must be ascending sorted" ) return True if __name__ == "__main__": import sys A = 0 if debug == 1: A = [10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("Sequence must be ascending sorted to apply interpolation search") A = 67 A = interpolation_search(collection, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
475
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING __magic_name__ = logging.get_logger(__name__) class _lowerCAmelCase ( lowerCamelCase ): lowercase_ : Optional[Any] = '''upernet''' def __init__( self , a_=None , a_=512 , a_=0.02 , a_=[1, 2, 3, 6] , a_=True , a_=0.4 , a_=384 , a_=256 , a_=1 , a_=False , a_=255 , **a_ , ) -> List[Any]: super().__init__(**a_ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) _UpperCAmelCase = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(a_ , a_ ): _UpperCAmelCase = backbone_config.get("model_type" ) _UpperCAmelCase = CONFIG_MAPPING[backbone_model_type] _UpperCAmelCase = config_class.from_dict(a_ ) _UpperCAmelCase = backbone_config _UpperCAmelCase = hidden_size _UpperCAmelCase = initializer_range _UpperCAmelCase = pool_scales _UpperCAmelCase = use_auxiliary_head _UpperCAmelCase = auxiliary_loss_weight _UpperCAmelCase = auxiliary_in_channels _UpperCAmelCase = auxiliary_channels _UpperCAmelCase = auxiliary_num_convs _UpperCAmelCase = auxiliary_concat_input _UpperCAmelCase = loss_ignore_index def _a ( self ) -> int: _UpperCAmelCase = copy.deepcopy(self.__dict__ ) _UpperCAmelCase = self.backbone_config.to_dict() _UpperCAmelCase = self.__class__.model_type return output
657
0
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: _a : Dict = None _a : Tuple = logging.get_logger(__name__) _a : str = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} _a : List[Any] = { "vocab_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json" ), }, } _a : Any = { "facebook/nllb-large-en-ro": 1024, "facebook/nllb-200-distilled-600M": 1024, } # fmt: off _a : str = ["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"] class __A (__magic_name__ ): snake_case :Dict = VOCAB_FILES_NAMES snake_case :Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case :Any = PRETRAINED_VOCAB_FILES_MAP snake_case :List[Any] = ['''input_ids''', '''attention_mask'''] snake_case :str = NllbTokenizer snake_case :List[int] = [] snake_case :List[int] = [] def __init__( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_="<s>" , UpperCamelCase_="</s>" , UpperCamelCase_="</s>" , UpperCamelCase_="<s>" , UpperCamelCase_="<unk>" , UpperCamelCase_="<pad>" , UpperCamelCase_="<mask>" , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=False , **UpperCamelCase_ , ): # Mask token behave like a normal word, i.e. include the space before it __UpperCAmelCase : Optional[int] = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token __UpperCAmelCase : Union[str, Any] = legacy_behaviour super().__init__( vocab_file=a_ , tokenizer_file=a_ , bos_token=a_ , eos_token=a_ , sep_token=a_ , cls_token=a_ , unk_token=a_ , pad_token=a_ , mask_token=a_ , src_lang=a_ , tgt_lang=a_ , additional_special_tokens=a_ , legacy_behaviour=a_ , **a_ , ) __UpperCAmelCase : Dict = vocab_file __UpperCAmelCase : List[str] = False if not self.vocab_file else True __UpperCAmelCase : Optional[int] = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({"additional_special_tokens": _additional_special_tokens} ) __UpperCAmelCase : Any = { lang_code: self.convert_tokens_to_ids(a_ ) for lang_code in FAIRSEQ_LANGUAGE_CODES } __UpperCAmelCase : List[str] = src_lang if src_lang is not None else "eng_Latn" __UpperCAmelCase : Any = self.convert_tokens_to_ids(self._src_lang ) __UpperCAmelCase : List[str] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _snake_case ( self ): return self._src_lang @src_lang.setter def _snake_case ( self , UpperCamelCase_ ): __UpperCAmelCase : Union[str, Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): __UpperCAmelCase : int = [self.sep_token_id] __UpperCAmelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ): if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) __UpperCAmelCase : Optional[int] = src_lang __UpperCAmelCase : List[str] = self(a_ , add_special_tokens=a_ , return_tensors=a_ , **a_ ) __UpperCAmelCase : List[Any] = self.convert_tokens_to_ids(a_ ) __UpperCAmelCase : Tuple = tgt_lang_id return inputs def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = "eng_Latn" , UpperCamelCase_ = None , UpperCamelCase_ = "fra_Latn" , **UpperCamelCase_ , ): __UpperCAmelCase : Union[str, Any] = src_lang __UpperCAmelCase : Dict = tgt_lang return super().prepare_seqaseq_batch(a_ , a_ , **a_ ) def _snake_case ( self ): return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , UpperCamelCase_ ): __UpperCAmelCase : Optional[int] = self.convert_tokens_to_ids(a_ ) if self.legacy_behaviour: __UpperCAmelCase : Tuple = [] __UpperCAmelCase : Union[str, Any] = [self.eos_token_id, self.cur_lang_code] else: __UpperCAmelCase : Optional[int] = [self.cur_lang_code] __UpperCAmelCase : Optional[Any] = [self.eos_token_id] __UpperCAmelCase : List[Any] = self.convert_ids_to_tokens(self.prefix_tokens ) __UpperCAmelCase : Any = self.convert_ids_to_tokens(self.suffix_tokens ) __UpperCAmelCase : int = processors.TemplateProcessing( single=prefix_tokens_str + ["$A"] + suffix_tokens_str , pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _snake_case ( self , UpperCamelCase_ ): __UpperCAmelCase : Optional[Any] = self.convert_tokens_to_ids(a_ ) if self.legacy_behaviour: __UpperCAmelCase : List[Any] = [] __UpperCAmelCase : Optional[Any] = [self.eos_token_id, self.cur_lang_code] else: __UpperCAmelCase : Optional[Any] = [self.cur_lang_code] __UpperCAmelCase : List[str] = [self.eos_token_id] __UpperCAmelCase : List[str] = self.convert_ids_to_tokens(self.prefix_tokens ) __UpperCAmelCase : Optional[Any] = self.convert_ids_to_tokens(self.suffix_tokens ) __UpperCAmelCase : Tuple = processors.TemplateProcessing( single=prefix_tokens_str + ["$A"] + suffix_tokens_str , pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = None ): if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(a_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory.""" ) return __UpperCAmelCase : Tuple = os.path.join( a_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ): copyfile(self.vocab_file , a_ ) return (out_vocab_file,)
168
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import _LazyModule __magic_name__ = {'''tokenization_tapex''': ['''TapexTokenizer''']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
657
0
'''simple docstring''' from jiwer import compute_measures import datasets UpperCamelCase__ = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n' UpperCamelCase__ = '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n' UpperCamelCase__ = '\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> wer = datasets.load_metric("wer")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _UpperCAmelCase ( datasets.Metric ): def lowerCAmelCase__ ( self : int ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def lowerCAmelCase__ ( self : int , a : Union[str, Any]=None , a : Optional[Any]=None , a : Tuple=False ): '''simple docstring''' if concatenate_texts: return compute_measures(a_ , a_ )["wer"] else: lowercase_ : Optional[Any] = 0 lowercase_ : Dict = 0 for prediction, reference in zip(a_ , a_ ): lowercase_ : List[Any] = compute_measures(a_ , a_ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
620
"""simple docstring""" import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase : def __init__( self , a_ , a_=2 , a_=3 , a_=4 , a_=2 , a_=7 , a_=True , a_=True , a_=True , a_=True , a_=99 , a_=36 , a_=3 , a_=4 , a_=37 , a_="gelu" , a_=0.1 , a_=0.1 , a_=512 , a_=16 , a_=2 , a_=0.02 , a_=6 , a_=6 , a_=3 , a_=4 , a_=None , a_=1000 , ) -> Optional[Any]: _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = text_seq_length _UpperCAmelCase = is_training _UpperCAmelCase = use_input_mask _UpperCAmelCase = use_token_type_ids _UpperCAmelCase = use_labels _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = coordinate_size _UpperCAmelCase = shape_size _UpperCAmelCase = num_labels _UpperCAmelCase = num_choices _UpperCAmelCase = scope _UpperCAmelCase = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) _UpperCAmelCase = text_seq_length _UpperCAmelCase = (image_size // patch_size) ** 2 + 1 _UpperCAmelCase = self.text_seq_length + self.image_seq_length def _a ( self ) -> Dict: _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_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]: _UpperCAmelCase = bbox[i, j, 3] _UpperCAmelCase = bbox[i, j, 1] _UpperCAmelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: _UpperCAmelCase = bbox[i, j, 2] _UpperCAmelCase = bbox[i, j, 0] _UpperCAmelCase = t _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_input_mask: _UpperCAmelCase = random_attention_mask([self.batch_size, self.text_seq_length] ) _UpperCAmelCase = None if self.use_token_type_ids: _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) _UpperCAmelCase = None _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) _UpperCAmelCase = LayoutLMvaConfig( 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 , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Tuple: _UpperCAmelCase = LayoutLMvaModel(config=a_ ) model.to(a_ ) model.eval() # text + image _UpperCAmelCase = model(a_ , pixel_values=a_ ) _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ , bbox=a_ , pixel_values=a_ , token_type_ids=a_ ) _UpperCAmelCase = model(a_ , bbox=a_ , pixel_values=a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only _UpperCAmelCase = model(a_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only _UpperCAmelCase = model(pixel_values=a_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Optional[Any]: _UpperCAmelCase = self.num_labels _UpperCAmelCase = LayoutLMvaForSequenceClassification(a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Union[str, Any]: _UpperCAmelCase = self.num_labels _UpperCAmelCase = LayoutLMvaForTokenClassification(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _a ( self , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ ) -> Dict: _UpperCAmelCase = LayoutLMvaForQuestionAnswering(config=a_ ) model.to(a_ ) model.eval() _UpperCAmelCase = model( a_ , bbox=a_ , pixel_values=a_ , attention_mask=a_ , token_type_ids=a_ , start_positions=a_ , end_positions=a_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _a ( self ) -> Optional[int]: _UpperCAmelCase = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = config_and_inputs _UpperCAmelCase = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class _lowerCAmelCase ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase_ : Any = False lowercase_ : Dict = False lowercase_ : List[str] = False lowercase_ : str = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) lowercase_ : int = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def _a ( self , a_ , a_ , a_ , a_ , a_ ) -> List[str]: # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = LayoutLMvaModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=a_ , hidden_size=37 ) def _a ( self , a_ , a_ , a_=False ) -> List[str]: _UpperCAmelCase = copy.deepcopy(a_ ) if model_class in get_values(a_ ): _UpperCAmelCase = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(a_ , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a_ ): _UpperCAmelCase = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in get_values(a_ ): _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in [ *get_values(a_ ), ]: _UpperCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) elif model_class in [ *get_values(a_ ), ]: _UpperCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=a_ , ) return inputs_dict def _a ( self ) -> int: self.config_tester.run_common_tests() def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def _a ( self ) -> List[str]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _UpperCAmelCase = type self.model_tester.create_and_check_model(*a_ ) def _a ( self ) -> int: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a_ ) def _a ( self ) -> Any: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) def _a ( self ) -> List[Any]: _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) @slow def _a ( self ) -> List[str]: for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = LayoutLMvaModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowerCamelCase ( ): """simple docstring""" _UpperCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class _lowerCAmelCase ( unittest.TestCase ): @cached_property def _a ( self ) -> List[Any]: return LayoutLMvaImageProcessor(apply_ocr=a_ ) if is_vision_available() else None @slow def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ).to(a_ ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=a_ , return_tensors="pt" ).pixel_values.to(a_ ) _UpperCAmelCase = torch.tensor([[1, 2]] ) _UpperCAmelCase = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass _UpperCAmelCase = model( input_ids=input_ids.to(a_ ) , bbox=bbox.to(a_ ) , pixel_values=pixel_values.to(a_ ) , ) # verify the logits _UpperCAmelCase = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , a_ ) _UpperCAmelCase = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(a_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , a_ , atol=1e-4 ) )
657
0
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() lowercase : Optional[Any] = logging.get_logger(__name__) lowercase : 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_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""", """encoder.layer_norm_for_extract""": """layer_norm_for_extract""", """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""": """lm_head""", """label_embs_concat""": """label_embeddings_concat""", """mask_emb""": """masked_spec_embed""", """spk_proj""": """speaker_proj""", } lowercase : Optional[int] = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """label_embeddings_concat""", """speaker_proj""", """layer_norm_for_extract""", ] def A_ ( A__ , A__ , A__ , A__ , A__ ) -> Optional[int]: for attribute in key.split('.' ): a__ : Tuple = getattr(UpperCamelCase__ , UpperCamelCase__ ) if weight_type is not None: a__ : Optional[int] = getattr(UpperCamelCase__ , UpperCamelCase__ ).shape else: a__ : List[str] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( 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": a__ : List[str] = value elif weight_type == "weight_g": a__ : Optional[Any] = value elif weight_type == "weight_v": a__ : Tuple = value elif weight_type == "bias": a__ : Optional[int] = value else: a__ : Tuple = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def A_ ( A__ , A__ ) -> Tuple: a__ : List[str] = [] a__ : List[str] = fairseq_model.state_dict() a__ : List[Any] = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): a__ : Optional[Any] = False if "conv_layers" in name: load_conv_layer( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , hf_model.config.feat_extract_norm == 'group' , ) a__ : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): a__ : str = 'unispeech_sat.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('.' )[:-1] ) != key): # special case since naming is very similar continue a__ : Optional[Any] = True if "*" in mapped_key: a__ : Any = name.split(UpperCamelCase__ )[0].split('.' )[-2] a__ : Any = mapped_key.replace('*' , UpperCamelCase__ ) if "weight_g" in name: a__ : Union[str, Any] = 'weight_g' elif "weight_v" in name: a__ : Tuple = 'weight_v' elif "bias" in name: a__ : str = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj a__ : Any = 'weight' else: a__ : Tuple = None set_recursively(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) continue if not is_used: unused_weights.append(UpperCamelCase__ ) logger.warning(F'Unused weights: {unused_weights}' ) def A_ ( A__ , A__ , A__ , A__ , A__ ) -> Tuple: a__ : Union[str, Any] = full_name.split('conv_layers.' )[-1] a__ : Dict = name.split('.' ) a__ : Dict = int(items[0] ) a__ : str = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) a__ : List[str] = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) a__ : Tuple = 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: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.' ) a__ : Union[str, Any] = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) a__ : str = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(UpperCamelCase__ ) @torch.no_grad() def A_ ( A__ , A__ , A__=None , A__=None , A__=True ) -> str: if config_path is not None: a__ : Dict = UniSpeechSatConfig.from_pretrained(UpperCamelCase__ ) else: a__ : List[str] = UniSpeechSatConfig() a__ : str = '' if is_finetuned: a__ : List[str] = UniSpeechSatForCTC(UpperCamelCase__ ) else: a__ : int = UniSpeechSatForPreTraining(UpperCamelCase__ ) a__ , a__ , a__ : Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) a__ : str = model[0].eval() recursively_load_weights(UpperCamelCase__ , UpperCamelCase__ ) hf_wavavec.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": lowercase : Any = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) lowercase : int = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
302
"""simple docstring""" import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class _lowerCAmelCase ( unittest.TestCase ): lowercase_ : str = MODEL_FOR_MASKED_LM_MAPPING lowercase_ : List[str] = TF_MODEL_FOR_MASKED_LM_MAPPING def _a ( self ) -> Optional[Any]: super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def _a ( self ) -> str: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="tf" ) _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is grouped", "score": 2.1e-05, "token": 38015, "token_str": " grouped"}, {"sequence": "My name is accuser", "score": 2.1e-05, "token": 25506, "token_str": " accuser"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ { "sequence": "The largest city in France is grouped", "score": 2.1e-05, "token": 38015, "token_str": " grouped", }, { "sequence": "The largest city in France is accuser", "score": 2.1e-05, "token": 25506, "token_str": " accuser", }, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, {"sequence": "My name is Patrick", "score": 2e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 1.9e-05, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _a ( self ) -> Union[str, Any]: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , top_k=2 , framework="pt" ) _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul"}, {"sequence": "My name isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ { "sequence": "The largest city in France is Maul", "score": 2.2e-05, "token": 35676, "token_str": " Maul", }, {"sequence": "The largest city in France isELS", "score": 2.2e-05, "token": 16416, "token_str": "ELS"}, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ {"sequence": "My name is Patrick", "score": 2.1e-05, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Te", "score": 2e-05, "token": 2941, "token_str": " Te"}, {"sequence": "My name is Clara", "score": 2e-05, "token": 13606, "token_str": " Clara"}, ] , ) _UpperCAmelCase = unmasker("My name is <mask> <mask>" , top_k=2 ) self.assertEqual( nested_simplify(a_ , decimals=6 ) , [ [ { "score": 2.2e-05, "token": 35676, "token_str": " Maul", "sequence": "<s>My name is Maul<mask></s>", }, {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name isELS<mask></s>"}, ], [ { "score": 2.2e-05, "token": 35676, "token_str": " Maul", "sequence": "<s>My name is<mask> Maul</s>", }, {"score": 2.2e-05, "token": 16416, "token_str": "ELS", "sequence": "<s>My name is<mask>ELS</s>"}, ], ] , ) @require_torch_gpu def _a ( self ) -> int: _UpperCAmelCase = pipeline("fill-mask" , model="hf-internal-testing/tiny-random-distilbert" , device=0 , framework="pt" ) # convert model to fp16 pipe.model.half() _UpperCAmelCase = pipe("Paris is the [MASK] of France." ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(a_ , a_ ) @slow @require_torch def _a ( self ) -> int: _UpperCAmelCase = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="pt" ) self.run_large_test(a_ ) @slow @require_tf def _a ( self ) -> int: _UpperCAmelCase = pipeline(task="fill-mask" , model="distilroberta-base" , top_k=2 , framework="tf" ) self.run_large_test(a_ ) def _a ( self , a_ ) -> int: _UpperCAmelCase = unmasker("My name is <mask>" ) self.assertEqual( nested_simplify(a_ ) , [ {"sequence": "My name is John", "score": 0.008, "token": 610, "token_str": " John"}, {"sequence": "My name is Chris", "score": 0.007, "token": 1573, "token_str": " Chris"}, ] , ) _UpperCAmelCase = unmasker("The largest city in France is <mask>" ) self.assertEqual( nested_simplify(a_ ) , [ { "sequence": "The largest city in France is Paris", "score": 0.251, "token": 2201, "token_str": " Paris", }, { "sequence": "The largest city in France is Lyon", "score": 0.214, "token": 12790, "token_str": " Lyon", }, ] , ) _UpperCAmelCase = unmasker("My name is <mask>" , targets=[" Patrick", " Clara", " Teven"] , top_k=3 ) self.assertEqual( nested_simplify(a_ ) , [ {"sequence": "My name is Patrick", "score": 0.005, "token": 3499, "token_str": " Patrick"}, {"sequence": "My name is Clara", "score": 0.000, "token": 13606, "token_str": " Clara"}, {"sequence": "My name is Te", "score": 0.000, "token": 2941, "token_str": " Te"}, ] , ) @require_torch def _a ( self ) -> Any: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="pt" ) _UpperCAmelCase = None _UpperCAmelCase = None self.run_pipeline_test(a_ , [] ) @require_tf def _a ( self ) -> List[Any]: _UpperCAmelCase = pipeline(task="fill-mask" , model="sshleifer/tiny-distilroberta-base" , framework="tf" ) _UpperCAmelCase = None _UpperCAmelCase = None self.run_pipeline_test(a_ , [] ) def _a ( self , a_ , a_ , a_ ) -> Optional[Any]: if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest("The provided tokenizer has no mask token, (probably reformer or wav2vec2)" ) _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = [ f"This is another {tokenizer.mask_token} test", ] return fill_masker, examples def _a ( self , a_ , a_ ) -> List[str]: _UpperCAmelCase = fill_masker.tokenizer _UpperCAmelCase = fill_masker.model _UpperCAmelCase = fill_masker( f"This is a {tokenizer.mask_token}" , ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = fill_masker([f"This is a {tokenizer.mask_token}"] ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = fill_masker([f"This is a {tokenizer.mask_token}", f"Another {tokenizer.mask_token} great test."] ) self.assertEqual( a_ , [ [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], ] , ) with self.assertRaises(a_ ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(a_ ): fill_masker("This is" ) self.run_test_top_k(a_ , a_ ) self.run_test_targets(a_ , a_ ) self.run_test_top_k_targets(a_ , a_ ) self.fill_mask_with_duplicate_targets_and_top_k(a_ , a_ ) self.fill_mask_with_multiple_masks(a_ , a_ ) def _a ( self , a_ , a_ ) -> Optional[int]: _UpperCAmelCase = tokenizer.get_vocab() _UpperCAmelCase = sorted(vocab.keys() )[:2] # Pipeline argument _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ , targets=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , a_ ) _UpperCAmelCase = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(a_ ) ) # Call argument _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = {vocab[el] for el in targets} self.assertEqual({el["token"] for el in outputs} , a_ ) _UpperCAmelCase = [tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el["token_str"] for el in outputs} , set(a_ ) ) # Score equivalence _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) _UpperCAmelCase = [top_mask["token_str"] for top_mask in outputs] _UpperCAmelCase = [top_mask["score"] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(a_ ) == set(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=a_ ) _UpperCAmelCase = [top_mask["score"] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) # Raises with invalid with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets=[""] ) with self.assertRaises(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , targets="" ) def _a ( self , a_ , a_ ) -> str: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ , top_k=2 ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=2 ) self.assertEqual( a_ , [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ] , ) self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) def _a ( self , a_ , a_ ) -> List[Any]: _UpperCAmelCase = tokenizer.get_vocab() _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) # top_k=2, ntargets=3 _UpperCAmelCase = sorted(vocab.keys() )[:3] _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=2 , targets=a_ ) # If we use the most probably targets, and filter differently, we should still # have the same results _UpperCAmelCase = [el["token_str"] for el in sorted(a_ , key=lambda a_ : x["score"] , reverse=a_ )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(a_ ).issubset(a_ ): _UpperCAmelCase = fill_masker(f"This is a {tokenizer.mask_token}" , top_k=3 , targets=a_ ) # They should yield exactly the same result self.assertEqual(nested_simplify(a_ ) , nested_simplify(a_ ) ) def _a ( self , a_ , a_ ) -> Optional[Any]: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = tokenizer.get_vocab() # String duplicates + id duplicates _UpperCAmelCase = sorted(vocab.keys() )[:3] _UpperCAmelCase = [targets[0], targets[1], targets[0], targets[2], targets[1]] _UpperCAmelCase = fill_masker(f"My name is {tokenizer.mask_token}" , targets=a_ , top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(a_ ) , 3 ) def _a ( self , a_ , a_ ) -> Any: _UpperCAmelCase = FillMaskPipeline(model=a_ , tokenizer=a_ ) _UpperCAmelCase = fill_masker( f"This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}" , top_k=2 ) self.assertEqual( a_ , [ [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], [ {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, {"sequence": ANY(a_ ), "score": ANY(a_ ), "token": ANY(a_ ), "token_str": ANY(a_ )}, ], ] , )
657
0