code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
from __future__ import annotations import math def _snake_case ( __snake_case ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__snake_case ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _snake_case ( __snake_case ): _UpperCamelCase = str(__snake_case ) _UpperCamelCase = [n] for i in range(1 , len(__snake_case ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _snake_case ( __snake_case ): if len(str(__snake_case ) ) > 3: if not is_prime(int(str(__snake_case )[-3:] ) ) or not is_prime(int(str(__snake_case )[:3] ) ): return False return True def _snake_case ( __snake_case = 11 ): _UpperCamelCase = [] _UpperCamelCase = 13 while len(__snake_case ) != count: if validate(__snake_case ): _UpperCamelCase = list_truncated_nums(__snake_case ) if all(is_prime(__snake_case ) for i in list_nums ): list_truncated_primes.append(__snake_case ) num += 2 return list_truncated_primes def _snake_case ( ): return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f'{sum(compute_truncated_primes(11)) = }')
71
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _lowerCAmelCase = logging.getLogger(__name__) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether tp freeze the encoder."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) UpperCAmelCase = field( default="summarization", metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"}, ) UpperCAmelCase = field( default=1024, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=128, metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field(default=-1, metadata={"help": "# training examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# validation examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# test examples. -1 means use all."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Source language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Target language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "# num_beams to use for evaluation."} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."}, ) def _snake_case ( __snake_case , __snake_case , __snake_case ): logger.info(f"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(f""" {key} = {metrics[key]}""" ) save_json(__snake_case , os.path.join(__snake_case , f"""{split}_results.json""" ) ) def _snake_case ( ): # 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. _UpperCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_args_into_dataclasses() check_output_dir(__snake_case ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , __snake_case ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _UpperCamelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _UpperCamelCase = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(__snake_case , __snake_case , __snake_case ): assert hasattr(__snake_case , __snake_case ), f"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(__snake_case , __snake_case , getattr(__snake_case , __snake_case ) ) _UpperCamelCase = 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 , ) _UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=__snake_case , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(__snake_case , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: _UpperCamelCase = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(__snake_case , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(__snake_case , __snake_case ): _UpperCamelCase = tokenizer.lang_code_to_id[data_args.tgt_lang] else: _UpperCamelCase = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(__snake_case ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) _UpperCamelCase = SeqaSeqDataset # Get datasets _UpperCamelCase = ( dataset_class( __snake_case , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer _UpperCamelCase = ( build_compute_metrics_fn(data_args.task , __snake_case ) if training_args.predict_with_generate else None ) _UpperCamelCase = SeqaSeqTrainer( model=__snake_case , args=__snake_case , data_args=__snake_case , train_dataset=__snake_case , eval_dataset=__snake_case , data_collator=SeqaSeqDataCollator( __snake_case , __snake_case , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=__snake_case , tokenizer=__snake_case , ) _UpperCamelCase = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) _UpperCamelCase = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) _UpperCamelCase = train_result.metrics _UpperCamelCase = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) _UpperCamelCase = trainer.evaluate(metric_key_prefix='''val''' ) _UpperCamelCase = data_args.n_val _UpperCamelCase = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.do_predict: logger.info('''*** Predict ***''' ) _UpperCamelCase = trainer.predict(test_dataset=__snake_case , metric_key_prefix='''test''' ) _UpperCamelCase = test_output.metrics _UpperCamelCase = data_args.n_test if trainer.is_world_process_zero(): _UpperCamelCase = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.predict_with_generate: _UpperCamelCase = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=__snake_case , clean_up_tokenization_spaces=__snake_case ) _UpperCamelCase = lmap(str.strip , __snake_case ) write_txt_file(__snake_case , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(__snake_case , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def _snake_case ( __snake_case ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
71
1
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "new-model" if is_tf_available(): class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = NewModelConfig @require_tf class lowerCAmelCase_ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = '''bert-base-cased''' _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) _UpperCamelCase = TFAutoModel.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = '''bert-base-cased''' _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) _UpperCamelCase = TFAutoModelForPreTraining.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def UpperCamelCase_ ( self : Optional[Any] ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) _UpperCamelCase = TFAutoModelForCausalLM.from_pretrained(_A ) _UpperCamelCase , _UpperCamelCase = TFAutoModelForCausalLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def UpperCamelCase_ ( self : List[str] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) _UpperCamelCase = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def UpperCamelCase_ ( self : Optional[int] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) _UpperCamelCase = TFAutoModelForMaskedLM.from_pretrained(_A ) _UpperCamelCase , _UpperCamelCase = TFAutoModelForMaskedLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def UpperCamelCase_ ( self : Any ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) _UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(_A ) _UpperCamelCase , _UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(_A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def UpperCamelCase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) _UpperCamelCase = TFAutoModelForSequenceClassification.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow def UpperCamelCase_ ( self : Any ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) _UpperCamelCase = TFAutoModelForQuestionAnswering.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) @slow @require_tensorflow_probability def UpperCamelCase_ ( self : List[str] ): for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) _UpperCamelCase = TFAutoModelForTableQuestionAnswering.from_pretrained(_A ) _UpperCamelCase , _UpperCamelCase = TFAutoModelForTableQuestionAnswering.from_pretrained( _A , output_loading_info=_A ) self.assertIsNotNone(_A ) self.assertIsInstance(_A , _A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsInstance(_A , _A ) self.assertEqual(model.num_parameters() , 1_4410 ) self.assertEqual(model.num_parameters(only_trainable=_A ) , 1_4410 ) def UpperCamelCase_ ( self : Any ): _UpperCamelCase = TFAutoModelWithLMHead.from_pretrained(_A ) self.assertIsInstance(_A , _A ) self.assertEqual(model.num_parameters() , 1_4410 ) self.assertEqual(model.num_parameters(only_trainable=_A ) , 1_4410 ) def UpperCamelCase_ ( self : Optional[int] ): # For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel _UpperCamelCase = TFAutoModel.from_pretrained('''sgugger/funnel-random-tiny''' ) self.assertIsInstance(_A , _A ) _UpperCamelCase = copy.deepcopy(model.config ) _UpperCamelCase = ['''FunnelBaseModel'''] _UpperCamelCase = TFAutoModel.from_config(_A ) self.assertIsInstance(_A , _A ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_A ) _UpperCamelCase = TFAutoModel.from_pretrained(_A ) self.assertIsInstance(_A , _A ) def UpperCamelCase_ ( self : Tuple ): try: AutoConfig.register('''new-model''' , _A ) _UpperCamelCase = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(_A ): auto_class.register(_A , _A ) auto_class.register(_A , _A ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_A ): auto_class.register(_A , _A ) # Now that the config is registered, it can be used as any other config with the auto-API _UpperCamelCase = BertModelTester(self ).get_config() _UpperCamelCase = NewModelConfig(**tiny_config.to_dict() ) _UpperCamelCase = auto_class.from_config(_A ) self.assertIsInstance(_A , _A ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_A ) _UpperCamelCase = auto_class.from_pretrained(_A ) self.assertIsInstance(_A , _A ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def UpperCamelCase_ ( self : Any ): with self.assertRaisesRegex( _A , '''bert-base is not a local folder and is not a valid model identifier''' ): _UpperCamelCase = TFAutoModel.from_pretrained('''bert-base''' ) def UpperCamelCase_ ( self : Optional[Any] ): with self.assertRaisesRegex( _A , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): _UpperCamelCase = TFAutoModel.from_pretrained(_A , revision='''aaaaaa''' ) def UpperCamelCase_ ( self : str ): with self.assertRaisesRegex( _A , '''hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin''' , ): _UpperCamelCase = TFAutoModel.from_pretrained('''hf-internal-testing/config-no-model''' ) def UpperCamelCase_ ( self : Optional[int] ): with self.assertRaisesRegex(_A , '''Use `from_pt=True` to load this model''' ): _UpperCamelCase = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-bert-pt-only''' ) def UpperCamelCase_ ( self : Dict ): # Make sure we have cached the model. _UpperCamelCase = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) with RequestCounter() as counter: _UpperCamelCase = TFAutoModel.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint _UpperCamelCase = TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded''' ) with RequestCounter() as counter: _UpperCamelCase = TFAutoModel.from_pretrained('''ArthurZ/tiny-random-bert-sharded''' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
71
from __future__ import annotations import typing from collections import Counter def _snake_case ( __snake_case ): _UpperCamelCase = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(__snake_case , max_perimeter + 1 ): _UpperCamelCase = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__snake_case ): _UpperCamelCase = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _snake_case ( __snake_case = 1000 ): _UpperCamelCase = pythagorean_triple(__snake_case ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'Perimeter {solution()} has maximum solutions')
71
1
from ..utils import DummyObject, requires_backends class lowerCAmelCase_ ( metaclass=__lowercase ): UpperCAmelCase = ["transformers", "torch", "note_seq"] def __init__( self : int , *_A : List[str] , **_A : List[Any] ): requires_backends(self , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def UpperCamelCase_ ( cls : List[str] , *_A : str , **_A : Optional[int] ): requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def UpperCamelCase_ ( cls : Union[str, Any] , *_A : List[Any] , **_A : Tuple ): requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] )
71
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = (DPMSolverSDEScheduler,) UpperCAmelCase = 10 def UpperCamelCase_ ( self : Tuple , **_A : Union[str, Any] ): _UpperCamelCase = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''noise_sampler_seed''': 0, } config.update(**_A ) return config def UpperCamelCase_ ( self : List[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=_A ) def UpperCamelCase_ ( self : List[Any] ): for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_A , beta_end=_A ) def UpperCamelCase_ ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_A ) def UpperCamelCase_ ( self : Union[str, Any] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_8210_4492_1875 ) < 1e-2 assert abs(result_mean.item() - 0.2178_7059_6456_5277 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3521_1181_6406 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9068_9229_9652 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_1492_0043_9453 ) < 1e-2 assert abs(result_mean.item() - 0.1_6226_2890_1481_6284 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_6633_6059_5703 ) < 1e-2 assert abs(result_mean.item() - 0.1_6688_3260_0116_7297 ) < 1e-3 else: assert abs(result_sum.item() - 119.8_4875_4882_8125 ) < 1e-2 assert abs(result_mean.item() - 0.1560_5306_6253_6621 ) < 1e-3 def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps , device=_A ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter.to(_A ) * scheduler.init_noise_sigma for t in scheduler.timesteps: _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_9573_9746_0938 ) < 1e-2 assert abs(result_mean.item() - 0.2_1805_9346_0798_2635 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3536_3769_5312 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9083_8241_5771 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A , use_karras_sigmas=_A ) scheduler.set_timesteps(self.num_inference_steps , device=_A ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter.to(_A ) * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for t in scheduler.timesteps: _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_9741_3574_2188 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_6535_6445_3125 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 else: assert abs(result_sum.item() - 170.3_1352_2338_8672 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2
71
1
import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup _lowerCAmelCase = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def _snake_case ( __snake_case = "dhaka" , __snake_case = 5 ): _UpperCamelCase = min(__snake_case , 50 ) # Prevent abuse! _UpperCamelCase = { '''q''': query, '''tbm''': '''isch''', '''hl''': '''en''', '''ijn''': '''0''', } _UpperCamelCase = requests.get('''https://www.google.com/search''' , params=__snake_case , headers=__snake_case ) _UpperCamelCase = BeautifulSoup(html.text , '''html.parser''' ) _UpperCamelCase = ''''''.join( re.findall(R'''AF_initDataCallback\(([^<]+)\);''' , str(soup.select('''script''' ) ) ) ) _UpperCamelCase = json.dumps(__snake_case ) _UpperCamelCase = json.loads(__snake_case ) _UpperCamelCase = re.findall( R'''\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",''' , __snake_case , ) if not matched_google_image_data: return 0 _UpperCamelCase = re.sub( R'''\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]''' , '''''' , str(__snake_case ) , ) _UpperCamelCase = re.findall( R'''(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]''' , __snake_case , ) for index, fixed_full_res_image in enumerate(__snake_case ): if index >= max_images: return index _UpperCamelCase = bytes(__snake_case , '''ascii''' ).decode( '''unicode-escape''' ) _UpperCamelCase = bytes(__snake_case , '''ascii''' ).decode( '''unicode-escape''' ) _UpperCamelCase = urllib.request.build_opener() _UpperCamelCase = [ ( '''User-Agent''', '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36''' ''' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582''', ) ] urllib.request.install_opener(__snake_case ) _UpperCamelCase = f"""query_{query.replace(" " , "_" )}""" if not os.path.exists(__snake_case ): os.makedirs(__snake_case ) urllib.request.urlretrieve( # noqa: S310 __snake_case , f"""{path_name}/original_size_img_{index}.jpg""" ) return index if __name__ == "__main__": try: _lowerCAmelCase = download_images_from_google_query(sys.argv[1]) print(f'{image_count} images were downloaded to disk.') except IndexError: print("Please provide a search term.") raise
71
import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class lowerCAmelCase_ : @property def UpperCamelCase_ ( self : Optional[int] ): return self.get_dummy_input() @property def UpperCamelCase_ ( self : Dict ): if self.block_type == "down": return (4, 32, 16, 16) elif self.block_type == "mid": return (4, 32, 32, 32) elif self.block_type == "up": return (4, 32, 64, 64) raise ValueError(F"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'.""" ) def UpperCamelCase_ ( self : Union[str, Any] , _A : List[str]=True , _A : Any=False , _A : Union[str, Any]=False , _A : int=False , ): _UpperCamelCase = 4 _UpperCamelCase = 32 _UpperCamelCase = (32, 32) _UpperCamelCase = torch.manual_seed(0 ) _UpperCamelCase = torch.device(_A ) _UpperCamelCase = (batch_size, num_channels) + sizes _UpperCamelCase = randn_tensor(_A , generator=_A , device=_A ) _UpperCamelCase = {'''hidden_states''': hidden_states} if include_temb: _UpperCamelCase = 128 _UpperCamelCase = randn_tensor((batch_size, temb_channels) , generator=_A , device=_A ) if include_res_hidden_states_tuple: _UpperCamelCase = torch.manual_seed(1 ) _UpperCamelCase = (randn_tensor(_A , generator=_A , device=_A ),) if include_encoder_hidden_states: _UpperCamelCase = floats_tensor((batch_size, 32, 32) ).to(_A ) if include_skip_sample: _UpperCamelCase = randn_tensor(((batch_size, 3) + sizes) , generator=_A , device=_A ) return dummy_input def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = { '''in_channels''': 32, '''out_channels''': 32, '''temb_channels''': 128, } if self.block_type == "up": _UpperCamelCase = 32 if self.block_type == "mid": init_dict.pop('''out_channels''' ) _UpperCamelCase = self.dummy_input return init_dict, inputs_dict def UpperCamelCase_ ( self : Tuple , _A : Union[str, Any] ): _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**_A ) unet_block.to(_A ) unet_block.eval() with torch.no_grad(): _UpperCamelCase = unet_block(**_A ) if isinstance(_A , _A ): _UpperCamelCase = output[0] self.assertEqual(output.shape , self.output_shape ) _UpperCamelCase = output[0, -1, -3:, -3:] _UpperCamelCase = torch.tensor(_A ).to(_A ) assert torch_all_close(output_slice.flatten() , _A , atol=5e-3 ) @unittest.skipIf(torch_device == '''mps''' , '''Training is not supported in mps''' ) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**_A ) model.to(_A ) model.train() _UpperCamelCase = model(**_A ) if isinstance(_A , _A ): _UpperCamelCase = output[0] _UpperCamelCase = torch.device(_A ) _UpperCamelCase = randn_tensor(output.shape , device=_A ) _UpperCamelCase = torch.nn.functional.mse_loss(_A , _A ) loss.backward()
71
1
# 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 from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu _lowerCAmelCase = [ "EAGER", "AOT_EAGER", "INDUCTOR", "NVFUSER", "AOT_NVFUSER", "AOT_CUDAGRAPHS", "OFI", "FX2TRT", "ONNXRT", "IPEX", ] def _snake_case ( __snake_case , __snake_case=None , __snake_case=None , __snake_case=None ): _UpperCamelCase = True while ask_again: _UpperCamelCase = input(__snake_case ) try: if default is not None and len(__snake_case ) == 0: return default return convert_value(__snake_case ) if convert_value is not None else result except Exception: if error_message is not None: print(__snake_case ) def _snake_case ( __snake_case , __snake_case=[] , __snake_case=None , __snake_case=0 ): _UpperCamelCase = BulletMenu(__snake_case , __snake_case ) _UpperCamelCase = menu.run(default_choice=__snake_case ) return convert_value(__snake_case ) if convert_value is not None else result def _snake_case ( __snake_case ): _UpperCamelCase = int(__snake_case ) return ComputeEnvironment(['''LOCAL_MACHINE''', '''AMAZON_SAGEMAKER'''][value] ) def _snake_case ( __snake_case ): _UpperCamelCase = int(__snake_case ) return DistributedType(['''NO''', '''MULTI_CPU''', '''MULTI_XPU''', '''MULTI_GPU''', '''MULTI_NPU''', '''TPU'''][value] ) def _snake_case ( __snake_case ): _UpperCamelCase = int(__snake_case ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _snake_case ( __snake_case ): _UpperCamelCase = int(__snake_case ) return PrecisionType(['''no''', '''fp16''', '''bf16''', '''fp8'''][value] ) def _snake_case ( __snake_case ): _UpperCamelCase = int(__snake_case ) return SageMakerDistributedType(['''NO''', '''DATA_PARALLEL''', '''MODEL_PARALLEL'''][value] ) def _snake_case ( __snake_case ): return {"yes": True, "no": False}[value.lower()] class lowerCAmelCase_ ( argparse.RawDescriptionHelpFormatter ): def UpperCamelCase_ ( self : Any , _A : List[str] , _A : Any , _A : Dict , _A : Union[str, Any] ): _UpperCamelCase = super()._format_usage(_A , _A , _A , _A ) _UpperCamelCase = usage.replace('''<command> [<args>] ''' , '''''' ) return usage
71
def _snake_case ( __snake_case ): if not isinstance(__snake_case , __snake_case ): raise TypeError('''Input value must be an \'int\' type''' ) _UpperCamelCase = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
71
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "BAAI/AltCLIP": "https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json", # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "altclip_text_model" def __init__( self : Optional[Any] , _A : List[str]=25_0002 , _A : Optional[int]=1024 , _A : str=24 , _A : List[Any]=16 , _A : int=4096 , _A : Any="gelu" , _A : Union[str, Any]=0.1 , _A : Optional[int]=0.1 , _A : List[Any]=514 , _A : Any=1 , _A : List[str]=0.02 , _A : List[str]=0.02 , _A : Optional[int]=1e-05 , _A : Dict=1 , _A : Dict=0 , _A : Union[str, Any]=2 , _A : str="absolute" , _A : Optional[Any]=True , _A : Union[str, Any]=768 , **_A : str , ): 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 = hidden_act _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = initializer_range _UpperCamelCase = initializer_factor _UpperCamelCase = layer_norm_eps _UpperCamelCase = position_embedding_type _UpperCamelCase = use_cache _UpperCamelCase = project_dim class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "altclip_vision_model" def __init__( self : str , _A : Optional[Any]=768 , _A : int=3072 , _A : Optional[int]=512 , _A : Optional[int]=12 , _A : List[str]=12 , _A : Any=3 , _A : Optional[Any]=224 , _A : str=32 , _A : Dict="quick_gelu" , _A : List[str]=1e-5 , _A : Dict=0.0 , _A : Dict=0.02 , _A : Union[str, Any]=1.0 , **_A : List[Any] , ): super().__init__(**_A ) _UpperCamelCase = hidden_size _UpperCamelCase = intermediate_size _UpperCamelCase = projection_dim _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = num_channels _UpperCamelCase = patch_size _UpperCamelCase = image_size _UpperCamelCase = initializer_range _UpperCamelCase = initializer_factor _UpperCamelCase = attention_dropout _UpperCamelCase = layer_norm_eps _UpperCamelCase = hidden_act @classmethod def UpperCamelCase_ ( cls : List[str] , _A : Union[str, os.PathLike] , **_A : Tuple ): cls._set_token_in_kwargs(_A ) _UpperCamelCase , _UpperCamelCase = cls.get_config_dict(_A , **_A ) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get('''model_type''' ) == "altclip": _UpperCamelCase = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(_A , **_A ) class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "altclip" UpperCAmelCase = True def __init__( self : List[str] , _A : Tuple=None , _A : Tuple=None , _A : Union[str, Any]=768 , _A : Optional[int]=2.6592 , **_A : Tuple ): # If `_config_dict` exist, we use them for the backward compatibility. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot # of confusion!). _UpperCamelCase = kwargs.pop('''text_config_dict''' , _A ) _UpperCamelCase = kwargs.pop('''vision_config_dict''' , _A ) super().__init__(**_A ) # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. if text_config_dict is not None: if text_config is None: _UpperCamelCase = {} # This is the complete result when using `text_config_dict`. _UpperCamelCase = AltCLIPTextConfig(**_A ).to_dict() # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. for key, value in _text_config_dict.items(): if key in text_config and value != text_config[key] and key not in ["transformers_version"]: # If specified in `text_config_dict` if key in text_config_dict: _UpperCamelCase = ( F"""`{key}` is found in both `text_config_dict` and `text_config` but with different values. """ F"""The value `text_config_dict[\"{key}\"]` will be used instead.""" ) # If inferred from default argument values (just to be super careful) else: _UpperCamelCase = ( F"""`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The """ F"""value `text_config[\"{key}\"]` will be overriden.""" ) logger.warning(_A ) # Update all values in `text_config` with the ones in `_text_config_dict`. text_config.update(_text_config_dict ) if vision_config_dict is not None: if vision_config is None: _UpperCamelCase = {} # This is the complete result when using `vision_config_dict`. _UpperCamelCase = AltCLIPVisionConfig(**_A ).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: _UpperCamelCase = { str(_A ): value for key, value in _vision_config_dict['''id2label'''].items() } # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. for key, value in _vision_config_dict.items(): if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]: # If specified in `vision_config_dict` if key in vision_config_dict: _UpperCamelCase = ( F"""`{key}` is found in both `vision_config_dict` and `vision_config` but with different """ F"""values. The value `vision_config_dict[\"{key}\"]` will be used instead.""" ) # If inferred from default argument values (just to be super careful) else: _UpperCamelCase = ( F"""`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. """ F"""The value `vision_config[\"{key}\"]` will be overriden.""" ) logger.warning(_A ) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict ) if text_config is None: _UpperCamelCase = {} logger.info('''`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.''' ) if vision_config is None: _UpperCamelCase = {} logger.info('''`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.''' ) _UpperCamelCase = AltCLIPTextConfig(**_A ) _UpperCamelCase = AltCLIPVisionConfig(**_A ) _UpperCamelCase = projection_dim _UpperCamelCase = logit_scale_init_value _UpperCamelCase = 1.0 @classmethod def UpperCamelCase_ ( cls : int , _A : AltCLIPTextConfig , _A : AltCLIPVisionConfig , **_A : List[str] ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = copy.deepcopy(self.__dict__ ) _UpperCamelCase = self.text_config.to_dict() _UpperCamelCase = self.vision_config.to_dict() _UpperCamelCase = self.__class__.model_type return output
71
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } _lowerCAmelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): for attribute in key.split('''.''' ): _UpperCamelCase = getattr(__snake_case , __snake_case ) if weight_type is not None: _UpperCamelCase = getattr(__snake_case , __snake_case ).shape else: _UpperCamelCase = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": _UpperCamelCase = value elif weight_type == "weight_g": _UpperCamelCase = value elif weight_type == "weight_v": _UpperCamelCase = value elif weight_type == "bias": _UpperCamelCase = value else: _UpperCamelCase = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = [] _UpperCamelCase = fairseq_model.state_dict() _UpperCamelCase = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _UpperCamelCase = None for name, value in fairseq_dict.items(): _UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __snake_case , __snake_case , __snake_case , __snake_case , hf_model.config.feat_extract_norm == '''group''' , ) _UpperCamelCase = True elif name.split('''.''' )[0] == "proj": _UpperCamelCase = fairseq_model.proj _UpperCamelCase = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: _UpperCamelCase = True if "*" in mapped_key: _UpperCamelCase = name.split(__snake_case )[0].split('''.''' )[-2] _UpperCamelCase = mapped_key.replace('''*''' , __snake_case ) if "weight_g" in name: _UpperCamelCase = '''weight_g''' elif "weight_v" in name: _UpperCamelCase = '''weight_v''' elif "bias" in name: _UpperCamelCase = '''bias''' elif "weight" in name: _UpperCamelCase = '''weight''' else: _UpperCamelCase = None set_recursively(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) continue if not is_used: unused_weights.append(__snake_case ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = full_name.split('''conv_layers.''' )[-1] _UpperCamelCase = name.split('''.''' ) _UpperCamelCase = int(items[0] ) _UpperCamelCase = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__snake_case ) def _snake_case ( __snake_case ): _UpperCamelCase , _UpperCamelCase = emb.weight.shape _UpperCamelCase = nn.Linear(__snake_case , __snake_case , bias=__snake_case ) _UpperCamelCase = emb.weight.data return lin_layer def _snake_case ( __snake_case ): with open(__snake_case , '''r''' , encoding='''utf-8''' ) as f: _UpperCamelCase = f.readlines() _UpperCamelCase = [line.split(''' ''' )[0] for line in lines] _UpperCamelCase = len(__snake_case ) _UpperCamelCase = { '''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3, } vocab_dict.update(dict(zip(__snake_case , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ): _UpperCamelCase = WavaVecaConfig.from_pretrained(__snake_case ) _UpperCamelCase = SpeechaTextaConfig.from_pretrained( __snake_case , vocab_size=__snake_case , decoder_layers=__snake_case , do_stable_layer_norm=__snake_case ) _UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=__snake_case , return_attention_mask=__snake_case , ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) _UpperCamelCase = model[0].eval() # set weights for wav2vec2 encoder _UpperCamelCase = WavaVecaModel(__snake_case ) _UpperCamelCase = recursively_load_weights_wavaveca(model.encoder , __snake_case ) _UpperCamelCase = SpeechaTextaForCausalLM(__snake_case ) _UpperCamelCase , _UpperCamelCase = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__snake_case ) # set output linear layer unexpected_keys.remove('''embed_out''' ) _UpperCamelCase = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) _UpperCamelCase = SpeechEncoderDecoderModel(encoder=__snake_case , decoder=__snake_case ) _UpperCamelCase = False # add projection layer _UpperCamelCase = nn.Parameter(projection_layer.weight ) _UpperCamelCase = nn.Parameter(projection_layer.bias ) _UpperCamelCase = create_vocab_dict(__snake_case ) with open(os.path.join(__snake_case , '''vocab.json''' ) , '''w''' ) as fp: json.dump(__snake_case , __snake_case ) _UpperCamelCase = SpeechaTextaTokenizer(os.path.join(__snake_case , '''vocab.json''' ) ) tokenizer.save_pretrained(__snake_case ) _UpperCamelCase = hf_wavavec.config.to_dict() _UpperCamelCase = tokenizer.pad_token_id _UpperCamelCase = tokenizer.bos_token_id _UpperCamelCase = tokenizer.eos_token_id _UpperCamelCase = '''speech_to_text_2''' _UpperCamelCase = '''wav2vec2''' _UpperCamelCase = SpeechEncoderDecoderConfig.from_dict(__snake_case ) hf_wavavec.save_pretrained(__snake_case ) feature_extractor.save_pretrained(__snake_case ) if __name__ == "__main__": _lowerCAmelCase = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10_224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") _lowerCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
71
1
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = 42 @flax_register_to_config class lowerCAmelCase_ ( nn.Module, __lowercase, __lowercase ): UpperCAmelCase = 32 UpperCAmelCase = 4 UpperCAmelCase = 4 UpperCAmelCase = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) UpperCAmelCase = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") UpperCAmelCase = False UpperCAmelCase = (320, 640, 1280, 1280) UpperCAmelCase = 2 UpperCAmelCase = 8 UpperCAmelCase = None UpperCAmelCase = 1280 UpperCAmelCase = 0.0 UpperCAmelCase = False UpperCAmelCase = jnp.floataa UpperCAmelCase = True UpperCAmelCase = 0 UpperCAmelCase = False def UpperCamelCase_ ( self : Any , _A : jax.random.KeyArray ): # init input tensors _UpperCamelCase = (1, self.in_channels, self.sample_size, self.sample_size) _UpperCamelCase = jnp.zeros(_A , dtype=jnp.floataa ) _UpperCamelCase = jnp.ones((1,) , dtype=jnp.intaa ) _UpperCamelCase = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) _UpperCamelCase , _UpperCamelCase = jax.random.split(_A ) _UpperCamelCase = {'''params''': params_rng, '''dropout''': dropout_rng} return self.init(_A , _A , _A , _A )["params"] def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = self.block_out_channels _UpperCamelCase = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( '''At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.''' ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. _UpperCamelCase = self.num_attention_heads or self.attention_head_dim # input _UpperCamelCase = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time _UpperCamelCase = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) _UpperCamelCase = FlaxTimestepEmbedding(_A , dtype=self.dtype ) _UpperCamelCase = self.only_cross_attention if isinstance(_A , _A ): _UpperCamelCase = (only_cross_attention,) * len(self.down_block_types ) if isinstance(_A , _A ): _UpperCamelCase = (num_attention_heads,) * len(self.down_block_types ) # down _UpperCamelCase = [] _UpperCamelCase = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): _UpperCamelCase = output_channel _UpperCamelCase = block_out_channels[i] _UpperCamelCase = i == len(_A ) - 1 if down_block_type == "CrossAttnDownBlock2D": _UpperCamelCase = FlaxCrossAttnDownBlockaD( in_channels=_A , out_channels=_A , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: _UpperCamelCase = FlaxDownBlockaD( in_channels=_A , out_channels=_A , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(_A ) _UpperCamelCase = down_blocks # mid _UpperCamelCase = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up _UpperCamelCase = [] _UpperCamelCase = list(reversed(_A ) ) _UpperCamelCase = list(reversed(_A ) ) _UpperCamelCase = list(reversed(_A ) ) _UpperCamelCase = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): _UpperCamelCase = output_channel _UpperCamelCase = reversed_block_out_channels[i] _UpperCamelCase = reversed_block_out_channels[min(i + 1 , len(_A ) - 1 )] _UpperCamelCase = i == len(_A ) - 1 if up_block_type == "CrossAttnUpBlock2D": _UpperCamelCase = FlaxCrossAttnUpBlockaD( in_channels=_A , out_channels=_A , prev_output_channel=_A , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: _UpperCamelCase = FlaxUpBlockaD( in_channels=_A , out_channels=_A , prev_output_channel=_A , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(_A ) _UpperCamelCase = output_channel _UpperCamelCase = up_blocks # out _UpperCamelCase = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) _UpperCamelCase = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : List[Any] , _A : Dict , _A : Optional[int] , _A : List[str] , _A : str=None , _A : List[str]=None , _A : bool = True , _A : bool = False , ): # 1. time if not isinstance(_A , jnp.ndarray ): _UpperCamelCase = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(_A , jnp.ndarray ) and len(timesteps.shape ) == 0: _UpperCamelCase = timesteps.astype(dtype=jnp.floataa ) _UpperCamelCase = jnp.expand_dims(_A , 0 ) _UpperCamelCase = self.time_proj(_A ) _UpperCamelCase = self.time_embedding(_A ) # 2. pre-process _UpperCamelCase = jnp.transpose(_A , (0, 2, 3, 1) ) _UpperCamelCase = self.conv_in(_A ) # 3. down _UpperCamelCase = (sample,) for down_block in self.down_blocks: if isinstance(_A , _A ): _UpperCamelCase , _UpperCamelCase = down_block(_A , _A , _A , deterministic=not train ) else: _UpperCamelCase , _UpperCamelCase = down_block(_A , _A , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: _UpperCamelCase = () for down_block_res_sample, down_block_additional_residual in zip( _A , _A ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) _UpperCamelCase = new_down_block_res_samples # 4. mid _UpperCamelCase = self.mid_block(_A , _A , _A , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: _UpperCamelCase = down_block_res_samples[-(self.layers_per_block + 1) :] _UpperCamelCase = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(_A , _A ): _UpperCamelCase = up_block( _A , temb=_A , encoder_hidden_states=_A , res_hidden_states_tuple=_A , deterministic=not train , ) else: _UpperCamelCase = up_block(_A , temb=_A , res_hidden_states_tuple=_A , deterministic=not train ) # 6. post-process _UpperCamelCase = self.conv_norm_out(_A ) _UpperCamelCase = nn.silu(_A ) _UpperCamelCase = self.conv_out(_A ) _UpperCamelCase = jnp.transpose(_A , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=_A )
71
from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class lowerCAmelCase_ : def __init__( self : Optional[Any] , _A : Optional[Any] , _A : List[str]=13 , _A : Union[str, Any]=7 , _A : int=True , _A : Optional[int]=True , _A : Optional[int]=True , _A : Union[str, Any]=True , _A : Optional[int]=99 , _A : Union[str, Any]=32 , _A : Dict=2 , _A : List[Any]=4 , _A : Optional[Any]=37 , _A : int="gelu" , _A : Optional[int]=0.1 , _A : str=0.1 , _A : List[str]=512 , _A : Optional[Any]=16 , _A : Optional[Any]=2 , _A : Optional[int]=0.02 , _A : str=False , _A : int=True , _A : Any="None" , _A : Dict=3 , _A : List[Any]=4 , _A : Optional[Any]=None , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_mask _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_labels _UpperCamelCase = num_choices _UpperCamelCase = relative_attention _UpperCamelCase = position_biased_input _UpperCamelCase = pos_att_type _UpperCamelCase = scope def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = None if self.use_input_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None if self.use_labels: _UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCamelCase = DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=_A , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self : Dict , _A : Tuple , _A : Tuple , _A : Union[str, Any] , _A : List[str] , _A : Optional[int] , _A : int , _A : Optional[Any] ): _UpperCamelCase = TFDebertaVaModel(config=_A ) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = [input_ids, input_mask] _UpperCamelCase = model(_A ) _UpperCamelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Dict , _A : Optional[int] , _A : Any , _A : Dict , _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any] , _A : List[str] ): _UpperCamelCase = TFDebertaVaForMaskedLM(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self : Dict , _A : Dict , _A : List[str] , _A : List[Any] , _A : List[Any] , _A : Optional[Any] , _A : Tuple , _A : int ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForSequenceClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple , _A : Dict , _A : Optional[int] , _A : Any , _A : List[Any] , _A : Dict , _A : Union[str, Any] , _A : List[str] ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForTokenClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Dict , _A : Optional[Any] , _A : Optional[int] , _A : Any , _A : List[str] , _A : str , _A : Optional[int] , _A : str ): _UpperCamelCase = TFDebertaVaForQuestionAnswering(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_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 UpperCamelCase_ ( self : Any ): _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( __lowercase, __lowercase, unittest.TestCase ): UpperCAmelCase = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) UpperCAmelCase = ( { "feature-extraction": TFDebertaVaModel, "fill-mask": TFDebertaVaForMaskedLM, "question-answering": TFDebertaVaForQuestionAnswering, "text-classification": TFDebertaVaForSequenceClassification, "token-classification": TFDebertaVaForTokenClassification, "zero-shot": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase = False UpperCAmelCase = False def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = TFDebertaVaModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_A ) @slow def UpperCamelCase_ ( self : Any ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) self.assertIsNotNone(_A ) @require_tf class lowerCAmelCase_ ( unittest.TestCase ): @unittest.skip(reason='''Model not available yet''' ) def UpperCamelCase_ ( self : List[Any] ): pass @slow def UpperCamelCase_ ( self : int ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) _UpperCamelCase = tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) _UpperCamelCase = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) _UpperCamelCase = model(_A , attention_mask=_A )[0] _UpperCamelCase = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , _A , atol=1e-4 )
71
1
def _snake_case ( __snake_case , __snake_case ): return price * (1 + tax_rate) if __name__ == "__main__": print(f'{price_plus_tax(100, 0.25) = }') print(f'{price_plus_tax(125.50, 0.05) = }')
71
def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case ): # Return True if there is node that has not iterated. _UpperCamelCase = [False] * len(__snake_case ) _UpperCamelCase = [] queue.append(__snake_case ) _UpperCamelCase = True while queue: _UpperCamelCase = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(__snake_case ) _UpperCamelCase = True _UpperCamelCase = u return visited[t] def _snake_case ( __snake_case , __snake_case , __snake_case ): # This array is filled by BFS and to store path _UpperCamelCase = [-1] * (len(__snake_case )) _UpperCamelCase = 0 while bfs(__snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = float('''Inf''' ) _UpperCamelCase = sink while s != source: # Find the minimum value in select path _UpperCamelCase = min(__snake_case , graph[parent[s]][s] ) _UpperCamelCase = parent[s] max_flow += path_flow _UpperCamelCase = sink while v != source: _UpperCamelCase = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow _UpperCamelCase = parent[v] return max_flow _lowerCAmelCase = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] _lowerCAmelCase, _lowerCAmelCase = 0, 5 print(ford_fulkerson(graph, source, sink))
71
1
from typing import TYPE_CHECKING from ...utils import _LazyModule _lowerCAmelCase = {"tokenization_byt5": ["ByT5Tokenizer"]} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _lowerCAmelCase = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
1
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _snake_case ( __snake_case , __snake_case ): assert isinstance(__snake_case , __snake_case ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def _snake_case ( __snake_case , __snake_case , __snake_case ): _UpperCamelCase = tmp_path / '''cache''' _UpperCamelCase = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _UpperCamelCase = ParquetDatasetReader(__snake_case , cache_dir=__snake_case , keep_in_memory=__snake_case ).read() _check_parquet_dataset(__snake_case , __snake_case ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def _snake_case ( __snake_case , __snake_case , __snake_case ): _UpperCamelCase = tmp_path / '''cache''' _UpperCamelCase = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} _UpperCamelCase = features.copy() if features else default_expected_features _UpperCamelCase = ( Features({feature: Value(__snake_case ) for feature, dtype in features.items()} ) if features is not None else None ) _UpperCamelCase = ParquetDatasetReader(__snake_case , features=__snake_case , cache_dir=__snake_case ).read() _check_parquet_dataset(__snake_case , __snake_case ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def _snake_case ( __snake_case , __snake_case , __snake_case ): _UpperCamelCase = tmp_path / '''cache''' _UpperCamelCase = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} _UpperCamelCase = ParquetDatasetReader(__snake_case , cache_dir=__snake_case , split=__snake_case ).read() _check_parquet_dataset(__snake_case , __snake_case ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def _snake_case ( __snake_case , __snake_case , __snake_case ): if issubclass(__snake_case , __snake_case ): _UpperCamelCase = parquet_path elif issubclass(__snake_case , __snake_case ): _UpperCamelCase = [parquet_path] _UpperCamelCase = tmp_path / '''cache''' _UpperCamelCase = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} _UpperCamelCase = ParquetDatasetReader(__snake_case , cache_dir=__snake_case ).read() _check_parquet_dataset(__snake_case , __snake_case ) def _snake_case ( __snake_case , __snake_case , __snake_case=("train",) ): assert isinstance(__snake_case , __snake_case ) for split in splits: _UpperCamelCase = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def _snake_case ( __snake_case , __snake_case , __snake_case ): _UpperCamelCase = tmp_path / '''cache''' _UpperCamelCase = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _UpperCamelCase = ParquetDatasetReader( {'''train''': parquet_path} , cache_dir=__snake_case , keep_in_memory=__snake_case ).read() _check_parquet_datasetdict(__snake_case , __snake_case ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def _snake_case ( __snake_case , __snake_case , __snake_case ): _UpperCamelCase = tmp_path / '''cache''' _UpperCamelCase = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} _UpperCamelCase = features.copy() if features else default_expected_features _UpperCamelCase = ( Features({feature: Value(__snake_case ) for feature, dtype in features.items()} ) if features is not None else None ) _UpperCamelCase = ParquetDatasetReader({'''train''': parquet_path} , features=__snake_case , cache_dir=__snake_case ).read() _check_parquet_datasetdict(__snake_case , __snake_case ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def _snake_case ( __snake_case , __snake_case , __snake_case ): if split: _UpperCamelCase = {split: parquet_path} else: _UpperCamelCase = '''train''' _UpperCamelCase = {'''train''': parquet_path, '''test''': parquet_path} _UpperCamelCase = tmp_path / '''cache''' _UpperCamelCase = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} _UpperCamelCase = ParquetDatasetReader(__snake_case , cache_dir=__snake_case ).read() _check_parquet_datasetdict(__snake_case , __snake_case , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = ParquetDatasetWriter(__snake_case , tmp_path / '''foo.parquet''' ) assert writer.write() > 0 _UpperCamelCase = pq.ParquetFile(tmp_path / '''foo.parquet''' ) _UpperCamelCase = pf.read() assert dataset.data.table == output_table def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = str(shared_datadir / '''test_image_rgb.jpg''' ) _UpperCamelCase = {'''image''': [image_path]} _UpperCamelCase = Features({'''image''': Image()} ) _UpperCamelCase = Dataset.from_dict(__snake_case , features=__snake_case ) _UpperCamelCase = ParquetDatasetWriter(__snake_case , tmp_path / '''foo.parquet''' ) assert writer.write() > 0 _UpperCamelCase = Dataset.from_parquet(str(tmp_path / '''foo.parquet''' ) ) assert dataset.features == reloaded_dataset.features _UpperCamelCase = ParquetDatasetReader(str(tmp_path / '''foo.parquet''' ) , streaming=__snake_case ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( '''feature, expected''' , [ (Features({'''foo''': Value('''int32''' )} ), None), (Features({'''image''': Image(), '''foo''': Value('''int32''' )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({'''nested''': Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def _snake_case ( __snake_case , __snake_case ): assert get_writer_batch_size(__snake_case ) == expected
71
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Any ): _UpperCamelCase = tempfile.mkdtemp() # fmt: off _UpperCamelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on _UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) _UpperCamelCase = { '''do_resize''': True, '''size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } _UpperCamelCase = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_A , _A ) def UpperCamelCase_ ( self : Tuple , **_A : Optional[Any] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : List[Any] , **_A : Union[str, Any] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : int ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _UpperCamelCase = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = self.get_image_processor() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _UpperCamelCase = self.get_image_processor(do_normalize=_A , padding_value=1.0 ) _UpperCamelCase = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = image_processor(_A , return_tensors='''np''' ) _UpperCamelCase = processor(images=_A , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = processor(text=_A ) _UpperCamelCase = tokenizer(_A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_A ): processor() def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _UpperCamelCase = processor.batch_decode(_A ) _UpperCamelCase = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A ) def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
71
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = tempfile.mkdtemp() # fmt: off _UpperCamelCase = ['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on _UpperCamelCase = dict(zip(_A , range(len(_A ) ) ) ) _UpperCamelCase = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] _UpperCamelCase = {'''unk_token''': '''<unk>'''} _UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(_A ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(_A ) ) _UpperCamelCase = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.4814_5466, 0.457_8275, 0.4082_1073], '''image_std''': [0.2686_2954, 0.2613_0258, 0.2757_7711], } _UpperCamelCase = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_A , _A ) def UpperCamelCase_ ( self : str , **_A : Union[str, Any] ): return CLIPTokenizer.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : Union[str, Any] , **_A : int ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : Optional[Any] , **_A : int ): return CLIPImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : int ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _UpperCamelCase = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = self.get_rust_tokenizer() _UpperCamelCase = self.get_image_processor() _UpperCamelCase = CLIPProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) _UpperCamelCase = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) _UpperCamelCase = CLIPProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) _UpperCamelCase = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _UpperCamelCase = self.get_image_processor(do_normalize=_A , padding_value=1.0 ) _UpperCamelCase = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = CLIPProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = image_processor(_A , return_tensors='''np''' ) _UpperCamelCase = processor(images=_A , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = CLIPProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = processor(text=_A ) _UpperCamelCase = tokenizer(_A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase_ ( self : str ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = CLIPProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCamelCase_ ( self : str ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = CLIPProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _UpperCamelCase = processor.batch_decode(_A ) _UpperCamelCase = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = CLIPProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
71
def _snake_case ( __snake_case , __snake_case , __snake_case ): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__snake_case , n - 1 , __snake_case ) * a) % mod else: _UpperCamelCase = binary_exponentiation(__snake_case , n / 2 , __snake_case ) return (b * b) % mod # a prime number _lowerCAmelCase = 701 _lowerCAmelCase = 1_000_000_000 _lowerCAmelCase = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
71
1
_lowerCAmelCase = [ "DownloadConfig", "DownloadManager", "DownloadMode", "StreamingDownloadManager", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
71
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = (1 - _cos) / 2 _UpperCamelCase = 1 - _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = (1 + _cos) / 2 _UpperCamelCase = -1 - _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = _sin / 2 _UpperCamelCase = 0 _UpperCamelCase = -ba _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 1 - alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = 1 + alpha * big_a _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha * big_a _UpperCamelCase = 1 + alpha / big_a _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha / big_a _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = (big_a + 1) - (big_a - 1) * _cos _UpperCamelCase = (big_a + 1) + (big_a - 1) * _cos _UpperCamelCase = (big_a - 1) - (big_a + 1) * _cos _UpperCamelCase = (big_a - 1) + (big_a + 1) * _cos _UpperCamelCase = 2 * sqrt(__snake_case ) * alpha _UpperCamelCase = big_a * (pmc + aaa) _UpperCamelCase = 2 * big_a * mpc _UpperCamelCase = big_a * (pmc - aaa) _UpperCamelCase = ppmc + aaa _UpperCamelCase = -2 * pmpc _UpperCamelCase = ppmc - aaa _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = (big_a + 1) - (big_a - 1) * _cos _UpperCamelCase = (big_a + 1) + (big_a - 1) * _cos _UpperCamelCase = (big_a - 1) - (big_a + 1) * _cos _UpperCamelCase = (big_a - 1) + (big_a + 1) * _cos _UpperCamelCase = 2 * sqrt(__snake_case ) * alpha _UpperCamelCase = big_a * (ppmc + aaa) _UpperCamelCase = -2 * big_a * pmpc _UpperCamelCase = big_a * (ppmc - aaa) _UpperCamelCase = pmc + aaa _UpperCamelCase = 2 * mpc _UpperCamelCase = pmc - aaa _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
71
1
class lowerCAmelCase_ : def __init__( self : Tuple , _A : str = "" , _A : bool = False ): # Mapping from the first character of the prefix of the node _UpperCamelCase = {} # A node will be a leaf if the tree contains its word _UpperCamelCase = is_leaf _UpperCamelCase = prefix def UpperCamelCase_ ( self : Union[str, Any] , _A : str ): _UpperCamelCase = 0 for q, w in zip(self.prefix , _A ): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def UpperCamelCase_ ( self : int , _A : list[str] ): for word in words: self.insert(_A ) def UpperCamelCase_ ( self : List[Any] , _A : str ): # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word: _UpperCamelCase = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: _UpperCamelCase = RadixNode(prefix=_A , is_leaf=_A ) else: _UpperCamelCase = self.nodes[word[0]] _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = incoming_node.match( _A ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(_A ) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: _UpperCamelCase = remaining_prefix _UpperCamelCase = self.nodes[matching_string[0]] _UpperCamelCase = RadixNode(_A , _A ) _UpperCamelCase = aux_node if remaining_word == "": _UpperCamelCase = True else: self.nodes[matching_string[0]].insert(_A ) def UpperCamelCase_ ( self : Optional[int] , _A : str ): _UpperCamelCase = self.nodes.get(word[0] , _A ) if not incoming_node: return False else: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = incoming_node.match( _A ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(_A ) def UpperCamelCase_ ( self : Tuple , _A : str ): _UpperCamelCase = self.nodes.get(word[0] , _A ) if not incoming_node: return False else: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = incoming_node.match( _A ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(_A ) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes ) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes ) == 1 and not self.is_leaf: _UpperCamelCase = list(self.nodes.values() )[0] _UpperCamelCase = merging_node.is_leaf self.prefix += merging_node.prefix _UpperCamelCase = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes ) > 1: _UpperCamelCase = False # If there is 1 edge, we merge it with its child else: _UpperCamelCase = list(incoming_node.nodes.values() )[0] _UpperCamelCase = merging_node.is_leaf incoming_node.prefix += merging_node.prefix _UpperCamelCase = merging_node.nodes return True def UpperCamelCase_ ( self : str , _A : int = 0 ): if self.prefix != "": print('''-''' * height , self.prefix , ''' (leaf)''' if self.is_leaf else '''''' ) for value in self.nodes.values(): value.print_tree(height + 1 ) def _snake_case ( ): _UpperCamelCase = '''banana bananas bandana band apple all beast'''.split() _UpperCamelCase = RadixNode() root.insert_many(__snake_case ) assert all(root.find(__snake_case ) for word in words ) assert not root.find('''bandanas''' ) assert not root.find('''apps''' ) root.delete('''all''' ) assert not root.find('''all''' ) root.delete('''banana''' ) assert not root.find('''banana''' ) assert root.find('''bananas''' ) return True def _snake_case ( ): assert test_trie() def _snake_case ( ): _UpperCamelCase = RadixNode() _UpperCamelCase = '''banana bananas bandanas bandana band apple all beast'''.split() root.insert_many(__snake_case ) print('''Words:''' , __snake_case ) print('''Tree:''' ) root.print_tree() if __name__ == "__main__": main()
71
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json", # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "gpt_neox" def __init__( self : Union[str, Any] , _A : Union[str, Any]=5_0432 , _A : List[Any]=6144 , _A : int=44 , _A : int=64 , _A : Optional[Any]=2_4576 , _A : Any="gelu" , _A : Tuple=0.25 , _A : Union[str, Any]=1_0000 , _A : Tuple=0.0 , _A : Any=0.0 , _A : int=0.1 , _A : List[str]=2048 , _A : Dict=0.02 , _A : Optional[Any]=1e-5 , _A : Tuple=True , _A : List[Any]=0 , _A : Optional[int]=2 , _A : Optional[int]=False , _A : List[Any]=True , _A : Any=None , **_A : Any , ): super().__init__(bos_token_id=_A , eos_token_id=_A , **_A ) _UpperCamelCase = vocab_size _UpperCamelCase = max_position_embeddings _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = rotary_pct _UpperCamelCase = rotary_emb_base _UpperCamelCase = attention_dropout _UpperCamelCase = hidden_dropout _UpperCamelCase = classifier_dropout _UpperCamelCase = initializer_range _UpperCamelCase = layer_norm_eps _UpperCamelCase = use_cache _UpperCamelCase = tie_word_embeddings _UpperCamelCase = use_parallel_residual _UpperCamelCase = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( '''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' ) def UpperCamelCase_ ( self : str ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _A ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F"""got {self.rope_scaling}""" ) _UpperCamelCase = self.rope_scaling.get('''type''' , _A ) _UpperCamelCase = self.rope_scaling.get('''factor''' , _A ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}""" ) if rope_scaling_factor is None or not isinstance(_A , _A ) or rope_scaling_factor <= 1.0: raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
71
1
def _snake_case ( __snake_case ): if len(__snake_case ) <= 1: return [tuple(__snake_case )] _UpperCamelCase = [] def generate(__snake_case , __snake_case ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , __snake_case ) for i in range(k - 1 ): if k % 2 == 0: # k is even _UpperCamelCase , _UpperCamelCase = arr[k - 1], arr[i] else: # k is odd _UpperCamelCase , _UpperCamelCase = arr[k - 1], arr[0] generate(k - 1 , __snake_case ) generate(len(__snake_case ) , __snake_case ) return res if __name__ == "__main__": _lowerCAmelCase = input("Enter numbers separated by a comma:\n").strip() _lowerCAmelCase = [int(item) for item in user_input.split(",")] print(heaps(arr))
71
from ..utils import DummyObject, requires_backends class lowerCAmelCase_ ( metaclass=__lowercase ): UpperCAmelCase = ["keras_nlp"] def __init__( self : Any , *_A : Dict , **_A : List[str] ): requires_backends(self , ['''keras_nlp'''] )
71
1
from statistics import mean, stdev def _snake_case ( __snake_case , __snake_case = 3 ): _UpperCamelCase = min(__snake_case ) _UpperCamelCase = max(__snake_case ) # normalize data return [round((x - x_min) / (x_max - x_min) , __snake_case ) for x in data] def _snake_case ( __snake_case , __snake_case = 3 ): _UpperCamelCase = mean(__snake_case ) _UpperCamelCase = stdev(__snake_case ) # standardize data return [round((x - mu) / (sigma) , __snake_case ) for x in data]
71
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig _lowerCAmelCase = logging.get_logger(__name__) # General docstring _lowerCAmelCase = "RegNetConfig" # Base docstring _lowerCAmelCase = "facebook/regnet-y-040" _lowerCAmelCase = [1, 1_088, 7, 7] # Image classification docstring _lowerCAmelCase = "facebook/regnet-y-040" _lowerCAmelCase = "tabby, tabby cat" _lowerCAmelCase = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : str , _A : int , _A : int = 3 , _A : int = 1 , _A : int = 1 , _A : Optional[str] = "relu" , **_A : Any , ): super().__init__(**_A ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb _UpperCamelCase = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) _UpperCamelCase = tf.keras.layers.ConvaD( filters=_A , kernel_size=_A , strides=_A , padding='''VALID''' , groups=_A , use_bias=_A , name='''convolution''' , ) _UpperCamelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) _UpperCamelCase = ACTaFN[activation] if activation is not None else tf.identity def UpperCamelCase_ ( self : Any , _A : Any ): _UpperCamelCase = self.convolution(self.padding(_A ) ) _UpperCamelCase = self.normalization(_A ) _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] , _A : RegNetConfig , **_A : Any ): super().__init__(**_A ) _UpperCamelCase = config.num_channels _UpperCamelCase = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='''embedder''' , ) def UpperCamelCase_ ( self : List[str] , _A : Optional[int] ): _UpperCamelCase = shape_list(_A )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) _UpperCamelCase = tf.transpose(_A , perm=(0, 2, 3, 1) ) _UpperCamelCase = self.embedder(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : str , _A : int , _A : int = 2 , **_A : Optional[Any] ): super().__init__(**_A ) _UpperCamelCase = tf.keras.layers.ConvaD( filters=_A , kernel_size=1 , strides=_A , use_bias=_A , name='''convolution''' ) _UpperCamelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) def UpperCamelCase_ ( self : str , _A : tf.Tensor , _A : bool = False ): return self.normalization(self.convolution(_A ) , training=_A ) class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Dict , _A : int , _A : int , **_A : Dict ): super().__init__(**_A ) _UpperCamelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_A , name='''pooler''' ) _UpperCamelCase = [ tf.keras.layers.ConvaD(filters=_A , kernel_size=1 , activation='''relu''' , name='''attention.0''' ), tf.keras.layers.ConvaD(filters=_A , kernel_size=1 , activation='''sigmoid''' , name='''attention.2''' ), ] def UpperCamelCase_ ( self : List[str] , _A : List[Any] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] _UpperCamelCase = self.pooler(_A ) for layer_module in self.attention: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = hidden_state * pooled return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , _A : int , _A : int , _A : int = 1 , **_A : str ): super().__init__(**_A ) _UpperCamelCase = in_channels != out_channels or stride != 1 _UpperCamelCase = max(1 , out_channels // config.groups_width ) _UpperCamelCase = ( TFRegNetShortCut(_A , stride=_A , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. _UpperCamelCase = [ TFRegNetConvLayer(_A , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( _A , stride=_A , groups=_A , activation=config.hidden_act , name='''layer.1''' ), TFRegNetConvLayer(_A , kernel_size=1 , activation=_A , name='''layer.2''' ), ] _UpperCamelCase = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Dict , _A : Tuple ): _UpperCamelCase = hidden_state for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = self.shortcut(_A ) hidden_state += residual _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , _A : int , _A : int , _A : int = 1 , **_A : int ): super().__init__(**_A ) _UpperCamelCase = in_channels != out_channels or stride != 1 _UpperCamelCase = max(1 , out_channels // config.groups_width ) _UpperCamelCase = ( TFRegNetShortCut(_A , stride=_A , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) _UpperCamelCase = [ TFRegNetConvLayer(_A , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( _A , stride=_A , groups=_A , activation=config.hidden_act , name='''layer.1''' ), TFRegNetSELayer(_A , reduced_channels=int(round(in_channels / 4 ) ) , name='''layer.2''' ), TFRegNetConvLayer(_A , kernel_size=1 , activation=_A , name='''layer.3''' ), ] _UpperCamelCase = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Tuple , _A : List[Any] ): _UpperCamelCase = hidden_state for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = self.shortcut(_A ) hidden_state += residual _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Tuple , _A : RegNetConfig , _A : int , _A : int , _A : int = 2 , _A : int = 2 , **_A : Union[str, Any] ): super().__init__(**_A ) _UpperCamelCase = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer _UpperCamelCase = [ # downsampling is done in the first layer with stride of 2 layer(_A , _A , _A , stride=_A , name='''layers.0''' ), *[layer(_A , _A , _A , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCamelCase_ ( self : Union[str, Any] , _A : Optional[int] ): for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , **_A : List[str] ): super().__init__(**_A ) _UpperCamelCase = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( _A , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='''stages.0''' , ) ) _UpperCamelCase = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(_A , config.depths[1:] ) ): self.stages.append(TFRegNetStage(_A , _A , _A , depth=_A , name=F"""stages.{i+1}""" ) ) def UpperCamelCase_ ( self : Optional[int] , _A : tf.Tensor , _A : bool = False , _A : bool = True ): _UpperCamelCase = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _UpperCamelCase = hidden_states + (hidden_state,) _UpperCamelCase = stage_module(_A ) if output_hidden_states: _UpperCamelCase = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=_A , hidden_states=_A ) @keras_serializable class lowerCAmelCase_ ( tf.keras.layers.Layer ): UpperCAmelCase = RegNetConfig def __init__( self : int , _A : Tuple , **_A : int ): super().__init__(**_A ) _UpperCamelCase = config _UpperCamelCase = TFRegNetEmbeddings(_A , name='''embedder''' ) _UpperCamelCase = TFRegNetEncoder(_A , name='''encoder''' ) _UpperCamelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_A , name='''pooler''' ) @unpack_inputs def UpperCamelCase_ ( self : Optional[int] , _A : tf.Tensor , _A : Optional[bool] = None , _A : Optional[bool] = None , _A : bool = False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.embedder(_A , training=_A ) _UpperCamelCase = self.encoder( _A , output_hidden_states=_A , return_dict=_A , training=_A ) _UpperCamelCase = encoder_outputs[0] _UpperCamelCase = self.pooler(_A ) # Change to NCHW output format have uniformity in the modules _UpperCamelCase = tf.transpose(_A , perm=(0, 3, 1, 2) ) _UpperCamelCase = tf.transpose(_A , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: _UpperCamelCase = tuple([tf.transpose(_A , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_A , pooler_output=_A , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = RegNetConfig UpperCAmelCase = "regnet" UpperCAmelCase = "pixel_values" @property def UpperCamelCase_ ( self : Tuple ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} _lowerCAmelCase = r"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n" _lowerCAmelCase = r"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top.", __lowercase, ) class lowerCAmelCase_ ( __lowercase ): def __init__( self : List[Any] , _A : RegNetConfig , *_A : Optional[int] , **_A : Tuple ): super().__init__(_A , *_A , **_A ) _UpperCamelCase = TFRegNetMainLayer(_A , name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(_A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_A , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCamelCase_ ( self : Any , _A : tf.Tensor , _A : Optional[bool] = None , _A : Optional[bool] = None , _A : Optional[int]=False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.regnet( pixel_values=_A , output_hidden_states=_A , return_dict=_A , training=_A , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ", __lowercase, ) class lowerCAmelCase_ ( __lowercase, __lowercase ): def __init__( self : List[Any] , _A : RegNetConfig , *_A : Any , **_A : int ): super().__init__(_A , *_A , **_A ) _UpperCamelCase = config.num_labels _UpperCamelCase = TFRegNetMainLayer(_A , name='''regnet''' ) # classification head _UpperCamelCase = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(_A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCamelCase_ ( self : str , _A : tf.Tensor = None , _A : tf.Tensor = None , _A : bool = None , _A : bool = None , _A : Any=False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.regnet( _A , output_hidden_states=_A , return_dict=_A , training=_A ) _UpperCamelCase = outputs.pooler_output if return_dict else outputs[1] _UpperCamelCase = self.classifier[0](_A ) _UpperCamelCase = self.classifier[1](_A ) _UpperCamelCase = None if labels is None else self.hf_compute_loss(labels=_A , logits=_A ) if not return_dict: _UpperCamelCase = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=_A , logits=_A , hidden_states=outputs.hidden_states )
71
1
from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : def __init__( self : Union[str, Any] , _A : Union[str, Any] , _A : Dict=12 , _A : Optional[int]=7 , _A : List[Any]=True , _A : int=True , _A : str=True , _A : Optional[int]=99 , _A : str=32 , _A : Tuple=32 , _A : List[str]=2 , _A : int=4 , _A : List[Any]=37 , _A : List[Any]=0.1 , _A : Optional[Any]=0.1 , _A : Union[str, Any]=512 , _A : Optional[Any]=0.02 , _A : Any=0 , _A : Dict=None , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_mask _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = projection_dim _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = dropout _UpperCamelCase = attention_dropout _UpperCamelCase = max_position_embeddings _UpperCamelCase = initializer_range _UpperCamelCase = scope _UpperCamelCase = bos_token_id def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = None if self.use_input_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: _UpperCamelCase = input_mask.numpy() _UpperCamelCase , _UpperCamelCase = input_mask.shape _UpperCamelCase = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_A ): _UpperCamelCase = 1 _UpperCamelCase = 0 _UpperCamelCase = self.get_config() return config, input_ids, tf.convert_to_tensor(_A ) def UpperCamelCase_ ( self : int ): return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def UpperCamelCase_ ( self : List[str] , _A : Optional[int] , _A : str , _A : List[str] ): _UpperCamelCase = TFBlipTextModel(config=_A ) _UpperCamelCase = model(_A , attention_mask=_A , training=_A ) _UpperCamelCase = model(_A , training=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.prepare_config_and_inputs() _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( __lowercase, unittest.TestCase ): UpperCAmelCase = (TFBlipTextModel,) if is_tf_available() else () UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = False def UpperCamelCase_ ( self : str ): _UpperCamelCase = BlipTextModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCamelCase_ ( self : List[str] ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : str ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCamelCase_ ( self : int ): pass def UpperCamelCase_ ( self : int ): pass @unittest.skip(reason='''Blip does not use inputs_embeds''' ) def UpperCamelCase_ ( self : int ): pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def UpperCamelCase_ ( self : List[str] ): pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def UpperCamelCase_ ( self : Any ): pass @slow def UpperCamelCase_ ( self : Tuple ): for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase = TFBlipTextModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def UpperCamelCase_ ( self : Dict , _A : Dict=True ): super().test_pt_tf_model_equivalence(allow_missing_keys=_A )
71
from sklearn.metrics import mean_squared_error import datasets _lowerCAmelCase = "\\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" _lowerCAmelCase = "\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n" _lowerCAmelCase = "\nArgs:\n predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n sample_weight: array-like of shape (n_samples,), default=None\n Sample weights.\n multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"\n Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n \"raw_values\" : Returns a full set of errors in case of multioutput input.\n\n \"uniform_average\" : Errors of all outputs are averaged with uniform weight.\n\n squared : bool, default=True\n If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n mse : mean squared error.\nExamples:\n\n >>> mse_metric = datasets.load_metric(\"mse\")\n >>> predictions = [2.5, 0.0, 2, 8]\n >>> references = [3, -0.5, 2, 7]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'mse': 0.375}\n >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n >>> print(rmse_result)\n {'mse': 0.6123724356957945}\n\n If you're using multi-dimensional lists, then set the config as follows :\n\n >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")\n >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n >>> references = [[0, 2], [-1, 2], [8, -5]]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'mse': 0.7083333333333334}\n >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {'mse': array([0.41666667, 1. ])}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): def UpperCamelCase_ ( self : Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html''' ] , ) def UpperCamelCase_ ( self : Dict ): if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value('''float''' ) ), "references": datasets.Sequence(datasets.Value('''float''' ) ), } else: return { "predictions": datasets.Value('''float''' ), "references": datasets.Value('''float''' ), } def UpperCamelCase_ ( self : Any , _A : List[Any] , _A : List[str] , _A : Dict=None , _A : List[str]="uniform_average" , _A : int=True ): _UpperCamelCase = mean_squared_error( _A , _A , sample_weight=_A , multioutput=_A , squared=_A ) return {"mse": mse}
71
1
import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html _lowerCAmelCase = "platform" import jax import jax.numpy as jnp from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, shift_tokens_right, ) def _snake_case ( __snake_case , __snake_case , __snake_case=None , __snake_case=None , __snake_case=None , __snake_case=None , __snake_case=None , __snake_case=None , ): if attention_mask is None: _UpperCamelCase = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: _UpperCamelCase = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: _UpperCamelCase = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _UpperCamelCase = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _UpperCamelCase = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class lowerCAmelCase_ : def __init__( self : Optional[int] , _A : Dict , _A : int=13 , _A : Any=7 , _A : Optional[Any]=True , _A : Dict=False , _A : Optional[Any]=99 , _A : Any=16 , _A : List[Any]=2 , _A : int=4 , _A : Tuple=4 , _A : int="gelu" , _A : int=0.1 , _A : Optional[int]=0.1 , _A : List[Any]=32 , _A : List[str]=2 , _A : List[str]=1 , _A : Union[str, Any]=0 , _A : Any=0.02 , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _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 = eos_token_id _UpperCamelCase = pad_token_id _UpperCamelCase = bos_token_id _UpperCamelCase = initializer_range def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) _UpperCamelCase = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) _UpperCamelCase = shift_tokens_right(_A , 1 , 2 ) _UpperCamelCase = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=_A , ) _UpperCamelCase = prepare_blenderbot_inputs_dict(_A , _A , _A ) return config, inputs_dict def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase , _UpperCamelCase = self.prepare_config_and_inputs() return config, inputs_dict def UpperCamelCase_ ( self : int , _A : Optional[Any] , _A : str , _A : Tuple ): _UpperCamelCase = 20 _UpperCamelCase = model_class_name(_A ) _UpperCamelCase = model.encode(inputs_dict['''input_ids'''] ) _UpperCamelCase , _UpperCamelCase = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) _UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , _A , _A ) _UpperCamelCase = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) _UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , _A , decoder_attention_mask=_A , past_key_values=_A , decoder_position_ids=_A , ) _UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) _UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , _A , decoder_attention_mask=_A , past_key_values=outputs_cache.past_key_values , decoder_position_ids=_A , ) _UpperCamelCase = model.decode(_A , _A ) _UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"""Max diff is {diff}""" ) def UpperCamelCase_ ( self : int , _A : List[str] , _A : Optional[int] , _A : Optional[Any] ): _UpperCamelCase = 20 _UpperCamelCase = model_class_name(_A ) _UpperCamelCase = model.encode(inputs_dict['''input_ids'''] ) _UpperCamelCase , _UpperCamelCase = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) _UpperCamelCase = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) _UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , _A , _A ) _UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , _A , decoder_attention_mask=_A , past_key_values=_A , decoder_position_ids=_A , ) _UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) _UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , _A , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=_A , decoder_position_ids=_A , ) _UpperCamelCase = model.decode(_A , _A , decoder_attention_mask=_A ) _UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"""Max diff is {diff}""" ) @require_flax class lowerCAmelCase_ ( unittest.TestCase ): UpperCAmelCase = 99 def UpperCamelCase_ ( self : int ): _UpperCamelCase = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) _UpperCamelCase = input_ids.shape[0] _UpperCamelCase = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = self._get_config_and_data() _UpperCamelCase = FlaxBlenderbotSmallForConditionalGeneration(_A ) _UpperCamelCase = lm_model(input_ids=_A ) _UpperCamelCase = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , _A ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) _UpperCamelCase = FlaxBlenderbotSmallForConditionalGeneration(_A ) _UpperCamelCase = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) _UpperCamelCase = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) _UpperCamelCase = lm_model(input_ids=_A , decoder_input_ids=_A ) _UpperCamelCase = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , _A ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) _UpperCamelCase = shift_tokens_right(_A , 1 , 2 ) _UpperCamelCase = np.equal(_A , 1 ).astype(np.floataa ).sum() _UpperCamelCase = np.equal(_A , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(_A , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class lowerCAmelCase_ ( __lowercase, unittest.TestCase, __lowercase ): UpperCAmelCase = True UpperCAmelCase = ( ( FlaxBlenderbotSmallModel, FlaxBlenderbotSmallForConditionalGeneration, ) if is_flax_available() else () ) UpperCAmelCase = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else () def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = FlaxBlenderbotSmallModelTester(self ) def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(_A , _A , _A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(_A , _A , _A ) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _UpperCamelCase = self._prepare_for_class(_A , _A ) _UpperCamelCase = model_class(_A ) @jax.jit def encode_jitted(_A : Optional[int] , _A : Any=None , **_A : str ): return model.encode(input_ids=_A , attention_mask=_A ) with self.subTest('''JIT Enabled''' ): _UpperCamelCase = encode_jitted(**_A ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _UpperCamelCase = encode_jitted(**_A ).to_tuple() self.assertEqual(len(_A ) , len(_A ) ) for jitted_output, output in zip(_A , _A ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _UpperCamelCase = model_class(_A ) _UpperCamelCase = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) _UpperCamelCase = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(_A : Optional[Any] , _A : Dict , _A : List[str] ): return model.decode( decoder_input_ids=_A , decoder_attention_mask=_A , encoder_outputs=_A , ) with self.subTest('''JIT Enabled''' ): _UpperCamelCase = decode_jitted(**_A ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): _UpperCamelCase = decode_jitted(**_A ).to_tuple() self.assertEqual(len(_A ) , len(_A ) ) for jitted_output, output in zip(_A , _A ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCamelCase_ ( self : Any ): for model_class_name in self.all_model_classes: _UpperCamelCase = model_class_name.from_pretrained('''facebook/blenderbot_small-90M''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids _UpperCamelCase = np.ones((1, 1) ) * model.config.eos_token_id _UpperCamelCase = model(_A ) self.assertIsNotNone(_A )
71
import os import re import shutil import sys import tempfile import unittest import black _lowerCAmelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. _lowerCAmelCase = " \"\"\"\n Output class for the scheduler's step function output.\n\n Args:\n prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the\n denoising loop.\n pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n The predicted denoised sample (x_{0}) based on the model output from the current timestep.\n `pred_original_sample` can be used to preview progress or for guidance.\n \"\"\"\n\n prev_sample: torch.FloatTensor\n pred_original_sample: Optional[torch.FloatTensor] = None\n" class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Any ): _UpperCamelCase = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , '''schedulers/''' ) ) _UpperCamelCase = self.diffusers_dir shutil.copy( os.path.join(_A , '''src/diffusers/schedulers/scheduling_ddpm.py''' ) , os.path.join(self.diffusers_dir , '''schedulers/scheduling_ddpm.py''' ) , ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = '''src/diffusers''' shutil.rmtree(self.diffusers_dir ) def UpperCamelCase_ ( self : Union[str, Any] , _A : Tuple , _A : Optional[Any] , _A : Dict , _A : List[str]=None ): _UpperCamelCase = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: _UpperCamelCase = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result _UpperCamelCase = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) _UpperCamelCase = black.format_str(_A , mode=_A ) _UpperCamelCase = os.path.join(self.diffusers_dir , '''new_code.py''' ) with open(_A , '''w''' , newline='''\n''' ) as f: f.write(_A ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(_A ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=_A ) with open(_A , '''r''' ) as f: self.assertTrue(f.read() , _A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = check_copies.find_code_in_diffusers('''schedulers.scheduling_ddpm.DDPMSchedulerOutput''' ) self.assertEqual(_A , _A ) def UpperCamelCase_ ( self : Optional[Any] ): # Base copy consistency self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , REFERENCE_CODE + '''\n''' , ) # With no empty line at the end self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , _A , ) # Copy consistency with rename self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , re.sub('''DDPM''' , '''Test''' , _A ) , ) # Copy consistency with a really long name _UpperCamelCase = '''TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason''' self.check_copy_consistency( F"""# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}""" , F"""{long_class_name}SchedulerOutput""" , re.sub('''Bert''' , _A , _A ) , ) # Copy consistency with overwrite self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , _A , overwrite_result=re.sub('''DDPM''' , '''Test''' , _A ) , )
71
1
def _snake_case ( __snake_case , __snake_case ): # Check if the input is valid if not len(__snake_case ) == len(__snake_case ) == 3: raise ValueError('''Please enter a valid equation.''' ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError('''Both a & b of two equations can\'t be zero.''' ) # Extract the coefficients _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = equationa _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = equationa # Calculate the determinants of the matrices _UpperCamelCase = aa * ba - aa * ba _UpperCamelCase = ca * ba - ca * ba _UpperCamelCase = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError('''Infinite solutions. (Consistent system)''' ) else: raise ValueError('''No solution. (Inconsistent system)''' ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: _UpperCamelCase = determinant_x / determinant _UpperCamelCase = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
71
from __future__ import annotations import math class lowerCAmelCase_ : def __init__( self : int , _A : int ): _UpperCamelCase = size # approximate the overall size of segment tree with given value _UpperCamelCase = [0 for i in range(0 , 4 * size )] # create array to store lazy update _UpperCamelCase = [0 for i in range(0 , 4 * size )] _UpperCamelCase = [0 for i in range(0 , 4 * size )] # flag for lazy update def UpperCamelCase_ ( self : str , _A : int ): return idx * 2 def UpperCamelCase_ ( self : Any , _A : int ): return idx * 2 + 1 def UpperCamelCase_ ( self : Union[str, Any] , _A : int , _A : int , _A : int , _A : list[int] ): if left_element == right_element: _UpperCamelCase = a[left_element - 1] else: _UpperCamelCase = (left_element + right_element) // 2 self.build(self.left(_A ) , _A , _A , _A ) self.build(self.right(_A ) , mid + 1 , _A , _A ) _UpperCamelCase = max( self.segment_tree[self.left(_A )] , self.segment_tree[self.right(_A )] ) def UpperCamelCase_ ( self : Tuple , _A : int , _A : int , _A : int , _A : int , _A : int , _A : int ): if self.flag[idx] is True: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = False if left_element != right_element: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = self.lazy[idx] _UpperCamelCase = True _UpperCamelCase = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: _UpperCamelCase = val if left_element != right_element: _UpperCamelCase = val _UpperCamelCase = val _UpperCamelCase = True _UpperCamelCase = True return True _UpperCamelCase = (left_element + right_element) // 2 self.update(self.left(_A ) , _A , _A , _A , _A , _A ) self.update(self.right(_A ) , mid + 1 , _A , _A , _A , _A ) _UpperCamelCase = max( self.segment_tree[self.left(_A )] , self.segment_tree[self.right(_A )] ) return True def UpperCamelCase_ ( self : Any , _A : int , _A : int , _A : int , _A : int , _A : int ): if self.flag[idx] is True: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = False if left_element != right_element: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = self.lazy[idx] _UpperCamelCase = True _UpperCamelCase = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] _UpperCamelCase = (left_element + right_element) // 2 _UpperCamelCase = self.query(self.left(_A ) , _A , _A , _A , _A ) _UpperCamelCase = self.query(self.right(_A ) , mid + 1 , _A , _A , _A ) return max(_A , _A ) def __str__( self : Tuple ): return str([self.query(1 , 1 , self.size , _A , _A ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _lowerCAmelCase = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _lowerCAmelCase = 15 _lowerCAmelCase = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
71
1
def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): if index == number_of_items: return 0 _UpperCamelCase = 0 _UpperCamelCase = 0 _UpperCamelCase = knapsack(__snake_case , __snake_case , __snake_case , __snake_case , index + 1 ) if weights[index] <= max_weight: _UpperCamelCase = values[index] + knapsack( __snake_case , __snake_case , __snake_case , max_weight - weights[index] , index + 1 ) return max(__snake_case , __snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
71
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase = { "configuration_jukebox": [ "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "JukeboxConfig", "JukeboxPriorConfig", "JukeboxVQVAEConfig", ], "tokenization_jukebox": ["JukeboxTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST", "JukeboxModel", "JukeboxPreTrainedModel", "JukeboxVQVAE", "JukeboxPrior", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
1
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 _lowerCAmelCase = get_tests_dir("fixtures") class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Optional[Any] ): # A mock response for an HTTP head request to emulate server down _UpperCamelCase = mock.Mock() _UpperCamelCase = 500 _UpperCamelCase = {} _UpperCamelCase = HTTPError _UpperCamelCase = {} # Download this model to make sure it's in the cache. _UpperCamelCase = ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=_A ) as mock_head: _UpperCamelCase = ViTImageProcessor.from_pretrained('''hf-internal-testing/tiny-random-vit''' ) # This check we did call the fake head request mock_head.assert_called() def UpperCamelCase_ ( self : Tuple ): # This test is for deprecated behavior and can be removed in v5 _UpperCamelCase = ViTImageProcessor.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json''' ) def UpperCamelCase_ ( self : str ): with self.assertRaises(_A ): # config is in subfolder, the following should not work without specifying the subfolder _UpperCamelCase = AutoImageProcessor.from_pretrained('''hf-internal-testing/stable-diffusion-all-variants''' ) _UpperCamelCase = AutoImageProcessor.from_pretrained( '''hf-internal-testing/stable-diffusion-all-variants''' , subfolder='''feature_extractor''' ) self.assertIsNotNone(_A ) @is_staging_test class lowerCAmelCase_ ( unittest.TestCase ): @classmethod def UpperCamelCase_ ( cls : Optional[int] ): _UpperCamelCase = TOKEN HfFolder.save_token(_A ) @classmethod def UpperCamelCase_ ( cls : Optional[int] ): try: delete_repo(token=cls._token , repo_id='''test-image-processor''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-image-processor-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-image-processor''' ) except HTTPError: pass def UpperCamelCase_ ( self : int ): _UpperCamelCase = ViTImageProcessor.from_pretrained(_A ) image_processor.push_to_hub('''test-image-processor''' , use_auth_token=self._token ) _UpperCamelCase = ViTImageProcessor.from_pretrained(F"""{USER}/test-image-processor""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(_A , getattr(_A , _A ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-image-processor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( _A , repo_id='''test-image-processor''' , push_to_hub=_A , use_auth_token=self._token ) _UpperCamelCase = ViTImageProcessor.from_pretrained(F"""{USER}/test-image-processor""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(_A , getattr(_A , _A ) ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = ViTImageProcessor.from_pretrained(_A ) image_processor.push_to_hub('''valid_org/test-image-processor''' , use_auth_token=self._token ) _UpperCamelCase = ViTImageProcessor.from_pretrained('''valid_org/test-image-processor''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(_A , getattr(_A , _A ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-image-processor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( _A , repo_id='''valid_org/test-image-processor-org''' , push_to_hub=_A , use_auth_token=self._token ) _UpperCamelCase = ViTImageProcessor.from_pretrained('''valid_org/test-image-processor-org''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(_A , getattr(_A , _A ) ) def UpperCamelCase_ ( self : List[Any] ): CustomImageProcessor.register_for_auto_class() _UpperCamelCase = CustomImageProcessor.from_pretrained(_A ) image_processor.push_to_hub('''test-dynamic-image-processor''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {'''AutoImageProcessor''': '''custom_image_processing.CustomImageProcessor'''} , ) _UpperCamelCase = AutoImageProcessor.from_pretrained( F"""{USER}/test-dynamic-image-processor""" , trust_remote_code=_A ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , '''CustomImageProcessor''' )
71
import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase_ ( __lowercase ): def __init__( self : int , _A : NestedDataStructureLike[PathLike] , _A : Optional[NamedSplit] = None , _A : Optional[Features] = None , _A : str = None , _A : bool = False , _A : bool = False , _A : Optional[str] = None , _A : Optional[int] = None , **_A : str , ): super().__init__( _A , split=_A , features=_A , cache_dir=_A , keep_in_memory=_A , streaming=_A , num_proc=_A , **_A , ) _UpperCamelCase = field _UpperCamelCase = path_or_paths if isinstance(_A , _A ) else {self.split: path_or_paths} _UpperCamelCase = Json( cache_dir=_A , data_files=_A , features=_A , field=_A , **_A , ) def UpperCamelCase_ ( self : List[str] ): # Build iterable dataset if self.streaming: _UpperCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None self.builder.download_and_prepare( download_config=_A , download_mode=_A , verification_mode=_A , base_path=_A , num_proc=self.num_proc , ) _UpperCamelCase = self.builder.as_dataset( split=self.split , verification_mode=_A , in_memory=self.keep_in_memory ) return dataset class lowerCAmelCase_ : def __init__( self : Optional[Any] , _A : Dataset , _A : Union[PathLike, BinaryIO] , _A : Optional[int] = None , _A : Optional[int] = None , **_A : List[str] , ): if num_proc is not None and num_proc <= 0: raise ValueError(F"""num_proc {num_proc} must be an integer > 0.""" ) _UpperCamelCase = dataset _UpperCamelCase = path_or_buf _UpperCamelCase = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _UpperCamelCase = num_proc _UpperCamelCase = '''utf-8''' _UpperCamelCase = to_json_kwargs def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = self.to_json_kwargs.pop('''path_or_buf''' , _A ) _UpperCamelCase = self.to_json_kwargs.pop('''orient''' , '''records''' ) _UpperCamelCase = self.to_json_kwargs.pop('''lines''' , True if orient == '''records''' else False ) _UpperCamelCase = self.to_json_kwargs.pop('''index''' , False if orient in ['''split''', '''table'''] else True ) _UpperCamelCase = self.to_json_kwargs.pop('''compression''' , _A ) if compression not in [None, "infer", "gzip", "bz2", "xz"]: raise NotImplementedError(F"""`datasets` currently does not support {compression} compression""" ) if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with fsspec.open(self.path_or_buf , '''wb''' , compression=_A ) as buffer: _UpperCamelCase = self._write(file_obj=_A , orient=_A , lines=_A , index=_A , **self.to_json_kwargs ) else: if compression: raise NotImplementedError( F"""The compression parameter is not supported when writing to a buffer, but compression={compression}""" ''' was passed. Please provide a local path instead.''' ) _UpperCamelCase = self._write( file_obj=self.path_or_buf , orient=_A , lines=_A , index=_A , **self.to_json_kwargs ) return written def UpperCamelCase_ ( self : Any , _A : Optional[Any] ): _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = args _UpperCamelCase = query_table( table=self.dataset.data , key=slice(_A , offset + self.batch_size ) , indices=self.dataset._indices , ) _UpperCamelCase = batch.to_pandas().to_json( path_or_buf=_A , orient=_A , lines=_A , index=_A , **_A ) if not json_str.endswith('''\n''' ): json_str += "\n" return json_str.encode(self.encoding ) def UpperCamelCase_ ( self : int , _A : BinaryIO , _A : Dict , _A : Optional[Any] , _A : Dict , **_A : str , ): _UpperCamelCase = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating json from Arrow format''' , ): _UpperCamelCase = self._batch_json((offset, orient, lines, index, to_json_kwargs) ) written += file_obj.write(_A ) else: _UpperCamelCase , _UpperCamelCase = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for json_str in logging.tqdm( pool.imap( self._batch_json , [(offset, orient, lines, index, to_json_kwargs) for offset in range(0 , _A , _A )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating json from Arrow format''' , ): written += file_obj.write(_A ) return written
71
1
import heapq def _snake_case ( __snake_case ): _UpperCamelCase = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(__snake_case , [-1 * len(__snake_case ), (key, value)] ) # chosen_vertices = set of chosen vertices _UpperCamelCase = set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices _UpperCamelCase = heapq.heappop(__snake_case )[1][0] chosen_vertices.add(__snake_case ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: _UpperCamelCase = elem[1][1].index(__snake_case ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(__snake_case ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowerCAmelCase = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}')
71
import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class lowerCAmelCase_ ( enum.Enum ): UpperCAmelCase = 0 UpperCAmelCase = 1 UpperCAmelCase = 2 @add_end_docstrings(__lowercase ) class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n " def __init__( self : Tuple , *_A : List[str] , **_A : str ): super().__init__(*_A , **_A ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == '''tf''' else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. _UpperCamelCase = None if self.model.config.prefix is not None: _UpperCamelCase = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. _UpperCamelCase = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = self._sanitize_parameters(prefix=_A , **self._forward_params ) _UpperCamelCase = {**self._preprocess_params, **preprocess_params} _UpperCamelCase = {**self._forward_params, **forward_params} def UpperCamelCase_ ( self : Dict , _A : Optional[int]=None , _A : Any=None , _A : Optional[int]=None , _A : List[str]=None , _A : List[Any]=None , _A : int=None , _A : Tuple=None , _A : Optional[Any]=None , **_A : Optional[int] , ): _UpperCamelCase = {} if prefix is not None: _UpperCamelCase = prefix if prefix: _UpperCamelCase = self.tokenizer( _A , padding=_A , add_special_tokens=_A , return_tensors=self.framework ) _UpperCamelCase = prefix_inputs['''input_ids'''].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( F"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected""" ''' [None, \'hole\']''' ) _UpperCamelCase = handle_long_generation preprocess_params.update(_A ) _UpperCamelCase = generate_kwargs _UpperCamelCase = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_full_text`''' ) if return_tensors is not None: raise ValueError('''`return_full_text` is mutually exclusive with `return_tensors`''' ) _UpperCamelCase = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_tensors`''' ) _UpperCamelCase = ReturnType.TENSORS if return_type is not None: _UpperCamelCase = return_type if clean_up_tokenization_spaces is not None: _UpperCamelCase = clean_up_tokenization_spaces if stop_sequence is not None: _UpperCamelCase = self.tokenizer.encode(_A , add_special_tokens=_A ) if len(_A ) > 1: warnings.warn( '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of''' ''' the stop sequence will be used as the stop sequence string in the interim.''' ) _UpperCamelCase = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCamelCase_ ( self : int , *_A : Union[str, Any] , **_A : Union[str, Any] ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({'''add_space_before_punct_symbol''': True} ) return super()._parse_and_tokenize(*_A , **_A ) def __call__( self : List[str] , _A : str , **_A : Any ): return super().__call__(_A , **_A ) def UpperCamelCase_ ( self : Optional[Any] , _A : List[str] , _A : int="" , _A : Optional[Any]=None , **_A : Optional[Any] ): _UpperCamelCase = self.tokenizer( prefix + prompt_text , padding=_A , add_special_tokens=_A , return_tensors=self.framework ) _UpperCamelCase = prompt_text if handle_long_generation == "hole": _UpperCamelCase = inputs['''input_ids'''].shape[-1] if "max_new_tokens" in generate_kwargs: _UpperCamelCase = generate_kwargs['''max_new_tokens'''] else: _UpperCamelCase = generate_kwargs.get('''max_length''' , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError('''We cannot infer how many new tokens are expected''' ) if cur_len + new_tokens > self.tokenizer.model_max_length: _UpperCamelCase = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( '''We cannot use `hole` to handle this generation the number of desired tokens exceeds the''' ''' models max length''' ) _UpperCamelCase = inputs['''input_ids'''][:, -keep_length:] if "attention_mask" in inputs: _UpperCamelCase = inputs['''attention_mask'''][:, -keep_length:] return inputs def UpperCamelCase_ ( self : Dict , _A : Optional[int] , **_A : str ): _UpperCamelCase = model_inputs['''input_ids'''] _UpperCamelCase = model_inputs.get('''attention_mask''' , _A ) # Allow empty prompts if input_ids.shape[1] == 0: _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = 1 else: _UpperCamelCase = input_ids.shape[0] _UpperCamelCase = model_inputs.pop('''prompt_text''' ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. _UpperCamelCase = generate_kwargs.pop('''prefix_length''' , 0 ) if prefix_length > 0: _UpperCamelCase = '''max_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].max_new_tokens is not None ) if not has_max_new_tokens: _UpperCamelCase = generate_kwargs.get('''max_length''' ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length _UpperCamelCase = '''min_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL _UpperCamelCase = self.model.generate(input_ids=_A , attention_mask=_A , **_A ) _UpperCamelCase = generated_sequence.shape[0] if self.framework == "pt": _UpperCamelCase = generated_sequence.reshape(_A , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": _UpperCamelCase = tf.reshape(_A , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def UpperCamelCase_ ( self : List[str] , _A : Dict , _A : Optional[Any]=ReturnType.FULL_TEXT , _A : Dict=True ): _UpperCamelCase = model_outputs['''generated_sequence'''][0] _UpperCamelCase = model_outputs['''input_ids'''] _UpperCamelCase = model_outputs['''prompt_text'''] _UpperCamelCase = generated_sequence.numpy().tolist() _UpperCamelCase = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: _UpperCamelCase = {'''generated_token_ids''': sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text _UpperCamelCase = self.tokenizer.decode( _A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: _UpperCamelCase = 0 else: _UpperCamelCase = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_A , clean_up_tokenization_spaces=_A , ) ) if return_type == ReturnType.FULL_TEXT: _UpperCamelCase = prompt_text + text[prompt_length:] else: _UpperCamelCase = text[prompt_length:] _UpperCamelCase = {'''generated_text''': all_text} records.append(_A ) return records
71
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowerCAmelCase = { "configuration_perceiver": ["PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP", "PerceiverConfig", "PerceiverOnnxConfig"], "tokenization_perceiver": ["PerceiverTokenizer"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = ["PerceiverFeatureExtractor"] _lowerCAmelCase = ["PerceiverImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST", "PerceiverForImageClassificationConvProcessing", "PerceiverForImageClassificationFourier", "PerceiverForImageClassificationLearned", "PerceiverForMaskedLM", "PerceiverForMultimodalAutoencoding", "PerceiverForOpticalFlow", "PerceiverForSequenceClassification", "PerceiverLayer", "PerceiverModel", "PerceiverPreTrainedModel", ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : Any ): _UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=_A ).to(_A ) _UpperCamelCase = AutoTokenizer.from_pretrained('''google/mt5-small''' ) _UpperCamelCase = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids _UpperCamelCase = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids _UpperCamelCase = model(input_ids.to(_A ) , labels=labels.to(_A ) ).loss _UpperCamelCase = -(labels.shape[-1] * loss.item()) _UpperCamelCase = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
71
1
from torch import nn def _snake_case ( __snake_case ): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f"""Unsupported activation function: {act_fn}""" )
71
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _lowerCAmelCase = logging.getLogger(__name__) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether tp freeze the encoder."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) UpperCAmelCase = field( default="summarization", metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"}, ) UpperCAmelCase = field( default=1024, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=128, metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field(default=-1, metadata={"help": "# training examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# validation examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# test examples. -1 means use all."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Source language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Target language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "# num_beams to use for evaluation."} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."}, ) def _snake_case ( __snake_case , __snake_case , __snake_case ): logger.info(f"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(f""" {key} = {metrics[key]}""" ) save_json(__snake_case , os.path.join(__snake_case , f"""{split}_results.json""" ) ) def _snake_case ( ): # 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. _UpperCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_args_into_dataclasses() check_output_dir(__snake_case ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , __snake_case ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _UpperCamelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _UpperCamelCase = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(__snake_case , __snake_case , __snake_case ): assert hasattr(__snake_case , __snake_case ), f"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(__snake_case , __snake_case , getattr(__snake_case , __snake_case ) ) _UpperCamelCase = 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 , ) _UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=__snake_case , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(__snake_case , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: _UpperCamelCase = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(__snake_case , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(__snake_case , __snake_case ): _UpperCamelCase = tokenizer.lang_code_to_id[data_args.tgt_lang] else: _UpperCamelCase = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(__snake_case ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) _UpperCamelCase = SeqaSeqDataset # Get datasets _UpperCamelCase = ( dataset_class( __snake_case , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer _UpperCamelCase = ( build_compute_metrics_fn(data_args.task , __snake_case ) if training_args.predict_with_generate else None ) _UpperCamelCase = SeqaSeqTrainer( model=__snake_case , args=__snake_case , data_args=__snake_case , train_dataset=__snake_case , eval_dataset=__snake_case , data_collator=SeqaSeqDataCollator( __snake_case , __snake_case , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=__snake_case , tokenizer=__snake_case , ) _UpperCamelCase = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) _UpperCamelCase = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) _UpperCamelCase = train_result.metrics _UpperCamelCase = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) _UpperCamelCase = trainer.evaluate(metric_key_prefix='''val''' ) _UpperCamelCase = data_args.n_val _UpperCamelCase = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.do_predict: logger.info('''*** Predict ***''' ) _UpperCamelCase = trainer.predict(test_dataset=__snake_case , metric_key_prefix='''test''' ) _UpperCamelCase = test_output.metrics _UpperCamelCase = data_args.n_test if trainer.is_world_process_zero(): _UpperCamelCase = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.predict_with_generate: _UpperCamelCase = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=__snake_case , clean_up_tokenization_spaces=__snake_case ) _UpperCamelCase = lmap(str.strip , __snake_case ) write_txt_file(__snake_case , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(__snake_case , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def _snake_case ( __snake_case ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
71
1
import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def _snake_case ( __snake_case ): # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def _snake_case ( ): with parallel_backend('''spark''' ): assert ParallelBackendConfig.backend_name == "spark" _UpperCamelCase = [1, 2, 3] with pytest.raises(__snake_case ): with parallel_backend('''unsupported backend''' ): map_nested(__snake_case , __snake_case , num_proc=2 ) with pytest.raises(__snake_case ): with parallel_backend('''unsupported backend''' ): map_nested(__snake_case , __snake_case , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize('''num_proc''' , [2, -1] ) def _snake_case ( __snake_case ): _UpperCamelCase = [1, 2] _UpperCamelCase = {'''a''': 1, '''b''': 2} _UpperCamelCase = {'''a''': [1, 2], '''b''': [3, 4]} _UpperCamelCase = {'''a''': {'''1''': 1}, '''b''': 2} _UpperCamelCase = {'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4} _UpperCamelCase = [2, 3] _UpperCamelCase = {'''a''': 2, '''b''': 3} _UpperCamelCase = {'''a''': [2, 3], '''b''': [4, 5]} _UpperCamelCase = {'''a''': {'''1''': 2}, '''b''': 3} _UpperCamelCase = {'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5} with parallel_backend('''spark''' ): assert map_nested(__snake_case , __snake_case , num_proc=__snake_case ) == expected_map_nested_sa assert map_nested(__snake_case , __snake_case , num_proc=__snake_case ) == expected_map_nested_sa assert map_nested(__snake_case , __snake_case , num_proc=__snake_case ) == expected_map_nested_sa assert map_nested(__snake_case , __snake_case , num_proc=__snake_case ) == expected_map_nested_sa assert map_nested(__snake_case , __snake_case , num_proc=__snake_case ) == expected_map_nested_sa
71
from __future__ import annotations import typing from collections import Counter def _snake_case ( __snake_case ): _UpperCamelCase = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(__snake_case , max_perimeter + 1 ): _UpperCamelCase = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__snake_case ): _UpperCamelCase = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _snake_case ( __snake_case = 1000 ): _UpperCamelCase = pythagorean_triple(__snake_case ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'Perimeter {solution()} has maximum solutions')
71
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class lowerCAmelCase_ ( __lowercase, __lowercase, unittest.TestCase ): UpperCAmelCase = StableDiffusionPanoramaPipeline UpperCAmelCase = TEXT_TO_IMAGE_PARAMS UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS def UpperCamelCase_ ( self : Union[str, Any] ): torch.manual_seed(0 ) _UpperCamelCase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) _UpperCamelCase = DDIMScheduler() torch.manual_seed(0 ) _UpperCamelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) _UpperCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _UpperCamelCase = CLIPTextModel(_A ) _UpperCamelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) _UpperCamelCase = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def UpperCamelCase_ ( self : Optional[Any] , _A : str , _A : int=0 ): _UpperCamelCase = torch.manual_seed(_A ) _UpperCamelCase = { '''prompt''': '''a photo of the dolomites''', '''generator''': generator, # Setting height and width to None to prevent OOMs on CPU. '''height''': None, '''width''': None, '''num_inference_steps''': 1, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = StableDiffusionPanoramaPipeline(**_A ) _UpperCamelCase = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = sd_pipe(**_A ).images _UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCamelCase = np.array([0.6186, 0.5374, 0.4915, 0.4135, 0.4114, 0.4563, 0.5128, 0.4977, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase_ ( self : List[Any] ): super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCamelCase_ ( self : Optional[int] ): super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25e-3 ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = StableDiffusionPanoramaPipeline(**_A ) _UpperCamelCase = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = '''french fries''' _UpperCamelCase = sd_pipe(**_A , negative_prompt=_A ) _UpperCamelCase = output.images _UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCamelCase = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase_ ( self : int ): _UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = StableDiffusionPanoramaPipeline(**_A ) _UpperCamelCase = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = sd_pipe(**_A , view_batch_size=2 ) _UpperCamelCase = output.images _UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCamelCase = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='''scaled_linear''' ) _UpperCamelCase = StableDiffusionPanoramaPipeline(**_A ) _UpperCamelCase = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = sd_pipe(**_A ).images _UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCamelCase = np.array([0.4024, 0.6510, 0.4901, 0.5378, 0.5813, 0.5622, 0.4795, 0.4467, 0.4952] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = PNDMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , skip_prk_steps=_A ) _UpperCamelCase = StableDiffusionPanoramaPipeline(**_A ) _UpperCamelCase = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = sd_pipe(**_A ).images _UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCamelCase = np.array([0.6391, 0.6291, 0.4861, 0.5134, 0.5552, 0.4578, 0.5032, 0.5023, 0.4539] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Optional[int] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self : Tuple , _A : Tuple=0 ): _UpperCamelCase = torch.manual_seed(_A ) _UpperCamelCase = { '''prompt''': '''a photo of the dolomites''', '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def UpperCamelCase_ ( self : str ): _UpperCamelCase = '''stabilityai/stable-diffusion-2-base''' _UpperCamelCase = DDIMScheduler.from_pretrained(_A , subfolder='''scheduler''' ) _UpperCamelCase = StableDiffusionPanoramaPipeline.from_pretrained(_A , scheduler=_A , safety_checker=_A ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() _UpperCamelCase = self.get_inputs() _UpperCamelCase = pipe(**_A ).images _UpperCamelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) _UpperCamelCase = np.array( [ 0.3696_8392, 0.2702_5372, 0.3244_6766, 0.2837_9387, 0.3636_3274, 0.3073_3347, 0.2710_0027, 0.2705_4125, 0.2553_6096, ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-2 def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = StableDiffusionPanoramaPipeline.from_pretrained( '''stabilityai/stable-diffusion-2-base''' , safety_checker=_A ) _UpperCamelCase = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() _UpperCamelCase = self.get_inputs() _UpperCamelCase = pipe(**_A ).images _UpperCamelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) _UpperCamelCase = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def UpperCamelCase_ ( self : int ): _UpperCamelCase = 0 def callback_fn(_A : int , _A : int , _A : torch.FloatTensor ) -> None: _UpperCamelCase = True nonlocal number_of_steps number_of_steps += 1 if step == 1: _UpperCamelCase = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) _UpperCamelCase = latents[0, -3:, -3:, -1] _UpperCamelCase = np.array( [ 0.1868_1869, 0.3390_7816, 0.536_1276, 0.1443_2865, -0.0285_6611, -0.7394_1123, 0.2339_7987, 0.4732_2682, -0.3782_3164, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: _UpperCamelCase = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) _UpperCamelCase = latents[0, -3:, -3:, -1] _UpperCamelCase = np.array( [ 0.1853_9645, 0.3398_7248, 0.537_8559, 0.1443_7142, -0.0245_5261, -0.733_8317, 0.2399_0755, 0.4735_6272, -0.378_6505, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 _UpperCamelCase = False _UpperCamelCase = '''stabilityai/stable-diffusion-2-base''' _UpperCamelCase = DDIMScheduler.from_pretrained(_A , subfolder='''scheduler''' ) _UpperCamelCase = StableDiffusionPanoramaPipeline.from_pretrained(_A , scheduler=_A , safety_checker=_A ) _UpperCamelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() _UpperCamelCase = self.get_inputs() pipe(**_A , callback=_A , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def UpperCamelCase_ ( self : int ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _UpperCamelCase = '''stabilityai/stable-diffusion-2-base''' _UpperCamelCase = DDIMScheduler.from_pretrained(_A , subfolder='''scheduler''' ) _UpperCamelCase = StableDiffusionPanoramaPipeline.from_pretrained(_A , scheduler=_A , safety_checker=_A ) _UpperCamelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _UpperCamelCase = self.get_inputs() _UpperCamelCase = pipe(**_A ) _UpperCamelCase = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
71
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = (DPMSolverSDEScheduler,) UpperCAmelCase = 10 def UpperCamelCase_ ( self : Tuple , **_A : Union[str, Any] ): _UpperCamelCase = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''noise_sampler_seed''': 0, } config.update(**_A ) return config def UpperCamelCase_ ( self : List[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=_A ) def UpperCamelCase_ ( self : List[Any] ): for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_A , beta_end=_A ) def UpperCamelCase_ ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_A ) def UpperCamelCase_ ( self : Union[str, Any] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_8210_4492_1875 ) < 1e-2 assert abs(result_mean.item() - 0.2178_7059_6456_5277 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3521_1181_6406 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9068_9229_9652 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_1492_0043_9453 ) < 1e-2 assert abs(result_mean.item() - 0.1_6226_2890_1481_6284 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_6633_6059_5703 ) < 1e-2 assert abs(result_mean.item() - 0.1_6688_3260_0116_7297 ) < 1e-3 else: assert abs(result_sum.item() - 119.8_4875_4882_8125 ) < 1e-2 assert abs(result_mean.item() - 0.1560_5306_6253_6621 ) < 1e-3 def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps , device=_A ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter.to(_A ) * scheduler.init_noise_sigma for t in scheduler.timesteps: _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_9573_9746_0938 ) < 1e-2 assert abs(result_mean.item() - 0.2_1805_9346_0798_2635 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3536_3769_5312 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9083_8241_5771 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A , use_karras_sigmas=_A ) scheduler.set_timesteps(self.num_inference_steps , device=_A ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter.to(_A ) * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for t in scheduler.timesteps: _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_9741_3574_2188 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_6535_6445_3125 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 else: assert abs(result_sum.item() - 170.3_1352_2338_8672 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2
71
1
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput _lowerCAmelCase = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase_ ( __lowercase ): def __init__( self : List[Any] , *_A : Any , _A : Tuple=None , _A : Any=None , _A : Union[str, Any]=None , **_A : str ): super().__init__(*_A , **_A ) _UpperCamelCase = eval_examples _UpperCamelCase = post_process_function _UpperCamelCase = quant_trainer_args _UpperCamelCase = 128 # default number of calibration samples def UpperCamelCase_ ( self : List[Any] , _A : Optional[int]=None ): if calib_dataset is None and self.calib_dataset is None: raise ValueError('''Trainer: calibration requires an calib_dataset.''' ) _UpperCamelCase = calib_dataset if calib_dataset is not None else self.calib_dataset _UpperCamelCase = self._remove_unused_columns(_A , description='''Calibration''' ) return DataLoader( _A , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=_A , ) def UpperCamelCase_ ( self : List[str] , _A : Any=None ): _UpperCamelCase = self.train_dataset if calib_dataset is None else calib_dataset _UpperCamelCase = self.get_calib_dataloader(_A ) _UpperCamelCase = self.model quant_trainer.configure_model(_A , self.quant_trainer_args , calib=_A ) model.eval() quant_trainer.enable_calibration(_A ) logger.info('''***** Running calibration *****''' ) logger.info(F""" Num examples = {self.calib_num}""" ) logger.info(F""" Batch size = {calib_dataloader.batch_size}""" ) for step, inputs in enumerate(_A ): # Prediction step _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = self.prediction_step(_A , _A , prediction_loss_only=_A ) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(_A , self.quant_trainer_args ) _UpperCamelCase = model def UpperCamelCase_ ( self : Optional[Any] , _A : Optional[int]=None , _A : Dict=None , _A : Optional[int]=None , _A : str = "eval" ): _UpperCamelCase = self.eval_dataset if eval_dataset is None else eval_dataset _UpperCamelCase = self.get_eval_dataloader(_A ) _UpperCamelCase = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. _UpperCamelCase = self.compute_metrics _UpperCamelCase = None _UpperCamelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: _UpperCamelCase = eval_loop( _A , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , ) finally: _UpperCamelCase = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: _UpperCamelCase = self.post_process_function(_A , _A , output.predictions ) _UpperCamelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): _UpperCamelCase = metrics.pop(_A ) self.log(_A ) else: _UpperCamelCase = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) _UpperCamelCase = self.callback_handler.on_evaluate(self.args , self.state , self.control , _A ) return metrics def UpperCamelCase_ ( self : Union[str, Any] , _A : Tuple , _A : Any , _A : Dict=None , _A : str = "test" ): _UpperCamelCase = self.get_test_dataloader(_A ) # Temporarily disable metric computation, we will do it in the loop here. _UpperCamelCase = self.compute_metrics _UpperCamelCase = None _UpperCamelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: _UpperCamelCase = eval_loop( _A , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , ) finally: _UpperCamelCase = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output _UpperCamelCase = self.post_process_function(_A , _A , output.predictions , '''predict''' ) _UpperCamelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): _UpperCamelCase = metrics.pop(_A ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_A ) def UpperCamelCase_ ( self : str , _A : str="./" ): _UpperCamelCase = self.eval_dataset _UpperCamelCase = self.get_eval_dataloader(_A ) _UpperCamelCase = next(iter(_A ) ) # saving device - to make it consistent _UpperCamelCase = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' ) # convert to tuple _UpperCamelCase = tuple(v.to(_A ) for k, v in batch.items() ) logger.info('''Converting model to be onnx compatible''' ) from pytorch_quantization.nn import TensorQuantizer _UpperCamelCase = True _UpperCamelCase = self.model.to(_A ) model.eval() model.float() _UpperCamelCase = model.module if hasattr(_A , '''module''' ) else model quant_trainer.configure_model(_A , self.quant_trainer_args ) _UpperCamelCase = os.path.join(_A , '''model.onnx''' ) logger.info(F"""exporting model to {output_model_file}""" ) _UpperCamelCase = {0: '''batch_size''', 1: '''seq_len'''} torch.onnx.export( _A , _A , _A , export_params=_A , opset_version=13 , do_constant_folding=_A , input_names=['''input_ids''', '''attention_mask''', '''token_type_ids'''] , output_names=['''output_start_logits''', '''output_end_logits'''] , dynamic_axes={ '''input_ids''': axes, '''attention_mask''': axes, '''token_type_ids''': axes, '''output_start_logits''': axes, '''output_end_logits''': axes, } , verbose=_A , ) logger.info('''onnx export finished''' )
71
import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class lowerCAmelCase_ : @property def UpperCamelCase_ ( self : Optional[int] ): return self.get_dummy_input() @property def UpperCamelCase_ ( self : Dict ): if self.block_type == "down": return (4, 32, 16, 16) elif self.block_type == "mid": return (4, 32, 32, 32) elif self.block_type == "up": return (4, 32, 64, 64) raise ValueError(F"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'.""" ) def UpperCamelCase_ ( self : Union[str, Any] , _A : List[str]=True , _A : Any=False , _A : Union[str, Any]=False , _A : int=False , ): _UpperCamelCase = 4 _UpperCamelCase = 32 _UpperCamelCase = (32, 32) _UpperCamelCase = torch.manual_seed(0 ) _UpperCamelCase = torch.device(_A ) _UpperCamelCase = (batch_size, num_channels) + sizes _UpperCamelCase = randn_tensor(_A , generator=_A , device=_A ) _UpperCamelCase = {'''hidden_states''': hidden_states} if include_temb: _UpperCamelCase = 128 _UpperCamelCase = randn_tensor((batch_size, temb_channels) , generator=_A , device=_A ) if include_res_hidden_states_tuple: _UpperCamelCase = torch.manual_seed(1 ) _UpperCamelCase = (randn_tensor(_A , generator=_A , device=_A ),) if include_encoder_hidden_states: _UpperCamelCase = floats_tensor((batch_size, 32, 32) ).to(_A ) if include_skip_sample: _UpperCamelCase = randn_tensor(((batch_size, 3) + sizes) , generator=_A , device=_A ) return dummy_input def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = { '''in_channels''': 32, '''out_channels''': 32, '''temb_channels''': 128, } if self.block_type == "up": _UpperCamelCase = 32 if self.block_type == "mid": init_dict.pop('''out_channels''' ) _UpperCamelCase = self.dummy_input return init_dict, inputs_dict def UpperCamelCase_ ( self : Tuple , _A : Union[str, Any] ): _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**_A ) unet_block.to(_A ) unet_block.eval() with torch.no_grad(): _UpperCamelCase = unet_block(**_A ) if isinstance(_A , _A ): _UpperCamelCase = output[0] self.assertEqual(output.shape , self.output_shape ) _UpperCamelCase = output[0, -1, -3:, -3:] _UpperCamelCase = torch.tensor(_A ).to(_A ) assert torch_all_close(output_slice.flatten() , _A , atol=5e-3 ) @unittest.skipIf(torch_device == '''mps''' , '''Training is not supported in mps''' ) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**_A ) model.to(_A ) model.train() _UpperCamelCase = model(**_A ) if isinstance(_A , _A ): _UpperCamelCase = output[0] _UpperCamelCase = torch.device(_A ) _UpperCamelCase = randn_tensor(output.shape , device=_A ) _UpperCamelCase = torch.nn.functional.mse_loss(_A , _A ) loss.backward()
71
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase = { "configuration_xmod": [ "XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP", "XmodConfig", "XmodOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "XMOD_PRETRAINED_MODEL_ARCHIVE_LIST", "XmodForCausalLM", "XmodForMaskedLM", "XmodForMultipleChoice", "XmodForQuestionAnswering", "XmodForSequenceClassification", "XmodForTokenClassification", "XmodModel", "XmodPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
def _snake_case ( __snake_case ): if not isinstance(__snake_case , __snake_case ): raise TypeError('''Input value must be an \'int\' type''' ) _UpperCamelCase = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
71
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() _lowerCAmelCase = logging.get_logger(__name__) def _snake_case ( __snake_case ): _UpperCamelCase = '''huggingface/label-files''' _UpperCamelCase = '''imagenet-1k-id2label.json''' _UpperCamelCase = json.load(open(hf_hub_download(__snake_case , __snake_case , repo_type='''dataset''' ) , '''r''' ) ) _UpperCamelCase = {int(__snake_case ): v for k, v in idalabel.items()} _UpperCamelCase = {v: k for k, v in idalabel.items()} _UpperCamelCase = '''std_conv''' if '''bit''' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" _UpperCamelCase = BitConfig( conv_layer=__snake_case , num_labels=1000 , idalabel=__snake_case , labelaid=__snake_case , ) return config def _snake_case ( __snake_case ): if "stem.conv" in name: _UpperCamelCase = name.replace('''stem.conv''' , '''bit.embedder.convolution''' ) if "blocks" in name: _UpperCamelCase = name.replace('''blocks''' , '''layers''' ) if "head.fc" in name: _UpperCamelCase = name.replace('''head.fc''' , '''classifier.1''' ) if name.startswith('''norm''' ): _UpperCamelCase = '''bit.''' + name if "bit" not in name and "classifier" not in name: _UpperCamelCase = '''bit.encoder.''' + name return name def _snake_case ( ): _UpperCamelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' _UpperCamelCase = Image.open(requests.get(__snake_case , stream=__snake_case ).raw ) return im @torch.no_grad() def _snake_case ( __snake_case , __snake_case , __snake_case=False ): _UpperCamelCase = get_config(__snake_case ) # load original model from timm _UpperCamelCase = create_model(__snake_case , pretrained=__snake_case ) timm_model.eval() # load state_dict of original model _UpperCamelCase = timm_model.state_dict() for key in state_dict.copy().keys(): _UpperCamelCase = state_dict.pop(__snake_case ) _UpperCamelCase = val.squeeze() if '''head''' in key else val # load HuggingFace model _UpperCamelCase = BitForImageClassification(__snake_case ) model.eval() model.load_state_dict(__snake_case ) # create image processor _UpperCamelCase = create_transform(**resolve_data_config({} , model=__snake_case ) ) _UpperCamelCase = transform.transforms _UpperCamelCase = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } _UpperCamelCase = BitImageProcessor( do_resize=__snake_case , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=__snake_case , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=__snake_case , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) _UpperCamelCase = prepare_img() _UpperCamelCase = transform(__snake_case ).unsqueeze(0 ) _UpperCamelCase = processor(__snake_case , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(__snake_case , __snake_case ) # verify logits with torch.no_grad(): _UpperCamelCase = model(__snake_case ) _UpperCamelCase = outputs.logits print('''Logits:''' , logits[0, :3] ) print('''Predicted class:''' , model.config.idalabel[logits.argmax(-1 ).item()] ) _UpperCamelCase = timm_model(__snake_case ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__snake_case , outputs.logits , atol=1E-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(__snake_case ).mkdir(exist_ok=__snake_case ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(__snake_case ) processor.save_pretrained(__snake_case ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": _lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="resnetv2_50x1_bitm", type=str, help="Name of the BiT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model to the hub.", ) _lowerCAmelCase = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
71
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } _lowerCAmelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): for attribute in key.split('''.''' ): _UpperCamelCase = getattr(__snake_case , __snake_case ) if weight_type is not None: _UpperCamelCase = getattr(__snake_case , __snake_case ).shape else: _UpperCamelCase = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": _UpperCamelCase = value elif weight_type == "weight_g": _UpperCamelCase = value elif weight_type == "weight_v": _UpperCamelCase = value elif weight_type == "bias": _UpperCamelCase = value else: _UpperCamelCase = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = [] _UpperCamelCase = fairseq_model.state_dict() _UpperCamelCase = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _UpperCamelCase = None for name, value in fairseq_dict.items(): _UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __snake_case , __snake_case , __snake_case , __snake_case , hf_model.config.feat_extract_norm == '''group''' , ) _UpperCamelCase = True elif name.split('''.''' )[0] == "proj": _UpperCamelCase = fairseq_model.proj _UpperCamelCase = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: _UpperCamelCase = True if "*" in mapped_key: _UpperCamelCase = name.split(__snake_case )[0].split('''.''' )[-2] _UpperCamelCase = mapped_key.replace('''*''' , __snake_case ) if "weight_g" in name: _UpperCamelCase = '''weight_g''' elif "weight_v" in name: _UpperCamelCase = '''weight_v''' elif "bias" in name: _UpperCamelCase = '''bias''' elif "weight" in name: _UpperCamelCase = '''weight''' else: _UpperCamelCase = None set_recursively(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) continue if not is_used: unused_weights.append(__snake_case ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = full_name.split('''conv_layers.''' )[-1] _UpperCamelCase = name.split('''.''' ) _UpperCamelCase = int(items[0] ) _UpperCamelCase = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__snake_case ) def _snake_case ( __snake_case ): _UpperCamelCase , _UpperCamelCase = emb.weight.shape _UpperCamelCase = nn.Linear(__snake_case , __snake_case , bias=__snake_case ) _UpperCamelCase = emb.weight.data return lin_layer def _snake_case ( __snake_case ): with open(__snake_case , '''r''' , encoding='''utf-8''' ) as f: _UpperCamelCase = f.readlines() _UpperCamelCase = [line.split(''' ''' )[0] for line in lines] _UpperCamelCase = len(__snake_case ) _UpperCamelCase = { '''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3, } vocab_dict.update(dict(zip(__snake_case , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ): _UpperCamelCase = WavaVecaConfig.from_pretrained(__snake_case ) _UpperCamelCase = SpeechaTextaConfig.from_pretrained( __snake_case , vocab_size=__snake_case , decoder_layers=__snake_case , do_stable_layer_norm=__snake_case ) _UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=__snake_case , return_attention_mask=__snake_case , ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) _UpperCamelCase = model[0].eval() # set weights for wav2vec2 encoder _UpperCamelCase = WavaVecaModel(__snake_case ) _UpperCamelCase = recursively_load_weights_wavaveca(model.encoder , __snake_case ) _UpperCamelCase = SpeechaTextaForCausalLM(__snake_case ) _UpperCamelCase , _UpperCamelCase = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__snake_case ) # set output linear layer unexpected_keys.remove('''embed_out''' ) _UpperCamelCase = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) _UpperCamelCase = SpeechEncoderDecoderModel(encoder=__snake_case , decoder=__snake_case ) _UpperCamelCase = False # add projection layer _UpperCamelCase = nn.Parameter(projection_layer.weight ) _UpperCamelCase = nn.Parameter(projection_layer.bias ) _UpperCamelCase = create_vocab_dict(__snake_case ) with open(os.path.join(__snake_case , '''vocab.json''' ) , '''w''' ) as fp: json.dump(__snake_case , __snake_case ) _UpperCamelCase = SpeechaTextaTokenizer(os.path.join(__snake_case , '''vocab.json''' ) ) tokenizer.save_pretrained(__snake_case ) _UpperCamelCase = hf_wavavec.config.to_dict() _UpperCamelCase = tokenizer.pad_token_id _UpperCamelCase = tokenizer.bos_token_id _UpperCamelCase = tokenizer.eos_token_id _UpperCamelCase = '''speech_to_text_2''' _UpperCamelCase = '''wav2vec2''' _UpperCamelCase = SpeechEncoderDecoderConfig.from_dict(__snake_case ) hf_wavavec.save_pretrained(__snake_case ) feature_extractor.save_pretrained(__snake_case ) if __name__ == "__main__": _lowerCAmelCase = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10_224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") _lowerCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
71
1
def _snake_case ( __snake_case , __snake_case , __snake_case ): _UpperCamelCase = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def _snake_case ( ): print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
71
from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class lowerCAmelCase_ : def __init__( self : Optional[Any] , _A : Optional[Any] , _A : List[str]=13 , _A : Union[str, Any]=7 , _A : int=True , _A : Optional[int]=True , _A : Optional[int]=True , _A : Union[str, Any]=True , _A : Optional[int]=99 , _A : Union[str, Any]=32 , _A : Dict=2 , _A : List[Any]=4 , _A : Optional[Any]=37 , _A : int="gelu" , _A : Optional[int]=0.1 , _A : str=0.1 , _A : List[str]=512 , _A : Optional[Any]=16 , _A : Optional[Any]=2 , _A : Optional[int]=0.02 , _A : str=False , _A : int=True , _A : Any="None" , _A : Dict=3 , _A : List[Any]=4 , _A : Optional[Any]=None , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_mask _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_labels _UpperCamelCase = num_choices _UpperCamelCase = relative_attention _UpperCamelCase = position_biased_input _UpperCamelCase = pos_att_type _UpperCamelCase = scope def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = None if self.use_input_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None if self.use_labels: _UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCamelCase = DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=_A , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self : Dict , _A : Tuple , _A : Tuple , _A : Union[str, Any] , _A : List[str] , _A : Optional[int] , _A : int , _A : Optional[Any] ): _UpperCamelCase = TFDebertaVaModel(config=_A ) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = [input_ids, input_mask] _UpperCamelCase = model(_A ) _UpperCamelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Dict , _A : Optional[int] , _A : Any , _A : Dict , _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any] , _A : List[str] ): _UpperCamelCase = TFDebertaVaForMaskedLM(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self : Dict , _A : Dict , _A : List[str] , _A : List[Any] , _A : List[Any] , _A : Optional[Any] , _A : Tuple , _A : int ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForSequenceClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple , _A : Dict , _A : Optional[int] , _A : Any , _A : List[Any] , _A : Dict , _A : Union[str, Any] , _A : List[str] ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForTokenClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Dict , _A : Optional[Any] , _A : Optional[int] , _A : Any , _A : List[str] , _A : str , _A : Optional[int] , _A : str ): _UpperCamelCase = TFDebertaVaForQuestionAnswering(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_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 UpperCamelCase_ ( self : Any ): _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( __lowercase, __lowercase, unittest.TestCase ): UpperCAmelCase = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) UpperCAmelCase = ( { "feature-extraction": TFDebertaVaModel, "fill-mask": TFDebertaVaForMaskedLM, "question-answering": TFDebertaVaForQuestionAnswering, "text-classification": TFDebertaVaForSequenceClassification, "token-classification": TFDebertaVaForTokenClassification, "zero-shot": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase = False UpperCAmelCase = False def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = TFDebertaVaModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_A ) @slow def UpperCamelCase_ ( self : Any ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) self.assertIsNotNone(_A ) @require_tf class lowerCAmelCase_ ( unittest.TestCase ): @unittest.skip(reason='''Model not available yet''' ) def UpperCamelCase_ ( self : List[Any] ): pass @slow def UpperCamelCase_ ( self : int ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) _UpperCamelCase = tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) _UpperCamelCase = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) _UpperCamelCase = model(_A , attention_mask=_A )[0] _UpperCamelCase = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , _A , atol=1e-4 )
71
1
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _lowerCAmelCase = 16 _lowerCAmelCase = 32 def _snake_case ( __snake_case , __snake_case = 16 ): _UpperCamelCase = AutoTokenizer.from_pretrained('''bert-base-cased''' ) _UpperCamelCase = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__snake_case ): # max_length=None => use the model max length (it's actually the default) _UpperCamelCase = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__snake_case , max_length=__snake_case ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _UpperCamelCase = datasets.map( __snake_case , batched=__snake_case , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _UpperCamelCase = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(__snake_case ): # On TPU it's best to pad everything to the same length or training will be very slow. _UpperCamelCase = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _UpperCamelCase = 16 elif accelerator.mixed_precision != "no": _UpperCamelCase = 8 else: _UpperCamelCase = None return tokenizer.pad( __snake_case , padding='''longest''' , max_length=__snake_case , pad_to_multiple_of=__snake_case , return_tensors='''pt''' , ) # Instantiate dataloaders. _UpperCamelCase = DataLoader( tokenized_datasets['''train'''] , shuffle=__snake_case , collate_fn=__snake_case , batch_size=__snake_case ) _UpperCamelCase = DataLoader( tokenized_datasets['''validation'''] , shuffle=__snake_case , collate_fn=__snake_case , batch_size=__snake_case ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders _lowerCAmelCase = mocked_dataloaders # noqa: F811 def _snake_case ( __snake_case , __snake_case ): # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , __snake_case ) == "1": _UpperCamelCase = 2 # Initialize accelerator _UpperCamelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _UpperCamelCase = config['''lr'''] _UpperCamelCase = int(config['''num_epochs'''] ) _UpperCamelCase = int(config['''seed'''] ) _UpperCamelCase = int(config['''batch_size'''] ) _UpperCamelCase = evaluate.load('''glue''' , '''mrpc''' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=__snake_case ) def inner_training_loop(__snake_case ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(__snake_case ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _UpperCamelCase = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=__snake_case ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _UpperCamelCase = model.to(accelerator.device ) # Instantiate optimizer _UpperCamelCase = AdamW(params=model.parameters() , lr=__snake_case ) _UpperCamelCase , _UpperCamelCase = get_dataloaders(__snake_case , __snake_case ) # Instantiate scheduler _UpperCamelCase = get_linear_schedule_with_warmup( optimizer=__snake_case , num_warmup_steps=100 , num_training_steps=(len(__snake_case ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = accelerator.prepare( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) # Now we train the model for epoch in range(__snake_case ): model.train() for step, batch in enumerate(__snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _UpperCamelCase = model(**__snake_case ) _UpperCamelCase = outputs.loss accelerator.backward(__snake_case ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _UpperCamelCase = model(**__snake_case ) _UpperCamelCase = outputs.logits.argmax(dim=-1 ) _UpperCamelCase , _UpperCamelCase = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=__snake_case , references=__snake_case , ) _UpperCamelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __snake_case ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def _snake_case ( ): _UpperCamelCase = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=__snake_case , default=__snake_case , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) _UpperCamelCase = parser.parse_args() _UpperCamelCase = {'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(__snake_case , __snake_case ) if __name__ == "__main__": main()
71
def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case ): # Return True if there is node that has not iterated. _UpperCamelCase = [False] * len(__snake_case ) _UpperCamelCase = [] queue.append(__snake_case ) _UpperCamelCase = True while queue: _UpperCamelCase = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(__snake_case ) _UpperCamelCase = True _UpperCamelCase = u return visited[t] def _snake_case ( __snake_case , __snake_case , __snake_case ): # This array is filled by BFS and to store path _UpperCamelCase = [-1] * (len(__snake_case )) _UpperCamelCase = 0 while bfs(__snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = float('''Inf''' ) _UpperCamelCase = sink while s != source: # Find the minimum value in select path _UpperCamelCase = min(__snake_case , graph[parent[s]][s] ) _UpperCamelCase = parent[s] max_flow += path_flow _UpperCamelCase = sink while v != source: _UpperCamelCase = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow _UpperCamelCase = parent[v] return max_flow _lowerCAmelCase = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] _lowerCAmelCase, _lowerCAmelCase = 0, 5 print(ford_fulkerson(graph, source, sink))
71
1
import re def _snake_case ( __snake_case ): _UpperCamelCase = re.compile(R'''^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$''' ) if match := re.search(__snake_case , __snake_case ): return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator("+918827897895"))
71
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _lowerCAmelCase = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
1
import argparse import intel_extension_for_pytorch as ipex import torch from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline _lowerCAmelCase = argparse.ArgumentParser("Stable Diffusion script with intel optimization", add_help=False) parser.add_argument("--dpm", action="store_true", help="Enable DPMSolver or not") parser.add_argument("--steps", default=None, type=int, help="Num inference steps") _lowerCAmelCase = parser.parse_args() _lowerCAmelCase = "cpu" _lowerCAmelCase = "a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings" _lowerCAmelCase = "path-to-your-trained-model" _lowerCAmelCase = StableDiffusionPipeline.from_pretrained(model_id) if args.dpm: _lowerCAmelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) _lowerCAmelCase = pipe.to(device) # to channels last _lowerCAmelCase = pipe.unet.to(memory_format=torch.channels_last) _lowerCAmelCase = pipe.vae.to(memory_format=torch.channels_last) _lowerCAmelCase = pipe.text_encoder.to(memory_format=torch.channels_last) if pipe.requires_safety_checker: _lowerCAmelCase = pipe.safety_checker.to(memory_format=torch.channels_last) # optimize with ipex _lowerCAmelCase = torch.randn(2, 4, 64, 64) _lowerCAmelCase = torch.rand(1) * 999 _lowerCAmelCase = torch.randn(2, 77, 768) _lowerCAmelCase = (sample, timestep, encoder_hidden_status) try: _lowerCAmelCase = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example) except Exception: _lowerCAmelCase = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True) _lowerCAmelCase = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True) _lowerCAmelCase = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True) if pipe.requires_safety_checker: _lowerCAmelCase = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True) # compute _lowerCAmelCase = 666 _lowerCAmelCase = torch.Generator(device).manual_seed(seed) _lowerCAmelCase = {"generator": generator} if args.steps is not None: _lowerCAmelCase = args.steps with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa): _lowerCAmelCase = pipe(prompt, **generate_kwargs).images[0] # save image image.save("generated.png")
71
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Any ): _UpperCamelCase = tempfile.mkdtemp() # fmt: off _UpperCamelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on _UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) _UpperCamelCase = { '''do_resize''': True, '''size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } _UpperCamelCase = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_A , _A ) def UpperCamelCase_ ( self : Tuple , **_A : Optional[Any] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : List[Any] , **_A : Union[str, Any] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : int ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _UpperCamelCase = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = self.get_image_processor() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _UpperCamelCase = self.get_image_processor(do_normalize=_A , padding_value=1.0 ) _UpperCamelCase = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = image_processor(_A , return_tensors='''np''' ) _UpperCamelCase = processor(images=_A , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = processor(text=_A ) _UpperCamelCase = tokenizer(_A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_A ): processor() def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _UpperCamelCase = processor.batch_decode(_A ) _UpperCamelCase = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A ) def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
71
1
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class lowerCAmelCase_ ( __lowercase, unittest.TestCase ): UpperCAmelCase = VideoToVideoSDPipeline UpperCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} UpperCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} UpperCAmelCase = PipelineTesterMixin.required_optional_params - {"latents"} UpperCAmelCase = False # No `output_type`. UpperCAmelCase = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def UpperCamelCase_ ( self : Union[str, Any] ): torch.manual_seed(0 ) _UpperCamelCase = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''') , up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''') , cross_attention_dim=32 , attention_head_dim=4 , ) _UpperCamelCase = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=_A , set_alpha_to_one=_A , ) torch.manual_seed(0 ) _UpperCamelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) _UpperCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='''gelu''' , projection_dim=512 , ) _UpperCamelCase = CLIPTextModel(_A ) _UpperCamelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) _UpperCamelCase = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, } return components def UpperCamelCase_ ( self : List[str] , _A : Any , _A : str=0 ): # 3 frames _UpperCamelCase = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(_A ) ).to(_A ) if str(_A ).startswith('''mps''' ): _UpperCamelCase = torch.manual_seed(_A ) else: _UpperCamelCase = torch.Generator(device=_A ).manual_seed(_A ) _UpperCamelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''video''': video, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''pt''', } return inputs def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = VideoToVideoSDPipeline(**_A ) _UpperCamelCase = sd_pipe.to(_A ) sd_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = '''np''' _UpperCamelCase = sd_pipe(**_A ).frames _UpperCamelCase = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) _UpperCamelCase = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def UpperCamelCase_ ( self : Optional[Any] ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=_A , expected_max_diff=5e-3 ) @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def UpperCamelCase_ ( self : List[Any] ): pass @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' ) def UpperCamelCase_ ( self : int ): pass @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''' ) def UpperCamelCase_ ( self : List[str] ): pass def UpperCamelCase_ ( self : List[str] ): return super().test_progress_bar() @slow @skip_mps class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = VideoToVideoSDPipeline.from_pretrained('''cerspense/zeroscope_v2_XL''' , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames _UpperCamelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) _UpperCamelCase = torch.randn((1, 10, 3, 1024, 576) , generator=_A ) _UpperCamelCase = video.to('''cuda''' ) _UpperCamelCase = '''Spiderman is surfing''' _UpperCamelCase = pipe(_A , video=_A , generator=_A , num_inference_steps=3 , output_type='''pt''' ).frames _UpperCamelCase = np.array([-1.045_8984, -1.127_9297, -0.966_3086, -0.9150_3906, -0.7509_7656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
71
def _snake_case ( __snake_case , __snake_case , __snake_case ): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__snake_case , n - 1 , __snake_case ) * a) % mod else: _UpperCamelCase = binary_exponentiation(__snake_case , n / 2 , __snake_case ) return (b * b) % mod # a prime number _lowerCAmelCase = 701 _lowerCAmelCase = 1_000_000_000 _lowerCAmelCase = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
71
1
import baseaa def _snake_case ( __snake_case ): return baseaa.aaaencode(string.encode('''utf-8''' ) ) def _snake_case ( __snake_case ): return baseaa.aaadecode(__snake_case ).decode('''utf-8''' ) if __name__ == "__main__": import doctest doctest.testmod()
71
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = (1 - _cos) / 2 _UpperCamelCase = 1 - _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = (1 + _cos) / 2 _UpperCamelCase = -1 - _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = _sin / 2 _UpperCamelCase = 0 _UpperCamelCase = -ba _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 1 - alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = 1 + alpha * big_a _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha * big_a _UpperCamelCase = 1 + alpha / big_a _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha / big_a _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = (big_a + 1) - (big_a - 1) * _cos _UpperCamelCase = (big_a + 1) + (big_a - 1) * _cos _UpperCamelCase = (big_a - 1) - (big_a + 1) * _cos _UpperCamelCase = (big_a - 1) + (big_a + 1) * _cos _UpperCamelCase = 2 * sqrt(__snake_case ) * alpha _UpperCamelCase = big_a * (pmc + aaa) _UpperCamelCase = 2 * big_a * mpc _UpperCamelCase = big_a * (pmc - aaa) _UpperCamelCase = ppmc + aaa _UpperCamelCase = -2 * pmpc _UpperCamelCase = ppmc - aaa _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = (big_a + 1) - (big_a - 1) * _cos _UpperCamelCase = (big_a + 1) + (big_a - 1) * _cos _UpperCamelCase = (big_a - 1) - (big_a + 1) * _cos _UpperCamelCase = (big_a - 1) + (big_a + 1) * _cos _UpperCamelCase = 2 * sqrt(__snake_case ) * alpha _UpperCamelCase = big_a * (ppmc + aaa) _UpperCamelCase = -2 * big_a * pmpc _UpperCamelCase = big_a * (ppmc - aaa) _UpperCamelCase = pmc + aaa _UpperCamelCase = 2 * mpc _UpperCamelCase = pmc - aaa _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
71
1
from __future__ import annotations from typing import Generic, TypeVar _lowerCAmelCase = TypeVar("T") class lowerCAmelCase_ ( Generic[T] ): def __init__( self : Any , _A : T ): _UpperCamelCase = data _UpperCamelCase = self _UpperCamelCase = 0 class lowerCAmelCase_ ( Generic[T] ): def __init__( self : Optional[int] ): # map from node name to the node object _UpperCamelCase = {} def UpperCamelCase_ ( self : str , _A : T ): # create a new set with x as its member _UpperCamelCase = DisjointSetTreeNode(_A ) def UpperCamelCase_ ( self : List[Any] , _A : T ): # find the set x belongs to (with path-compression) _UpperCamelCase = self.map[data] if elem_ref != elem_ref.parent: _UpperCamelCase = self.find_set(elem_ref.parent.data ) return elem_ref.parent def UpperCamelCase_ ( self : List[Any] , _A : DisjointSetTreeNode[T] , _A : DisjointSetTreeNode[T] ): # helper function for union operation if nodea.rank > nodea.rank: _UpperCamelCase = nodea else: _UpperCamelCase = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def UpperCamelCase_ ( self : List[Any] , _A : T , _A : T ): # merge 2 disjoint sets self.link(self.find_set(_A ) , self.find_set(_A ) ) class lowerCAmelCase_ ( Generic[T] ): def __init__( self : Any ): # connections: map from the node to the neighbouring nodes (with weights) _UpperCamelCase = {} def UpperCamelCase_ ( self : Optional[int] , _A : T ): # add a node ONLY if its not present in the graph if node not in self.connections: _UpperCamelCase = {} def UpperCamelCase_ ( self : Tuple , _A : T , _A : T , _A : int ): # add an edge with the given weight self.add_node(_A ) self.add_node(_A ) _UpperCamelCase = weight _UpperCamelCase = weight def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = [] _UpperCamelCase = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda _A : x[2] ) # creating the disjoint set _UpperCamelCase = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(_A ) # MST generation _UpperCamelCase = 0 _UpperCamelCase = 0 _UpperCamelCase = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = edges[index] index += 1 _UpperCamelCase = disjoint_set.find_set(_A ) _UpperCamelCase = disjoint_set.find_set(_A ) if parent_u != parent_v: num_edges += 1 graph.add_edge(_A , _A , _A ) disjoint_set.union(_A , _A ) return graph
71
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json", # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "gpt_neox" def __init__( self : Union[str, Any] , _A : Union[str, Any]=5_0432 , _A : List[Any]=6144 , _A : int=44 , _A : int=64 , _A : Optional[Any]=2_4576 , _A : Any="gelu" , _A : Tuple=0.25 , _A : Union[str, Any]=1_0000 , _A : Tuple=0.0 , _A : Any=0.0 , _A : int=0.1 , _A : List[str]=2048 , _A : Dict=0.02 , _A : Optional[Any]=1e-5 , _A : Tuple=True , _A : List[Any]=0 , _A : Optional[int]=2 , _A : Optional[int]=False , _A : List[Any]=True , _A : Any=None , **_A : Any , ): super().__init__(bos_token_id=_A , eos_token_id=_A , **_A ) _UpperCamelCase = vocab_size _UpperCamelCase = max_position_embeddings _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = rotary_pct _UpperCamelCase = rotary_emb_base _UpperCamelCase = attention_dropout _UpperCamelCase = hidden_dropout _UpperCamelCase = classifier_dropout _UpperCamelCase = initializer_range _UpperCamelCase = layer_norm_eps _UpperCamelCase = use_cache _UpperCamelCase = tie_word_embeddings _UpperCamelCase = use_parallel_residual _UpperCamelCase = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( '''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' ) def UpperCamelCase_ ( self : str ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _A ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F"""got {self.rope_scaling}""" ) _UpperCamelCase = self.rope_scaling.get('''type''' , _A ) _UpperCamelCase = self.rope_scaling.get('''factor''' , _A ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}""" ) if rope_scaling_factor is None or not isinstance(_A , _A ) or rope_scaling_factor <= 1.0: raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
71
1
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class lowerCAmelCase_ ( unittest.TestCase ): def __init__( self : Optional[int] , _A : Tuple , _A : Any=13 , _A : Union[str, Any]=7 , _A : int=True , _A : Optional[int]=True , _A : Optional[Any]=True , _A : Dict=True , _A : List[str]=99 , _A : List[str]=32 , _A : Optional[Any]=5 , _A : Optional[Any]=4 , _A : List[str]=37 , _A : List[str]="gelu" , _A : Any=0.1 , _A : int=0.1 , _A : Optional[Any]=512 , _A : int=16 , _A : List[str]=2 , _A : Optional[int]=0.02 , _A : Optional[Any]=4 , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_attention_mask _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_choices def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = None if self.use_attention_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCamelCase = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCamelCase_ ( self : str ): _UpperCamelCase = self.prepare_config_and_inputs() _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = self.prepare_config_and_inputs() _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = config_and_inputs _UpperCamelCase = True _UpperCamelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class lowerCAmelCase_ ( __lowercase, unittest.TestCase ): UpperCAmelCase = True UpperCAmelCase = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase_ ( self : str ): _UpperCamelCase = FlaxRobertaModelTester(self ) @slow def UpperCamelCase_ ( self : str ): for model_class_name in self.all_model_classes: _UpperCamelCase = model_class_name.from_pretrained('''roberta-base''' , from_pt=_A ) _UpperCamelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(_A )
71
from ..utils import DummyObject, requires_backends class lowerCAmelCase_ ( metaclass=__lowercase ): UpperCAmelCase = ["keras_nlp"] def __init__( self : Any , *_A : Dict , **_A : List[str] ): requires_backends(self , ['''keras_nlp'''] )
71
1
def _snake_case ( __snake_case = 4000000 ): _UpperCamelCase = [0, 1] _UpperCamelCase = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 _UpperCamelCase = 0 for j in range(len(__snake_case ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f'{solution() = }')
71
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig _lowerCAmelCase = logging.get_logger(__name__) # General docstring _lowerCAmelCase = "RegNetConfig" # Base docstring _lowerCAmelCase = "facebook/regnet-y-040" _lowerCAmelCase = [1, 1_088, 7, 7] # Image classification docstring _lowerCAmelCase = "facebook/regnet-y-040" _lowerCAmelCase = "tabby, tabby cat" _lowerCAmelCase = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : str , _A : int , _A : int = 3 , _A : int = 1 , _A : int = 1 , _A : Optional[str] = "relu" , **_A : Any , ): super().__init__(**_A ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb _UpperCamelCase = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) _UpperCamelCase = tf.keras.layers.ConvaD( filters=_A , kernel_size=_A , strides=_A , padding='''VALID''' , groups=_A , use_bias=_A , name='''convolution''' , ) _UpperCamelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) _UpperCamelCase = ACTaFN[activation] if activation is not None else tf.identity def UpperCamelCase_ ( self : Any , _A : Any ): _UpperCamelCase = self.convolution(self.padding(_A ) ) _UpperCamelCase = self.normalization(_A ) _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] , _A : RegNetConfig , **_A : Any ): super().__init__(**_A ) _UpperCamelCase = config.num_channels _UpperCamelCase = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='''embedder''' , ) def UpperCamelCase_ ( self : List[str] , _A : Optional[int] ): _UpperCamelCase = shape_list(_A )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) _UpperCamelCase = tf.transpose(_A , perm=(0, 2, 3, 1) ) _UpperCamelCase = self.embedder(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : str , _A : int , _A : int = 2 , **_A : Optional[Any] ): super().__init__(**_A ) _UpperCamelCase = tf.keras.layers.ConvaD( filters=_A , kernel_size=1 , strides=_A , use_bias=_A , name='''convolution''' ) _UpperCamelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) def UpperCamelCase_ ( self : str , _A : tf.Tensor , _A : bool = False ): return self.normalization(self.convolution(_A ) , training=_A ) class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Dict , _A : int , _A : int , **_A : Dict ): super().__init__(**_A ) _UpperCamelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_A , name='''pooler''' ) _UpperCamelCase = [ tf.keras.layers.ConvaD(filters=_A , kernel_size=1 , activation='''relu''' , name='''attention.0''' ), tf.keras.layers.ConvaD(filters=_A , kernel_size=1 , activation='''sigmoid''' , name='''attention.2''' ), ] def UpperCamelCase_ ( self : List[str] , _A : List[Any] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] _UpperCamelCase = self.pooler(_A ) for layer_module in self.attention: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = hidden_state * pooled return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , _A : int , _A : int , _A : int = 1 , **_A : str ): super().__init__(**_A ) _UpperCamelCase = in_channels != out_channels or stride != 1 _UpperCamelCase = max(1 , out_channels // config.groups_width ) _UpperCamelCase = ( TFRegNetShortCut(_A , stride=_A , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. _UpperCamelCase = [ TFRegNetConvLayer(_A , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( _A , stride=_A , groups=_A , activation=config.hidden_act , name='''layer.1''' ), TFRegNetConvLayer(_A , kernel_size=1 , activation=_A , name='''layer.2''' ), ] _UpperCamelCase = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Dict , _A : Tuple ): _UpperCamelCase = hidden_state for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = self.shortcut(_A ) hidden_state += residual _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , _A : int , _A : int , _A : int = 1 , **_A : int ): super().__init__(**_A ) _UpperCamelCase = in_channels != out_channels or stride != 1 _UpperCamelCase = max(1 , out_channels // config.groups_width ) _UpperCamelCase = ( TFRegNetShortCut(_A , stride=_A , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) _UpperCamelCase = [ TFRegNetConvLayer(_A , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( _A , stride=_A , groups=_A , activation=config.hidden_act , name='''layer.1''' ), TFRegNetSELayer(_A , reduced_channels=int(round(in_channels / 4 ) ) , name='''layer.2''' ), TFRegNetConvLayer(_A , kernel_size=1 , activation=_A , name='''layer.3''' ), ] _UpperCamelCase = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Tuple , _A : List[Any] ): _UpperCamelCase = hidden_state for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = self.shortcut(_A ) hidden_state += residual _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Tuple , _A : RegNetConfig , _A : int , _A : int , _A : int = 2 , _A : int = 2 , **_A : Union[str, Any] ): super().__init__(**_A ) _UpperCamelCase = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer _UpperCamelCase = [ # downsampling is done in the first layer with stride of 2 layer(_A , _A , _A , stride=_A , name='''layers.0''' ), *[layer(_A , _A , _A , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCamelCase_ ( self : Union[str, Any] , _A : Optional[int] ): for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , **_A : List[str] ): super().__init__(**_A ) _UpperCamelCase = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( _A , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='''stages.0''' , ) ) _UpperCamelCase = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(_A , config.depths[1:] ) ): self.stages.append(TFRegNetStage(_A , _A , _A , depth=_A , name=F"""stages.{i+1}""" ) ) def UpperCamelCase_ ( self : Optional[int] , _A : tf.Tensor , _A : bool = False , _A : bool = True ): _UpperCamelCase = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _UpperCamelCase = hidden_states + (hidden_state,) _UpperCamelCase = stage_module(_A ) if output_hidden_states: _UpperCamelCase = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=_A , hidden_states=_A ) @keras_serializable class lowerCAmelCase_ ( tf.keras.layers.Layer ): UpperCAmelCase = RegNetConfig def __init__( self : int , _A : Tuple , **_A : int ): super().__init__(**_A ) _UpperCamelCase = config _UpperCamelCase = TFRegNetEmbeddings(_A , name='''embedder''' ) _UpperCamelCase = TFRegNetEncoder(_A , name='''encoder''' ) _UpperCamelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_A , name='''pooler''' ) @unpack_inputs def UpperCamelCase_ ( self : Optional[int] , _A : tf.Tensor , _A : Optional[bool] = None , _A : Optional[bool] = None , _A : bool = False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.embedder(_A , training=_A ) _UpperCamelCase = self.encoder( _A , output_hidden_states=_A , return_dict=_A , training=_A ) _UpperCamelCase = encoder_outputs[0] _UpperCamelCase = self.pooler(_A ) # Change to NCHW output format have uniformity in the modules _UpperCamelCase = tf.transpose(_A , perm=(0, 3, 1, 2) ) _UpperCamelCase = tf.transpose(_A , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: _UpperCamelCase = tuple([tf.transpose(_A , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_A , pooler_output=_A , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = RegNetConfig UpperCAmelCase = "regnet" UpperCAmelCase = "pixel_values" @property def UpperCamelCase_ ( self : Tuple ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} _lowerCAmelCase = r"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n" _lowerCAmelCase = r"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top.", __lowercase, ) class lowerCAmelCase_ ( __lowercase ): def __init__( self : List[Any] , _A : RegNetConfig , *_A : Optional[int] , **_A : Tuple ): super().__init__(_A , *_A , **_A ) _UpperCamelCase = TFRegNetMainLayer(_A , name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(_A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_A , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCamelCase_ ( self : Any , _A : tf.Tensor , _A : Optional[bool] = None , _A : Optional[bool] = None , _A : Optional[int]=False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.regnet( pixel_values=_A , output_hidden_states=_A , return_dict=_A , training=_A , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ", __lowercase, ) class lowerCAmelCase_ ( __lowercase, __lowercase ): def __init__( self : List[Any] , _A : RegNetConfig , *_A : Any , **_A : int ): super().__init__(_A , *_A , **_A ) _UpperCamelCase = config.num_labels _UpperCamelCase = TFRegNetMainLayer(_A , name='''regnet''' ) # classification head _UpperCamelCase = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(_A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCamelCase_ ( self : str , _A : tf.Tensor = None , _A : tf.Tensor = None , _A : bool = None , _A : bool = None , _A : Any=False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.regnet( _A , output_hidden_states=_A , return_dict=_A , training=_A ) _UpperCamelCase = outputs.pooler_output if return_dict else outputs[1] _UpperCamelCase = self.classifier[0](_A ) _UpperCamelCase = self.classifier[1](_A ) _UpperCamelCase = None if labels is None else self.hf_compute_loss(labels=_A , logits=_A ) if not return_dict: _UpperCamelCase = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=_A , logits=_A , hidden_states=outputs.hidden_states )
71
1
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 _lowerCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def _snake_case ( __snake_case ): warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''' , __snake_case , ) if isinstance(__snake_case , torch.Tensor ): return image elif isinstance(__snake_case , PIL.Image.Image ): _UpperCamelCase = [image] if isinstance(image[0] , PIL.Image.Image ): _UpperCamelCase , _UpperCamelCase = image[0].size _UpperCamelCase , _UpperCamelCase = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 _UpperCamelCase = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] _UpperCamelCase = np.concatenate(__snake_case , axis=0 ) _UpperCamelCase = np.array(__snake_case ).astype(np.floataa ) / 255.0 _UpperCamelCase = image.transpose(0 , 3 , 1 , 2 ) _UpperCamelCase = 2.0 * image - 1.0 _UpperCamelCase = torch.from_numpy(__snake_case ) elif isinstance(image[0] , torch.Tensor ): _UpperCamelCase = torch.cat(__snake_case , dim=0 ) return image def _snake_case ( __snake_case ): if isinstance(__snake_case , torch.Tensor ): return mask elif isinstance(__snake_case , PIL.Image.Image ): _UpperCamelCase = [mask] if isinstance(mask[0] , PIL.Image.Image ): _UpperCamelCase , _UpperCamelCase = mask[0].size _UpperCamelCase , _UpperCamelCase = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 _UpperCamelCase = [np.array(m.convert('''L''' ).resize((w, h) , resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] _UpperCamelCase = np.concatenate(__snake_case , axis=0 ) _UpperCamelCase = mask.astype(np.floataa ) / 255.0 _UpperCamelCase = 0 _UpperCamelCase = 1 _UpperCamelCase = torch.from_numpy(__snake_case ) elif isinstance(mask[0] , torch.Tensor ): _UpperCamelCase = torch.cat(__snake_case , dim=0 ) return mask class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = 42 UpperCAmelCase = 42 def __init__( self : Dict , _A : List[str] , _A : List[str] ): super().__init__() self.register_modules(unet=_A , scheduler=_A ) @torch.no_grad() def __call__( self : List[str] , _A : Union[torch.Tensor, PIL.Image.Image] , _A : Union[torch.Tensor, PIL.Image.Image] , _A : int = 250 , _A : float = 0.0 , _A : int = 10 , _A : int = 10 , _A : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _A : Optional[str] = "pil" , _A : bool = True , ): _UpperCamelCase = image _UpperCamelCase = _preprocess_image(_A ) _UpperCamelCase = original_image.to(device=self.device , dtype=self.unet.dtype ) _UpperCamelCase = _preprocess_mask(_A ) _UpperCamelCase = mask_image.to(device=self.device , dtype=self.unet.dtype ) _UpperCamelCase = 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.""" ) _UpperCamelCase = original_image.shape _UpperCamelCase = randn_tensor(_A , generator=_A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(_A , _A , _A , self.device ) _UpperCamelCase = eta _UpperCamelCase = self.scheduler.timesteps[0] + 1 _UpperCamelCase = 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 _UpperCamelCase = self.unet(_A , _A ).sample # compute previous image: x_t -> x_t-1 _UpperCamelCase = self.scheduler.step(_A , _A , _A , _A , _A , _A ).prev_sample else: # compute the reverse: x_t-1 -> x_t _UpperCamelCase = self.scheduler.undo_step(_A , _A , _A ) _UpperCamelCase = t _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,) return ImagePipelineOutput(images=_A )
71
from sklearn.metrics import mean_squared_error import datasets _lowerCAmelCase = "\\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" _lowerCAmelCase = "\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n" _lowerCAmelCase = "\nArgs:\n predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n sample_weight: array-like of shape (n_samples,), default=None\n Sample weights.\n multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"\n Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n \"raw_values\" : Returns a full set of errors in case of multioutput input.\n\n \"uniform_average\" : Errors of all outputs are averaged with uniform weight.\n\n squared : bool, default=True\n If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n mse : mean squared error.\nExamples:\n\n >>> mse_metric = datasets.load_metric(\"mse\")\n >>> predictions = [2.5, 0.0, 2, 8]\n >>> references = [3, -0.5, 2, 7]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'mse': 0.375}\n >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n >>> print(rmse_result)\n {'mse': 0.6123724356957945}\n\n If you're using multi-dimensional lists, then set the config as follows :\n\n >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")\n >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n >>> references = [[0, 2], [-1, 2], [8, -5]]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'mse': 0.7083333333333334}\n >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {'mse': array([0.41666667, 1. ])}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): def UpperCamelCase_ ( self : Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html''' ] , ) def UpperCamelCase_ ( self : Dict ): if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value('''float''' ) ), "references": datasets.Sequence(datasets.Value('''float''' ) ), } else: return { "predictions": datasets.Value('''float''' ), "references": datasets.Value('''float''' ), } def UpperCamelCase_ ( self : Any , _A : List[Any] , _A : List[str] , _A : Dict=None , _A : List[str]="uniform_average" , _A : int=True ): _UpperCamelCase = mean_squared_error( _A , _A , sample_weight=_A , multioutput=_A , squared=_A ) return {"mse": mse}
71
1
from __future__ import annotations import typing from collections import Counter def _snake_case ( __snake_case ): _UpperCamelCase = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(__snake_case , max_perimeter + 1 ): _UpperCamelCase = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__snake_case ): _UpperCamelCase = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _snake_case ( __snake_case = 1000 ): _UpperCamelCase = pythagorean_triple(__snake_case ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'Perimeter {solution()} has maximum solutions')
71
import os import re import shutil import sys import tempfile import unittest import black _lowerCAmelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. _lowerCAmelCase = " \"\"\"\n Output class for the scheduler's step function output.\n\n Args:\n prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the\n denoising loop.\n pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n The predicted denoised sample (x_{0}) based on the model output from the current timestep.\n `pred_original_sample` can be used to preview progress or for guidance.\n \"\"\"\n\n prev_sample: torch.FloatTensor\n pred_original_sample: Optional[torch.FloatTensor] = None\n" class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Any ): _UpperCamelCase = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , '''schedulers/''' ) ) _UpperCamelCase = self.diffusers_dir shutil.copy( os.path.join(_A , '''src/diffusers/schedulers/scheduling_ddpm.py''' ) , os.path.join(self.diffusers_dir , '''schedulers/scheduling_ddpm.py''' ) , ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = '''src/diffusers''' shutil.rmtree(self.diffusers_dir ) def UpperCamelCase_ ( self : Union[str, Any] , _A : Tuple , _A : Optional[Any] , _A : Dict , _A : List[str]=None ): _UpperCamelCase = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: _UpperCamelCase = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result _UpperCamelCase = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) _UpperCamelCase = black.format_str(_A , mode=_A ) _UpperCamelCase = os.path.join(self.diffusers_dir , '''new_code.py''' ) with open(_A , '''w''' , newline='''\n''' ) as f: f.write(_A ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(_A ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=_A ) with open(_A , '''r''' ) as f: self.assertTrue(f.read() , _A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = check_copies.find_code_in_diffusers('''schedulers.scheduling_ddpm.DDPMSchedulerOutput''' ) self.assertEqual(_A , _A ) def UpperCamelCase_ ( self : Optional[Any] ): # Base copy consistency self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , REFERENCE_CODE + '''\n''' , ) # With no empty line at the end self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , _A , ) # Copy consistency with rename self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , re.sub('''DDPM''' , '''Test''' , _A ) , ) # Copy consistency with a really long name _UpperCamelCase = '''TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason''' self.check_copy_consistency( F"""# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}""" , F"""{long_class_name}SchedulerOutput""" , re.sub('''Bert''' , _A , _A ) , ) # Copy consistency with overwrite self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , _A , overwrite_result=re.sub('''DDPM''' , '''Test''' , _A ) , )
71
1
from collections.abc import Callable class lowerCAmelCase_ : def __init__( self : Optional[int] , _A : Callable | None = None ): # Stores actual heap items. _UpperCamelCase = [] # Stores indexes of each item for supporting updates and deletion. _UpperCamelCase = {} # Stores current size of heap. _UpperCamelCase = 0 # Stores function used to evaluate the score of an item on which basis ordering # will be done. _UpperCamelCase = key or (lambda _A : x) def UpperCamelCase_ ( self : Union[str, Any] , _A : int ): return int((i - 1) / 2 ) if i > 0 else None def UpperCamelCase_ ( self : List[str] , _A : int ): _UpperCamelCase = int(2 * i + 1 ) return left if 0 < left < self.size else None def UpperCamelCase_ ( self : Dict , _A : int ): _UpperCamelCase = int(2 * i + 2 ) return right if 0 < right < self.size else None def UpperCamelCase_ ( self : Tuple , _A : int , _A : int ): _UpperCamelCase , _UpperCamelCase = ( self.pos_map[self.arr[j][0]], self.pos_map[self.arr[i][0]], ) # Then swap the items in the list. _UpperCamelCase , _UpperCamelCase = self.arr[j], self.arr[i] def UpperCamelCase_ ( self : str , _A : int , _A : int ): return self.arr[i][1] < self.arr[j][1] def UpperCamelCase_ ( self : List[Any] , _A : int ): _UpperCamelCase = self._left(_A ) _UpperCamelCase = self._right(_A ) _UpperCamelCase = i if left is not None and not self._cmp(_A , _A ): _UpperCamelCase = left if right is not None and not self._cmp(_A , _A ): _UpperCamelCase = right return valid_parent def UpperCamelCase_ ( self : Optional[int] , _A : int ): _UpperCamelCase = self._parent(_A ) while parent is not None and not self._cmp(_A , _A ): self._swap(_A , _A ) _UpperCamelCase , _UpperCamelCase = parent, self._parent(_A ) def UpperCamelCase_ ( self : List[Any] , _A : int ): _UpperCamelCase = self._get_valid_parent(_A ) while valid_parent != index: self._swap(_A , _A ) _UpperCamelCase , _UpperCamelCase = valid_parent, self._get_valid_parent(_A ) def UpperCamelCase_ ( self : str , _A : int , _A : int ): if item not in self.pos_map: return _UpperCamelCase = self.pos_map[item] _UpperCamelCase = [item, self.key(_A )] # Make sure heap is right in both up and down direction. # Ideally only one of them will make any change. self._heapify_up(_A ) self._heapify_down(_A ) def UpperCamelCase_ ( self : Optional[Any] , _A : int ): if item not in self.pos_map: return _UpperCamelCase = self.pos_map[item] del self.pos_map[item] _UpperCamelCase = self.arr[self.size - 1] _UpperCamelCase = index self.size -= 1 # Make sure heap is right in both up and down direction. Ideally only one # of them will make any change- so no performance loss in calling both. if self.size > index: self._heapify_up(_A ) self._heapify_down(_A ) def UpperCamelCase_ ( self : List[Any] , _A : int , _A : int ): _UpperCamelCase = len(self.arr ) if arr_len == self.size: self.arr.append([item, self.key(_A )] ) else: _UpperCamelCase = [item, self.key(_A )] _UpperCamelCase = self.size self.size += 1 self._heapify_up(self.size - 1 ) def UpperCamelCase_ ( self : str ): return self.arr[0] if self.size else None def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.get_top() if top_item_tuple: self.delete_item(top_item_tuple[0] ) return top_item_tuple def _snake_case ( ): pass if __name__ == "__main__": import doctest doctest.testmod()
71
from __future__ import annotations import math class lowerCAmelCase_ : def __init__( self : int , _A : int ): _UpperCamelCase = size # approximate the overall size of segment tree with given value _UpperCamelCase = [0 for i in range(0 , 4 * size )] # create array to store lazy update _UpperCamelCase = [0 for i in range(0 , 4 * size )] _UpperCamelCase = [0 for i in range(0 , 4 * size )] # flag for lazy update def UpperCamelCase_ ( self : str , _A : int ): return idx * 2 def UpperCamelCase_ ( self : Any , _A : int ): return idx * 2 + 1 def UpperCamelCase_ ( self : Union[str, Any] , _A : int , _A : int , _A : int , _A : list[int] ): if left_element == right_element: _UpperCamelCase = a[left_element - 1] else: _UpperCamelCase = (left_element + right_element) // 2 self.build(self.left(_A ) , _A , _A , _A ) self.build(self.right(_A ) , mid + 1 , _A , _A ) _UpperCamelCase = max( self.segment_tree[self.left(_A )] , self.segment_tree[self.right(_A )] ) def UpperCamelCase_ ( self : Tuple , _A : int , _A : int , _A : int , _A : int , _A : int , _A : int ): if self.flag[idx] is True: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = False if left_element != right_element: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = self.lazy[idx] _UpperCamelCase = True _UpperCamelCase = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: _UpperCamelCase = val if left_element != right_element: _UpperCamelCase = val _UpperCamelCase = val _UpperCamelCase = True _UpperCamelCase = True return True _UpperCamelCase = (left_element + right_element) // 2 self.update(self.left(_A ) , _A , _A , _A , _A , _A ) self.update(self.right(_A ) , mid + 1 , _A , _A , _A , _A ) _UpperCamelCase = max( self.segment_tree[self.left(_A )] , self.segment_tree[self.right(_A )] ) return True def UpperCamelCase_ ( self : Any , _A : int , _A : int , _A : int , _A : int , _A : int ): if self.flag[idx] is True: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = False if left_element != right_element: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = self.lazy[idx] _UpperCamelCase = True _UpperCamelCase = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] _UpperCamelCase = (left_element + right_element) // 2 _UpperCamelCase = self.query(self.left(_A ) , _A , _A , _A , _A ) _UpperCamelCase = self.query(self.right(_A ) , mid + 1 , _A , _A , _A ) return max(_A , _A ) def __str__( self : Tuple ): return str([self.query(1 , 1 , self.size , _A , _A ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _lowerCAmelCase = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _lowerCAmelCase = 15 _lowerCAmelCase = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
71
1
import random from .binary_exp_mod import bin_exp_mod def _snake_case ( __snake_case , __snake_case=1000 ): if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd _UpperCamelCase = n - 1 _UpperCamelCase = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) _UpperCamelCase = 0 while count < prec: _UpperCamelCase = random.randint(2 , n - 1 ) _UpperCamelCase = bin_exp_mod(__snake_case , __snake_case , __snake_case ) if b != 1: _UpperCamelCase = True for _ in range(__snake_case ): if b == n - 1: _UpperCamelCase = False break _UpperCamelCase = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": _lowerCAmelCase = abs(int(input("Enter bound : ").strip())) print("Here's the list of primes:") print(", ".join(str(i) for i in range(n + 1) if is_prime_big(i)))
71
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase = { "configuration_jukebox": [ "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "JukeboxConfig", "JukeboxPriorConfig", "JukeboxVQVAEConfig", ], "tokenization_jukebox": ["JukeboxTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST", "JukeboxModel", "JukeboxPreTrainedModel", "JukeboxVQVAE", "JukeboxPrior", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
1
import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCAmelCase_ ( __lowercase, unittest.TestCase ): UpperCAmelCase = AudioLDMPipeline UpperCAmelCase = TEXT_TO_AUDIO_PARAMS UpperCAmelCase = TEXT_TO_AUDIO_BATCH_PARAMS UpperCAmelCase = frozenset( [ "num_inference_steps", "num_waveforms_per_prompt", "generator", "latents", "output_type", "return_dict", "callback", "callback_steps", ] ) def UpperCamelCase_ ( self : Optional[Any] ): torch.manual_seed(0 ) _UpperCamelCase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=(32, 64) , class_embed_type='''simple_projection''' , projection_class_embeddings_input_dim=32 , class_embeddings_concat=_A , ) _UpperCamelCase = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=_A , set_alpha_to_one=_A , ) torch.manual_seed(0 ) _UpperCamelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) _UpperCamelCase = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) _UpperCamelCase = ClapTextModelWithProjection(_A ) _UpperCamelCase = RobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-roberta''' , model_max_length=77 ) _UpperCamelCase = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=_A , ) _UpperCamelCase = SpeechTaHifiGan(_A ) _UpperCamelCase = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''vocoder''': vocoder, } return components def UpperCamelCase_ ( self : Optional[int] , _A : int , _A : Optional[int]=0 ): if str(_A ).startswith('''mps''' ): _UpperCamelCase = torch.manual_seed(_A ) else: _UpperCamelCase = torch.Generator(device=_A ).manual_seed(_A ) _UpperCamelCase = { '''prompt''': '''A hammer hitting a wooden surface''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, } return inputs def UpperCamelCase_ ( self : Any ): _UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = AudioLDMPipeline(**_A ) _UpperCamelCase = audioldm_pipe.to(_A ) audioldm_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = audioldm_pipe(**_A ) _UpperCamelCase = output.audios[0] assert audio.ndim == 1 assert len(_A ) == 256 _UpperCamelCase = audio[:10] _UpperCamelCase = np.array( [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = AudioLDMPipeline(**_A ) _UpperCamelCase = audioldm_pipe.to(_A ) _UpperCamelCase = audioldm_pipe.to(_A ) audioldm_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = 3 * [inputs['''prompt''']] # forward _UpperCamelCase = audioldm_pipe(**_A ) _UpperCamelCase = output.audios[0] _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = 3 * [inputs.pop('''prompt''' )] _UpperCamelCase = audioldm_pipe.tokenizer( _A , padding='''max_length''' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=_A , return_tensors='''pt''' , ) _UpperCamelCase = text_inputs['''input_ids'''].to(_A ) _UpperCamelCase = audioldm_pipe.text_encoder( _A , ) _UpperCamelCase = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state _UpperCamelCase = F.normalize(_A , dim=-1 ) _UpperCamelCase = prompt_embeds # forward _UpperCamelCase = audioldm_pipe(**_A ) _UpperCamelCase = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = AudioLDMPipeline(**_A ) _UpperCamelCase = audioldm_pipe.to(_A ) _UpperCamelCase = audioldm_pipe.to(_A ) audioldm_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = 3 * ['''this is a negative prompt'''] _UpperCamelCase = negative_prompt _UpperCamelCase = 3 * [inputs['''prompt''']] # forward _UpperCamelCase = audioldm_pipe(**_A ) _UpperCamelCase = output.audios[0] _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = 3 * [inputs.pop('''prompt''' )] _UpperCamelCase = [] for p in [prompt, negative_prompt]: _UpperCamelCase = audioldm_pipe.tokenizer( _A , padding='''max_length''' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=_A , return_tensors='''pt''' , ) _UpperCamelCase = text_inputs['''input_ids'''].to(_A ) _UpperCamelCase = audioldm_pipe.text_encoder( _A , ) _UpperCamelCase = text_embeds.text_embeds # additional L_2 normalization over each hidden-state _UpperCamelCase = F.normalize(_A , dim=-1 ) embeds.append(_A ) _UpperCamelCase , _UpperCamelCase = embeds # forward _UpperCamelCase = audioldm_pipe(**_A ) _UpperCamelCase = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def UpperCamelCase_ ( self : str ): _UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = PNDMScheduler(skip_prk_steps=_A ) _UpperCamelCase = AudioLDMPipeline(**_A ) _UpperCamelCase = audioldm_pipe.to(_A ) audioldm_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = '''egg cracking''' _UpperCamelCase = audioldm_pipe(**_A , negative_prompt=_A ) _UpperCamelCase = output.audios[0] assert audio.ndim == 1 assert len(_A ) == 256 _UpperCamelCase = audio[:10] _UpperCamelCase = np.array( [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = PNDMScheduler(skip_prk_steps=_A ) _UpperCamelCase = AudioLDMPipeline(**_A ) _UpperCamelCase = audioldm_pipe.to(_A ) audioldm_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = '''A hammer hitting a wooden surface''' # test num_waveforms_per_prompt=1 (default) _UpperCamelCase = audioldm_pipe(_A , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts _UpperCamelCase = 2 _UpperCamelCase = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt _UpperCamelCase = 2 _UpperCamelCase = audioldm_pipe(_A , num_inference_steps=2 , num_waveforms_per_prompt=_A ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts _UpperCamelCase = 2 _UpperCamelCase = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=_A ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = AudioLDMPipeline(**_A ) _UpperCamelCase = audioldm_pipe.to(_A ) audioldm_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = audioldm_pipe.vocoder.config.sampling_rate _UpperCamelCase = self.get_dummy_inputs(_A ) _UpperCamelCase = audioldm_pipe(audio_length_in_s=0.016 , **_A ) _UpperCamelCase = output.audios[0] assert audio.ndim == 1 assert len(_A ) / vocoder_sampling_rate == 0.016 _UpperCamelCase = audioldm_pipe(audio_length_in_s=0.032 , **_A ) _UpperCamelCase = output.audios[0] assert audio.ndim == 1 assert len(_A ) / vocoder_sampling_rate == 0.032 def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = AudioLDMPipeline(**_A ) _UpperCamelCase = audioldm_pipe.to(_A ) audioldm_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = ['''hey'''] _UpperCamelCase = audioldm_pipe(_A , num_inference_steps=1 ) _UpperCamelCase = output.audios.shape assert audio_shape == (1, 256) _UpperCamelCase = audioldm_pipe.vocoder.config config.model_in_dim *= 2 _UpperCamelCase = SpeechTaHifiGan(_A ).to(_A ) _UpperCamelCase = audioldm_pipe(_A , num_inference_steps=1 ) _UpperCamelCase = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def UpperCamelCase_ ( self : Optional[int] ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=_A ) def UpperCamelCase_ ( self : str ): self._test_inference_batch_single_identical(test_mean_pixel_difference=_A ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def UpperCamelCase_ ( self : Union[str, Any] ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=_A ) @slow class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Optional[int] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self : List[str] , _A : Union[str, Any] , _A : List[str]="cpu" , _A : Any=torch.floataa , _A : Dict=0 ): _UpperCamelCase = torch.Generator(device=_A ).manual_seed(_A ) _UpperCamelCase = np.random.RandomState(_A ).standard_normal((1, 8, 128, 16) ) _UpperCamelCase = torch.from_numpy(_A ).to(device=_A , dtype=_A ) _UpperCamelCase = { '''prompt''': '''A hammer hitting a wooden surface''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 2.5, } return inputs def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) _UpperCamelCase = audioldm_pipe.to(_A ) audioldm_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_inputs(_A ) _UpperCamelCase = 25 _UpperCamelCase = audioldm_pipe(**_A ).audios[0] assert audio.ndim == 1 assert len(_A ) == 8_1920 _UpperCamelCase = audio[7_7230:7_7240] _UpperCamelCase = np.array( [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315] ) _UpperCamelCase = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) _UpperCamelCase = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) _UpperCamelCase = audioldm_pipe.to(_A ) audioldm_pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = self.get_inputs(_A ) _UpperCamelCase = audioldm_pipe(**_A ).audios[0] assert audio.ndim == 1 assert len(_A ) == 8_1920 _UpperCamelCase = audio[2_7780:2_7790] _UpperCamelCase = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212] ) _UpperCamelCase = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
71
import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase_ ( __lowercase ): def __init__( self : int , _A : NestedDataStructureLike[PathLike] , _A : Optional[NamedSplit] = None , _A : Optional[Features] = None , _A : str = None , _A : bool = False , _A : bool = False , _A : Optional[str] = None , _A : Optional[int] = None , **_A : str , ): super().__init__( _A , split=_A , features=_A , cache_dir=_A , keep_in_memory=_A , streaming=_A , num_proc=_A , **_A , ) _UpperCamelCase = field _UpperCamelCase = path_or_paths if isinstance(_A , _A ) else {self.split: path_or_paths} _UpperCamelCase = Json( cache_dir=_A , data_files=_A , features=_A , field=_A , **_A , ) def UpperCamelCase_ ( self : List[str] ): # Build iterable dataset if self.streaming: _UpperCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None self.builder.download_and_prepare( download_config=_A , download_mode=_A , verification_mode=_A , base_path=_A , num_proc=self.num_proc , ) _UpperCamelCase = self.builder.as_dataset( split=self.split , verification_mode=_A , in_memory=self.keep_in_memory ) return dataset class lowerCAmelCase_ : def __init__( self : Optional[Any] , _A : Dataset , _A : Union[PathLike, BinaryIO] , _A : Optional[int] = None , _A : Optional[int] = None , **_A : List[str] , ): if num_proc is not None and num_proc <= 0: raise ValueError(F"""num_proc {num_proc} must be an integer > 0.""" ) _UpperCamelCase = dataset _UpperCamelCase = path_or_buf _UpperCamelCase = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _UpperCamelCase = num_proc _UpperCamelCase = '''utf-8''' _UpperCamelCase = to_json_kwargs def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = self.to_json_kwargs.pop('''path_or_buf''' , _A ) _UpperCamelCase = self.to_json_kwargs.pop('''orient''' , '''records''' ) _UpperCamelCase = self.to_json_kwargs.pop('''lines''' , True if orient == '''records''' else False ) _UpperCamelCase = self.to_json_kwargs.pop('''index''' , False if orient in ['''split''', '''table'''] else True ) _UpperCamelCase = self.to_json_kwargs.pop('''compression''' , _A ) if compression not in [None, "infer", "gzip", "bz2", "xz"]: raise NotImplementedError(F"""`datasets` currently does not support {compression} compression""" ) if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with fsspec.open(self.path_or_buf , '''wb''' , compression=_A ) as buffer: _UpperCamelCase = self._write(file_obj=_A , orient=_A , lines=_A , index=_A , **self.to_json_kwargs ) else: if compression: raise NotImplementedError( F"""The compression parameter is not supported when writing to a buffer, but compression={compression}""" ''' was passed. Please provide a local path instead.''' ) _UpperCamelCase = self._write( file_obj=self.path_or_buf , orient=_A , lines=_A , index=_A , **self.to_json_kwargs ) return written def UpperCamelCase_ ( self : Any , _A : Optional[Any] ): _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = args _UpperCamelCase = query_table( table=self.dataset.data , key=slice(_A , offset + self.batch_size ) , indices=self.dataset._indices , ) _UpperCamelCase = batch.to_pandas().to_json( path_or_buf=_A , orient=_A , lines=_A , index=_A , **_A ) if not json_str.endswith('''\n''' ): json_str += "\n" return json_str.encode(self.encoding ) def UpperCamelCase_ ( self : int , _A : BinaryIO , _A : Dict , _A : Optional[Any] , _A : Dict , **_A : str , ): _UpperCamelCase = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating json from Arrow format''' , ): _UpperCamelCase = self._batch_json((offset, orient, lines, index, to_json_kwargs) ) written += file_obj.write(_A ) else: _UpperCamelCase , _UpperCamelCase = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for json_str in logging.tqdm( pool.imap( self._batch_json , [(offset, orient, lines, index, to_json_kwargs) for offset in range(0 , _A , _A )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating json from Arrow format''' , ): written += file_obj.write(_A ) return written
71
1
from __future__ import annotations def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = 0 _UpperCamelCase = len(__snake_case ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: _UpperCamelCase = i + 1 else: _UpperCamelCase = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f'{two_pointer([2, 7, 11, 15], 9) = }')
71
import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class lowerCAmelCase_ ( enum.Enum ): UpperCAmelCase = 0 UpperCAmelCase = 1 UpperCAmelCase = 2 @add_end_docstrings(__lowercase ) class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n " def __init__( self : Tuple , *_A : List[str] , **_A : str ): super().__init__(*_A , **_A ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == '''tf''' else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. _UpperCamelCase = None if self.model.config.prefix is not None: _UpperCamelCase = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. _UpperCamelCase = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = self._sanitize_parameters(prefix=_A , **self._forward_params ) _UpperCamelCase = {**self._preprocess_params, **preprocess_params} _UpperCamelCase = {**self._forward_params, **forward_params} def UpperCamelCase_ ( self : Dict , _A : Optional[int]=None , _A : Any=None , _A : Optional[int]=None , _A : List[str]=None , _A : List[Any]=None , _A : int=None , _A : Tuple=None , _A : Optional[Any]=None , **_A : Optional[int] , ): _UpperCamelCase = {} if prefix is not None: _UpperCamelCase = prefix if prefix: _UpperCamelCase = self.tokenizer( _A , padding=_A , add_special_tokens=_A , return_tensors=self.framework ) _UpperCamelCase = prefix_inputs['''input_ids'''].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( F"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected""" ''' [None, \'hole\']''' ) _UpperCamelCase = handle_long_generation preprocess_params.update(_A ) _UpperCamelCase = generate_kwargs _UpperCamelCase = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_full_text`''' ) if return_tensors is not None: raise ValueError('''`return_full_text` is mutually exclusive with `return_tensors`''' ) _UpperCamelCase = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_tensors`''' ) _UpperCamelCase = ReturnType.TENSORS if return_type is not None: _UpperCamelCase = return_type if clean_up_tokenization_spaces is not None: _UpperCamelCase = clean_up_tokenization_spaces if stop_sequence is not None: _UpperCamelCase = self.tokenizer.encode(_A , add_special_tokens=_A ) if len(_A ) > 1: warnings.warn( '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of''' ''' the stop sequence will be used as the stop sequence string in the interim.''' ) _UpperCamelCase = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCamelCase_ ( self : int , *_A : Union[str, Any] , **_A : Union[str, Any] ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({'''add_space_before_punct_symbol''': True} ) return super()._parse_and_tokenize(*_A , **_A ) def __call__( self : List[str] , _A : str , **_A : Any ): return super().__call__(_A , **_A ) def UpperCamelCase_ ( self : Optional[Any] , _A : List[str] , _A : int="" , _A : Optional[Any]=None , **_A : Optional[Any] ): _UpperCamelCase = self.tokenizer( prefix + prompt_text , padding=_A , add_special_tokens=_A , return_tensors=self.framework ) _UpperCamelCase = prompt_text if handle_long_generation == "hole": _UpperCamelCase = inputs['''input_ids'''].shape[-1] if "max_new_tokens" in generate_kwargs: _UpperCamelCase = generate_kwargs['''max_new_tokens'''] else: _UpperCamelCase = generate_kwargs.get('''max_length''' , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError('''We cannot infer how many new tokens are expected''' ) if cur_len + new_tokens > self.tokenizer.model_max_length: _UpperCamelCase = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( '''We cannot use `hole` to handle this generation the number of desired tokens exceeds the''' ''' models max length''' ) _UpperCamelCase = inputs['''input_ids'''][:, -keep_length:] if "attention_mask" in inputs: _UpperCamelCase = inputs['''attention_mask'''][:, -keep_length:] return inputs def UpperCamelCase_ ( self : Dict , _A : Optional[int] , **_A : str ): _UpperCamelCase = model_inputs['''input_ids'''] _UpperCamelCase = model_inputs.get('''attention_mask''' , _A ) # Allow empty prompts if input_ids.shape[1] == 0: _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = 1 else: _UpperCamelCase = input_ids.shape[0] _UpperCamelCase = model_inputs.pop('''prompt_text''' ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. _UpperCamelCase = generate_kwargs.pop('''prefix_length''' , 0 ) if prefix_length > 0: _UpperCamelCase = '''max_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].max_new_tokens is not None ) if not has_max_new_tokens: _UpperCamelCase = generate_kwargs.get('''max_length''' ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length _UpperCamelCase = '''min_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL _UpperCamelCase = self.model.generate(input_ids=_A , attention_mask=_A , **_A ) _UpperCamelCase = generated_sequence.shape[0] if self.framework == "pt": _UpperCamelCase = generated_sequence.reshape(_A , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": _UpperCamelCase = tf.reshape(_A , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def UpperCamelCase_ ( self : List[str] , _A : Dict , _A : Optional[Any]=ReturnType.FULL_TEXT , _A : Dict=True ): _UpperCamelCase = model_outputs['''generated_sequence'''][0] _UpperCamelCase = model_outputs['''input_ids'''] _UpperCamelCase = model_outputs['''prompt_text'''] _UpperCamelCase = generated_sequence.numpy().tolist() _UpperCamelCase = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: _UpperCamelCase = {'''generated_token_ids''': sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text _UpperCamelCase = self.tokenizer.decode( _A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: _UpperCamelCase = 0 else: _UpperCamelCase = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_A , clean_up_tokenization_spaces=_A , ) ) if return_type == ReturnType.FULL_TEXT: _UpperCamelCase = prompt_text + text[prompt_length:] else: _UpperCamelCase = text[prompt_length:] _UpperCamelCase = {'''generated_text''': all_text} records.append(_A ) return records
71
1
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCAmelCase = { "configuration_gpt_neox_japanese": ["GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXJapaneseConfig"], "tokenization_gpt_neox_japanese": ["GPTNeoXJapaneseTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXJapaneseForCausalLM", "GPTNeoXJapaneseLayer", "GPTNeoXJapaneseModel", "GPTNeoXJapanesePreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : Any ): _UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=_A ).to(_A ) _UpperCamelCase = AutoTokenizer.from_pretrained('''google/mt5-small''' ) _UpperCamelCase = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids _UpperCamelCase = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids _UpperCamelCase = model(input_ids.to(_A ) , labels=labels.to(_A ) ).loss _UpperCamelCase = -(labels.shape[-1] * loss.item()) _UpperCamelCase = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
71
1
from ..utils import DummyObject, requires_backends class lowerCAmelCase_ ( metaclass=__lowercase ): UpperCAmelCase = ["speech"] def __init__( self : Dict , *_A : Union[str, Any] , **_A : str ): requires_backends(self , ['''speech'''] ) class lowerCAmelCase_ ( metaclass=__lowercase ): UpperCAmelCase = ["speech"] def __init__( self : List[str] , *_A : Tuple , **_A : Optional[Any] ): requires_backends(self , ['''speech'''] )
71
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _lowerCAmelCase = logging.getLogger(__name__) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether tp freeze the encoder."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) UpperCAmelCase = field( default="summarization", metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"}, ) UpperCAmelCase = field( default=1024, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=128, metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field(default=-1, metadata={"help": "# training examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# validation examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# test examples. -1 means use all."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Source language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Target language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "# num_beams to use for evaluation."} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."}, ) def _snake_case ( __snake_case , __snake_case , __snake_case ): logger.info(f"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(f""" {key} = {metrics[key]}""" ) save_json(__snake_case , os.path.join(__snake_case , f"""{split}_results.json""" ) ) def _snake_case ( ): # 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. _UpperCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_args_into_dataclasses() check_output_dir(__snake_case ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , __snake_case ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _UpperCamelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _UpperCamelCase = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(__snake_case , __snake_case , __snake_case ): assert hasattr(__snake_case , __snake_case ), f"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(__snake_case , __snake_case , getattr(__snake_case , __snake_case ) ) _UpperCamelCase = 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 , ) _UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=__snake_case , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(__snake_case , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: _UpperCamelCase = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(__snake_case , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(__snake_case , __snake_case ): _UpperCamelCase = tokenizer.lang_code_to_id[data_args.tgt_lang] else: _UpperCamelCase = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(__snake_case ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) _UpperCamelCase = SeqaSeqDataset # Get datasets _UpperCamelCase = ( dataset_class( __snake_case , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer _UpperCamelCase = ( build_compute_metrics_fn(data_args.task , __snake_case ) if training_args.predict_with_generate else None ) _UpperCamelCase = SeqaSeqTrainer( model=__snake_case , args=__snake_case , data_args=__snake_case , train_dataset=__snake_case , eval_dataset=__snake_case , data_collator=SeqaSeqDataCollator( __snake_case , __snake_case , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=__snake_case , tokenizer=__snake_case , ) _UpperCamelCase = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) _UpperCamelCase = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) _UpperCamelCase = train_result.metrics _UpperCamelCase = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) _UpperCamelCase = trainer.evaluate(metric_key_prefix='''val''' ) _UpperCamelCase = data_args.n_val _UpperCamelCase = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.do_predict: logger.info('''*** Predict ***''' ) _UpperCamelCase = trainer.predict(test_dataset=__snake_case , metric_key_prefix='''test''' ) _UpperCamelCase = test_output.metrics _UpperCamelCase = data_args.n_test if trainer.is_world_process_zero(): _UpperCamelCase = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.predict_with_generate: _UpperCamelCase = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=__snake_case , clean_up_tokenization_spaces=__snake_case ) _UpperCamelCase = lmap(str.strip , __snake_case ) write_txt_file(__snake_case , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(__snake_case , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def _snake_case ( __snake_case ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
71
1
def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = '''''' for i in table: res += inp[i - 1] return res def _snake_case ( __snake_case ): return data[1:] + data[0] def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = '''''' for i in range(len(__snake_case ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = int('''0b''' + data[0] + data[-1] , 2 ) _UpperCamelCase = int('''0b''' + data[1:3] , 2 ) return bin(s[row][col] )[2:] def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = message[:4] _UpperCamelCase = message[4:] _UpperCamelCase = apply_table(__snake_case , __snake_case ) _UpperCamelCase = xor(__snake_case , __snake_case ) _UpperCamelCase = apply_sbox(__snake_case , temp[:4] ) # noqa: E741 _UpperCamelCase = apply_sbox(__snake_case , temp[4:] ) _UpperCamelCase = '''0''' * (2 - len(__snake_case )) + l # noqa: E741 _UpperCamelCase = '''0''' * (2 - len(__snake_case )) + r _UpperCamelCase = apply_table(l + r , __snake_case ) _UpperCamelCase = xor(__snake_case , __snake_case ) return temp + right if __name__ == "__main__": _lowerCAmelCase = input("Enter 10 bit key: ") _lowerCAmelCase = input("Enter 8 bit message: ") _lowerCAmelCase = [6, 3, 7, 4, 8, 5, 10, 9] _lowerCAmelCase = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] _lowerCAmelCase = [2, 4, 3, 1] _lowerCAmelCase = [2, 6, 3, 1, 4, 8, 5, 7] _lowerCAmelCase = [4, 1, 3, 5, 7, 2, 8, 6] _lowerCAmelCase = [4, 1, 2, 3, 2, 3, 4, 1] _lowerCAmelCase = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] _lowerCAmelCase = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation _lowerCAmelCase = apply_table(key, paa_table) _lowerCAmelCase = temp[:5] _lowerCAmelCase = temp[5:] _lowerCAmelCase = left_shift(left) _lowerCAmelCase = left_shift(right) _lowerCAmelCase = apply_table(left + right, pa_table) _lowerCAmelCase = left_shift(left) _lowerCAmelCase = left_shift(right) _lowerCAmelCase = left_shift(left) _lowerCAmelCase = left_shift(right) _lowerCAmelCase = apply_table(left + right, pa_table) # encryption _lowerCAmelCase = apply_table(message, IP) _lowerCAmelCase = function(expansion, sa, sa, keya, temp) _lowerCAmelCase = temp[4:] + temp[:4] _lowerCAmelCase = function(expansion, sa, sa, keya, temp) _lowerCAmelCase = apply_table(temp, IP_inv) print("Cipher text is:", CT) # decryption _lowerCAmelCase = apply_table(CT, IP) _lowerCAmelCase = function(expansion, sa, sa, keya, temp) _lowerCAmelCase = temp[4:] + temp[:4] _lowerCAmelCase = function(expansion, sa, sa, keya, temp) _lowerCAmelCase = apply_table(temp, IP_inv) print("Plain text after decypting is:", PT)
71
from __future__ import annotations import typing from collections import Counter def _snake_case ( __snake_case ): _UpperCamelCase = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(__snake_case , max_perimeter + 1 ): _UpperCamelCase = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__snake_case ): _UpperCamelCase = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _snake_case ( __snake_case = 1000 ): _UpperCamelCase = pythagorean_triple(__snake_case ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'Perimeter {solution()} has maximum solutions')
71
1
from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class lowerCAmelCase_ ( __lowercase ): def __init__( self : Tuple , _A : Optional[NestedDataStructureLike[PathLike]] = None , _A : Optional[NamedSplit] = None , _A : Optional[Features] = None , _A : str = None , _A : bool = False , _A : bool = False , _A : Optional[int] = None , **_A : str , ): _UpperCamelCase = path_or_paths _UpperCamelCase = split if split or isinstance(_A , _A ) else '''train''' _UpperCamelCase = features _UpperCamelCase = cache_dir _UpperCamelCase = keep_in_memory _UpperCamelCase = streaming _UpperCamelCase = num_proc _UpperCamelCase = kwargs @abstractmethod def UpperCamelCase_ ( self : Optional[int] ): pass class lowerCAmelCase_ ( __lowercase ): def __init__( self : Optional[int] , _A : Optional[Features] = None , _A : str = None , _A : bool = False , _A : bool = False , _A : Optional[int] = None , **_A : List[Any] , ): _UpperCamelCase = features _UpperCamelCase = cache_dir _UpperCamelCase = keep_in_memory _UpperCamelCase = streaming _UpperCamelCase = num_proc _UpperCamelCase = kwargs @abstractmethod def UpperCamelCase_ ( self : Optional[int] ): pass
71
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = (DPMSolverSDEScheduler,) UpperCAmelCase = 10 def UpperCamelCase_ ( self : Tuple , **_A : Union[str, Any] ): _UpperCamelCase = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''noise_sampler_seed''': 0, } config.update(**_A ) return config def UpperCamelCase_ ( self : List[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=_A ) def UpperCamelCase_ ( self : List[Any] ): for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_A , beta_end=_A ) def UpperCamelCase_ ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_A ) def UpperCamelCase_ ( self : Union[str, Any] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_8210_4492_1875 ) < 1e-2 assert abs(result_mean.item() - 0.2178_7059_6456_5277 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3521_1181_6406 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9068_9229_9652 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_1492_0043_9453 ) < 1e-2 assert abs(result_mean.item() - 0.1_6226_2890_1481_6284 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_6633_6059_5703 ) < 1e-2 assert abs(result_mean.item() - 0.1_6688_3260_0116_7297 ) < 1e-3 else: assert abs(result_sum.item() - 119.8_4875_4882_8125 ) < 1e-2 assert abs(result_mean.item() - 0.1560_5306_6253_6621 ) < 1e-3 def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps , device=_A ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter.to(_A ) * scheduler.init_noise_sigma for t in scheduler.timesteps: _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_9573_9746_0938 ) < 1e-2 assert abs(result_mean.item() - 0.2_1805_9346_0798_2635 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3536_3769_5312 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9083_8241_5771 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A , use_karras_sigmas=_A ) scheduler.set_timesteps(self.num_inference_steps , device=_A ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter.to(_A ) * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for t in scheduler.timesteps: _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_9741_3574_2188 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_6535_6445_3125 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 else: assert abs(result_sum.item() - 170.3_1352_2338_8672 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2
71
1
import importlib import json import os import sys import tempfile import unittest from pathlib import Path import transformers import transformers.models.auto from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.bert.configuration_bert import BertConfig from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 _lowerCAmelCase = get_tests_dir("fixtures/dummy-config.json") class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = 0 def UpperCamelCase_ ( self : int ): self.assertIsNotNone(transformers.models.auto.__spec__ ) self.assertIsNotNone(importlib.util.find_spec('''transformers.models.auto''' ) ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = AutoConfig.from_pretrained('''bert-base-uncased''' ) self.assertIsInstance(_A , _A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsInstance(_A , _A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsInstance(_A , _A ) def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = AutoConfig.for_model('''roberta''' ) self.assertIsInstance(_A , _A ) def UpperCamelCase_ ( self : int ): with tempfile.TemporaryDirectory() as tmp_dir: # This model name contains bert and roberta, but roberta ends up being picked. _UpperCamelCase = os.path.join(_A , '''fake-roberta''' ) os.makedirs(_A , exist_ok=_A ) with open(os.path.join(_A , '''config.json''' ) , '''w''' ) as f: f.write(json.dumps({} ) ) _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertEqual(type(_A ) , _A ) def UpperCamelCase_ ( self : Any ): try: AutoConfig.register('''custom''' , _A ) # Wrong model type will raise an error with self.assertRaises(_A ): AutoConfig.register('''model''' , _A ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_A ): AutoConfig.register('''bert''' , _A ) # Now that the config is registered, it can be used as any other config with the auto-API _UpperCamelCase = CustomConfig() with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_A ) _UpperCamelCase = AutoConfig.from_pretrained(_A ) self.assertIsInstance(_A , _A ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] def UpperCamelCase_ ( self : Dict ): with self.assertRaisesRegex( _A , '''bert-base is not a local folder and is not a valid model identifier''' ): _UpperCamelCase = AutoConfig.from_pretrained('''bert-base''' ) def UpperCamelCase_ ( self : Optional[int] ): with self.assertRaisesRegex( _A , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): _UpperCamelCase = AutoConfig.from_pretrained(_A , revision='''aaaaaa''' ) def UpperCamelCase_ ( self : Any ): with self.assertRaisesRegex( _A , '''hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.''' , ): _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/no-config-test-repo''' ) def UpperCamelCase_ ( self : Optional[int] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_A ): _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_A ): _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''' , trust_remote_code=_A ) _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''' , trust_remote_code=_A ) self.assertEqual(config.__class__.__name__ , '''NewModelConfig''' ) # Test config can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(_A ) _UpperCamelCase = AutoConfig.from_pretrained(_A , trust_remote_code=_A ) self.assertEqual(reloaded_config.__class__.__name__ , '''NewModelConfig''' ) def UpperCamelCase_ ( self : List[Any] ): class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "new-model" try: AutoConfig.register('''new-model''' , _A ) # If remote code is not set, the default is to use local _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''' ) self.assertEqual(config.__class__.__name__ , '''NewModelConfigLocal''' ) # If remote code is disabled, we load the local one. _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''' , trust_remote_code=_A ) self.assertEqual(config.__class__.__name__ , '''NewModelConfigLocal''' ) # If remote is enabled, we load from the Hub _UpperCamelCase = AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''' , trust_remote_code=_A ) self.assertEqual(config.__class__.__name__ , '''NewModelConfig''' ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"]
71
import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class lowerCAmelCase_ : @property def UpperCamelCase_ ( self : Optional[int] ): return self.get_dummy_input() @property def UpperCamelCase_ ( self : Dict ): if self.block_type == "down": return (4, 32, 16, 16) elif self.block_type == "mid": return (4, 32, 32, 32) elif self.block_type == "up": return (4, 32, 64, 64) raise ValueError(F"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'.""" ) def UpperCamelCase_ ( self : Union[str, Any] , _A : List[str]=True , _A : Any=False , _A : Union[str, Any]=False , _A : int=False , ): _UpperCamelCase = 4 _UpperCamelCase = 32 _UpperCamelCase = (32, 32) _UpperCamelCase = torch.manual_seed(0 ) _UpperCamelCase = torch.device(_A ) _UpperCamelCase = (batch_size, num_channels) + sizes _UpperCamelCase = randn_tensor(_A , generator=_A , device=_A ) _UpperCamelCase = {'''hidden_states''': hidden_states} if include_temb: _UpperCamelCase = 128 _UpperCamelCase = randn_tensor((batch_size, temb_channels) , generator=_A , device=_A ) if include_res_hidden_states_tuple: _UpperCamelCase = torch.manual_seed(1 ) _UpperCamelCase = (randn_tensor(_A , generator=_A , device=_A ),) if include_encoder_hidden_states: _UpperCamelCase = floats_tensor((batch_size, 32, 32) ).to(_A ) if include_skip_sample: _UpperCamelCase = randn_tensor(((batch_size, 3) + sizes) , generator=_A , device=_A ) return dummy_input def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = { '''in_channels''': 32, '''out_channels''': 32, '''temb_channels''': 128, } if self.block_type == "up": _UpperCamelCase = 32 if self.block_type == "mid": init_dict.pop('''out_channels''' ) _UpperCamelCase = self.dummy_input return init_dict, inputs_dict def UpperCamelCase_ ( self : Tuple , _A : Union[str, Any] ): _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**_A ) unet_block.to(_A ) unet_block.eval() with torch.no_grad(): _UpperCamelCase = unet_block(**_A ) if isinstance(_A , _A ): _UpperCamelCase = output[0] self.assertEqual(output.shape , self.output_shape ) _UpperCamelCase = output[0, -1, -3:, -3:] _UpperCamelCase = torch.tensor(_A ).to(_A ) assert torch_all_close(output_slice.flatten() , _A , atol=5e-3 ) @unittest.skipIf(torch_device == '''mps''' , '''Training is not supported in mps''' ) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**_A ) model.to(_A ) model.train() _UpperCamelCase = model(**_A ) if isinstance(_A , _A ): _UpperCamelCase = output[0] _UpperCamelCase = torch.device(_A ) _UpperCamelCase = randn_tensor(output.shape , device=_A ) _UpperCamelCase = torch.nn.functional.mse_loss(_A , _A ) loss.backward()
71
1
from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase_ : def __init__( self : Dict ): _UpperCamelCase = {} def UpperCamelCase_ ( self : Tuple , _A : str ): _UpperCamelCase = {} def UpperCamelCase_ ( self : Tuple , _A : str , _A : str , _A : float ): if nodea not in self.connections: self.add_node(_A ) if nodea not in self.connections: self.add_node(_A ) _UpperCamelCase = probability def UpperCamelCase_ ( self : int ): return list(self.connections ) def UpperCamelCase_ ( self : Dict , _A : str ): _UpperCamelCase = 0 _UpperCamelCase = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def _snake_case ( __snake_case , __snake_case , __snake_case ): _UpperCamelCase = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__snake_case , __snake_case , __snake_case ) _UpperCamelCase = Counter(graph.get_nodes() ) _UpperCamelCase = start for _ in range(__snake_case ): _UpperCamelCase = graph.transition(__snake_case ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
71
def _snake_case ( __snake_case ): if not isinstance(__snake_case , __snake_case ): raise TypeError('''Input value must be an \'int\' type''' ) _UpperCamelCase = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
71
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version _lowerCAmelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt") @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( default="cifar10", metadata={"help": "Name of a dataset from the datasets package"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "The column name of the images in the files."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "A folder containing the training data."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "A folder containing the validation data."} ) UpperCAmelCase = field( default=0.1_5, metadata={"help": "Percent to split off of train for validation."} ) UpperCAmelCase = field( default=__lowercase, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) }, ) UpperCAmelCase = field( default=__lowercase, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) }, ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = {} if self.train_dir is not None: _UpperCamelCase = self.train_dir if self.validation_dir is not None: _UpperCamelCase = self.validation_dir _UpperCamelCase = data_files if data_files else None @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( default=__lowercase, metadata={ "help": ( "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch." ) }, ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained config name or path if not the same as model_name_or_path"} ) UpperCAmelCase = field( default=__lowercase, metadata={ "help": ( "Override some existing default config settings when a model is trained from scratch. Example: " "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" ) }, ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} ) UpperCAmelCase = field( default="main", metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Name or path of preprocessor config."} ) UpperCAmelCase = field( default=__lowercase, metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) }, ) UpperCAmelCase = field( default=0.7_5, metadata={"help": "The ratio of the number of masked tokens in the input sequence."} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Whether or not to train with normalized pixel values as target."} ) @dataclass class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = field( default=1e-3, metadata={"help": "Base learning rate: absolute_lr = base_lr * total_batch_size / 256."} ) def _snake_case ( __snake_case ): _UpperCamelCase = torch.stack([example['''pixel_values'''] for example in examples] ) return {"pixel_values": pixel_values} def _snake_case ( ): # 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. _UpperCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_mae''' , __snake_case , __snake_case ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _UpperCamelCase = training_args.get_process_log_level() logger.setLevel(__snake_case ) transformers.utils.logging.set_verbosity(__snake_case ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. _UpperCamelCase = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _UpperCamelCase = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset. _UpperCamelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _UpperCamelCase = None if '''validation''' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __snake_case ) and data_args.train_val_split > 0.0: _UpperCamelCase = ds['''train'''].train_test_split(data_args.train_val_split ) _UpperCamelCase = split['''train'''] _UpperCamelCase = split['''test'''] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _UpperCamelCase = { '''cache_dir''': model_args.cache_dir, '''revision''': model_args.model_revision, '''use_auth_token''': True if model_args.use_auth_token else None, } if model_args.config_name: _UpperCamelCase = ViTMAEConfig.from_pretrained(model_args.config_name , **__snake_case ) elif model_args.model_name_or_path: _UpperCamelCase = ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _UpperCamelCase = ViTMAEConfig() logger.warning('''You are instantiating a new config instance from scratch.''' ) if model_args.config_overrides is not None: logger.info(f"""Overriding config: {model_args.config_overrides}""" ) config.update_from_string(model_args.config_overrides ) logger.info(f"""New config: {config}""" ) # adapt config config.update( { '''mask_ratio''': model_args.mask_ratio, '''norm_pix_loss''': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _UpperCamelCase = ViTImageProcessor.from_pretrained(model_args.image_processor_name , **__snake_case ) elif model_args.model_name_or_path: _UpperCamelCase = ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **__snake_case ) else: _UpperCamelCase = ViTImageProcessor() # create model if model_args.model_name_or_path: _UpperCamelCase = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__snake_case , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('''Training new model from scratch''' ) _UpperCamelCase = ViTMAEForPreTraining(__snake_case ) if training_args.do_train: _UpperCamelCase = ds['''train'''].column_names else: _UpperCamelCase = ds['''validation'''].column_names if data_args.image_column_name is not None: _UpperCamelCase = data_args.image_column_name elif "image" in column_names: _UpperCamelCase = '''image''' elif "img" in column_names: _UpperCamelCase = '''img''' else: _UpperCamelCase = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _UpperCamelCase = image_processor.size['''shortest_edge'''] else: _UpperCamelCase = (image_processor.size['''height'''], image_processor.size['''width''']) _UpperCamelCase = Compose( [ Lambda(lambda __snake_case : img.convert('''RGB''' ) if img.mode != "RGB" else img ), RandomResizedCrop(__snake_case , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(__snake_case ): _UpperCamelCase = [transforms(__snake_case ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('''--do_train requires a train dataset''' ) if data_args.max_train_samples is not None: _UpperCamelCase = ds['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__snake_case ) if training_args.do_eval: if "validation" not in ds: raise ValueError('''--do_eval requires a validation dataset''' ) if data_args.max_eval_samples is not None: _UpperCamelCase = ( ds['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__snake_case ) # Compute absolute learning rate _UpperCamelCase = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _UpperCamelCase = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer _UpperCamelCase = Trainer( model=__snake_case , args=__snake_case , train_dataset=ds['''train'''] if training_args.do_train else None , eval_dataset=ds['''validation'''] if training_args.do_eval else None , tokenizer=__snake_case , data_collator=__snake_case , ) # Training if training_args.do_train: _UpperCamelCase = None if training_args.resume_from_checkpoint is not None: _UpperCamelCase = training_args.resume_from_checkpoint elif last_checkpoint is not None: _UpperCamelCase = last_checkpoint _UpperCamelCase = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _UpperCamelCase = trainer.evaluate() trainer.log_metrics('''eval''' , __snake_case ) trainer.save_metrics('''eval''' , __snake_case ) # Write model card and (optionally) push to hub _UpperCamelCase = { '''tasks''': '''masked-auto-encoding''', '''dataset''': data_args.dataset_name, '''tags''': ['''masked-auto-encoding'''], } if training_args.push_to_hub: trainer.push_to_hub(**__snake_case ) else: trainer.create_model_card(**__snake_case ) def _snake_case ( __snake_case ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
71
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } _lowerCAmelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): for attribute in key.split('''.''' ): _UpperCamelCase = getattr(__snake_case , __snake_case ) if weight_type is not None: _UpperCamelCase = getattr(__snake_case , __snake_case ).shape else: _UpperCamelCase = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": _UpperCamelCase = value elif weight_type == "weight_g": _UpperCamelCase = value elif weight_type == "weight_v": _UpperCamelCase = value elif weight_type == "bias": _UpperCamelCase = value else: _UpperCamelCase = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = [] _UpperCamelCase = fairseq_model.state_dict() _UpperCamelCase = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _UpperCamelCase = None for name, value in fairseq_dict.items(): _UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __snake_case , __snake_case , __snake_case , __snake_case , hf_model.config.feat_extract_norm == '''group''' , ) _UpperCamelCase = True elif name.split('''.''' )[0] == "proj": _UpperCamelCase = fairseq_model.proj _UpperCamelCase = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: _UpperCamelCase = True if "*" in mapped_key: _UpperCamelCase = name.split(__snake_case )[0].split('''.''' )[-2] _UpperCamelCase = mapped_key.replace('''*''' , __snake_case ) if "weight_g" in name: _UpperCamelCase = '''weight_g''' elif "weight_v" in name: _UpperCamelCase = '''weight_v''' elif "bias" in name: _UpperCamelCase = '''bias''' elif "weight" in name: _UpperCamelCase = '''weight''' else: _UpperCamelCase = None set_recursively(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) continue if not is_used: unused_weights.append(__snake_case ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = full_name.split('''conv_layers.''' )[-1] _UpperCamelCase = name.split('''.''' ) _UpperCamelCase = int(items[0] ) _UpperCamelCase = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__snake_case ) def _snake_case ( __snake_case ): _UpperCamelCase , _UpperCamelCase = emb.weight.shape _UpperCamelCase = nn.Linear(__snake_case , __snake_case , bias=__snake_case ) _UpperCamelCase = emb.weight.data return lin_layer def _snake_case ( __snake_case ): with open(__snake_case , '''r''' , encoding='''utf-8''' ) as f: _UpperCamelCase = f.readlines() _UpperCamelCase = [line.split(''' ''' )[0] for line in lines] _UpperCamelCase = len(__snake_case ) _UpperCamelCase = { '''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3, } vocab_dict.update(dict(zip(__snake_case , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ): _UpperCamelCase = WavaVecaConfig.from_pretrained(__snake_case ) _UpperCamelCase = SpeechaTextaConfig.from_pretrained( __snake_case , vocab_size=__snake_case , decoder_layers=__snake_case , do_stable_layer_norm=__snake_case ) _UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=__snake_case , return_attention_mask=__snake_case , ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) _UpperCamelCase = model[0].eval() # set weights for wav2vec2 encoder _UpperCamelCase = WavaVecaModel(__snake_case ) _UpperCamelCase = recursively_load_weights_wavaveca(model.encoder , __snake_case ) _UpperCamelCase = SpeechaTextaForCausalLM(__snake_case ) _UpperCamelCase , _UpperCamelCase = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__snake_case ) # set output linear layer unexpected_keys.remove('''embed_out''' ) _UpperCamelCase = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) _UpperCamelCase = SpeechEncoderDecoderModel(encoder=__snake_case , decoder=__snake_case ) _UpperCamelCase = False # add projection layer _UpperCamelCase = nn.Parameter(projection_layer.weight ) _UpperCamelCase = nn.Parameter(projection_layer.bias ) _UpperCamelCase = create_vocab_dict(__snake_case ) with open(os.path.join(__snake_case , '''vocab.json''' ) , '''w''' ) as fp: json.dump(__snake_case , __snake_case ) _UpperCamelCase = SpeechaTextaTokenizer(os.path.join(__snake_case , '''vocab.json''' ) ) tokenizer.save_pretrained(__snake_case ) _UpperCamelCase = hf_wavavec.config.to_dict() _UpperCamelCase = tokenizer.pad_token_id _UpperCamelCase = tokenizer.bos_token_id _UpperCamelCase = tokenizer.eos_token_id _UpperCamelCase = '''speech_to_text_2''' _UpperCamelCase = '''wav2vec2''' _UpperCamelCase = SpeechEncoderDecoderConfig.from_dict(__snake_case ) hf_wavavec.save_pretrained(__snake_case ) feature_extractor.save_pretrained(__snake_case ) if __name__ == "__main__": _lowerCAmelCase = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10_224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") _lowerCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
71
1
def _snake_case ( __snake_case = 1000 ): _UpperCamelCase , _UpperCamelCase = 1, 1 _UpperCamelCase = 2 while True: _UpperCamelCase = 0 _UpperCamelCase = fa + fa _UpperCamelCase , _UpperCamelCase = fa, f index += 1 for _ in str(__snake_case ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
71
from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class lowerCAmelCase_ : def __init__( self : Optional[Any] , _A : Optional[Any] , _A : List[str]=13 , _A : Union[str, Any]=7 , _A : int=True , _A : Optional[int]=True , _A : Optional[int]=True , _A : Union[str, Any]=True , _A : Optional[int]=99 , _A : Union[str, Any]=32 , _A : Dict=2 , _A : List[Any]=4 , _A : Optional[Any]=37 , _A : int="gelu" , _A : Optional[int]=0.1 , _A : str=0.1 , _A : List[str]=512 , _A : Optional[Any]=16 , _A : Optional[Any]=2 , _A : Optional[int]=0.02 , _A : str=False , _A : int=True , _A : Any="None" , _A : Dict=3 , _A : List[Any]=4 , _A : Optional[Any]=None , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_mask _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_labels _UpperCamelCase = num_choices _UpperCamelCase = relative_attention _UpperCamelCase = position_biased_input _UpperCamelCase = pos_att_type _UpperCamelCase = scope def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = None if self.use_input_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None if self.use_labels: _UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCamelCase = DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=_A , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self : Dict , _A : Tuple , _A : Tuple , _A : Union[str, Any] , _A : List[str] , _A : Optional[int] , _A : int , _A : Optional[Any] ): _UpperCamelCase = TFDebertaVaModel(config=_A ) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = [input_ids, input_mask] _UpperCamelCase = model(_A ) _UpperCamelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Dict , _A : Optional[int] , _A : Any , _A : Dict , _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any] , _A : List[str] ): _UpperCamelCase = TFDebertaVaForMaskedLM(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self : Dict , _A : Dict , _A : List[str] , _A : List[Any] , _A : List[Any] , _A : Optional[Any] , _A : Tuple , _A : int ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForSequenceClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple , _A : Dict , _A : Optional[int] , _A : Any , _A : List[Any] , _A : Dict , _A : Union[str, Any] , _A : List[str] ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForTokenClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Dict , _A : Optional[Any] , _A : Optional[int] , _A : Any , _A : List[str] , _A : str , _A : Optional[int] , _A : str ): _UpperCamelCase = TFDebertaVaForQuestionAnswering(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_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 UpperCamelCase_ ( self : Any ): _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( __lowercase, __lowercase, unittest.TestCase ): UpperCAmelCase = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) UpperCAmelCase = ( { "feature-extraction": TFDebertaVaModel, "fill-mask": TFDebertaVaForMaskedLM, "question-answering": TFDebertaVaForQuestionAnswering, "text-classification": TFDebertaVaForSequenceClassification, "token-classification": TFDebertaVaForTokenClassification, "zero-shot": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase = False UpperCAmelCase = False def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = TFDebertaVaModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_A ) @slow def UpperCamelCase_ ( self : Any ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) self.assertIsNotNone(_A ) @require_tf class lowerCAmelCase_ ( unittest.TestCase ): @unittest.skip(reason='''Model not available yet''' ) def UpperCamelCase_ ( self : List[Any] ): pass @slow def UpperCamelCase_ ( self : int ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) _UpperCamelCase = tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) _UpperCamelCase = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) _UpperCamelCase = model(_A , attention_mask=_A )[0] _UpperCamelCase = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , _A , atol=1e-4 )
71
1
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def _snake_case ( __snake_case ): # A local function to see if a dot lands in the circle. def is_in_circle(__snake_case , __snake_case ) -> bool: _UpperCamelCase = sqrt((x**2) + (y**2) ) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle _UpperCamelCase = mean( int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) ) for _ in range(__snake_case ) ) # The ratio of the area for circle to square is pi/4. _UpperCamelCase = proportion * 4 print(f"""The estimated value of pi is {pi_estimate}""" ) print(f"""The numpy value of pi is {pi}""" ) print(f"""The total error is {abs(pi - pi_estimate )}""" ) def _snake_case ( __snake_case , __snake_case , __snake_case = 0.0 , __snake_case = 1.0 , ): return mean( function_to_integrate(uniform(__snake_case , __snake_case ) ) for _ in range(__snake_case ) ) * (max_value - min_value) def _snake_case ( __snake_case , __snake_case = 0.0 , __snake_case = 1.0 ): def identity_function(__snake_case ) -> float: return x _UpperCamelCase = area_under_curve_estimator( __snake_case , __snake_case , __snake_case , __snake_case ) _UpperCamelCase = (max_value * max_value - min_value * min_value) / 2 print('''******************''' ) print(f"""Estimating area under y=x where x varies from {min_value} to {max_value}""" ) print(f"""Estimated value is {estimated_value}""" ) print(f"""Expected value is {expected_value}""" ) print(f"""Total error is {abs(estimated_value - expected_value )}""" ) print('''******************''' ) def _snake_case ( __snake_case ): def function_to_integrate(__snake_case ) -> float: return sqrt(4.0 - x * x ) _UpperCamelCase = area_under_curve_estimator( __snake_case , __snake_case , 0.0 , 2.0 ) print('''******************''' ) print('''Estimating pi using area_under_curve_estimator''' ) print(f"""Estimated value is {estimated_value}""" ) print(f"""Expected value is {pi}""" ) print(f"""Total error is {abs(estimated_value - pi )}""" ) print('''******************''' ) if __name__ == "__main__": import doctest doctest.testmod()
71
def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case ): # Return True if there is node that has not iterated. _UpperCamelCase = [False] * len(__snake_case ) _UpperCamelCase = [] queue.append(__snake_case ) _UpperCamelCase = True while queue: _UpperCamelCase = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(__snake_case ) _UpperCamelCase = True _UpperCamelCase = u return visited[t] def _snake_case ( __snake_case , __snake_case , __snake_case ): # This array is filled by BFS and to store path _UpperCamelCase = [-1] * (len(__snake_case )) _UpperCamelCase = 0 while bfs(__snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = float('''Inf''' ) _UpperCamelCase = sink while s != source: # Find the minimum value in select path _UpperCamelCase = min(__snake_case , graph[parent[s]][s] ) _UpperCamelCase = parent[s] max_flow += path_flow _UpperCamelCase = sink while v != source: _UpperCamelCase = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow _UpperCamelCase = parent[v] return max_flow _lowerCAmelCase = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] _lowerCAmelCase, _lowerCAmelCase = 0, 5 print(ford_fulkerson(graph, source, sink))
71
1
from maths.prime_check import is_prime def _snake_case ( __snake_case ): if not isinstance(__snake_case , __snake_case ): _UpperCamelCase = f"""Input value of [number={number}] must be an integer""" raise TypeError(__snake_case ) if is_prime(__snake_case ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
71
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _lowerCAmelCase = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
1
def _snake_case ( __snake_case ): if not isinstance(__snake_case , __snake_case ): raise TypeError('''Input value must be an \'int\' type''' ) _UpperCamelCase = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
71
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Any ): _UpperCamelCase = tempfile.mkdtemp() # fmt: off _UpperCamelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on _UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) _UpperCamelCase = { '''do_resize''': True, '''size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } _UpperCamelCase = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_A , _A ) def UpperCamelCase_ ( self : Tuple , **_A : Optional[Any] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : List[Any] , **_A : Union[str, Any] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : int ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _UpperCamelCase = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = self.get_image_processor() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _UpperCamelCase = self.get_image_processor(do_normalize=_A , padding_value=1.0 ) _UpperCamelCase = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = image_processor(_A , return_tensors='''np''' ) _UpperCamelCase = processor(images=_A , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = processor(text=_A ) _UpperCamelCase = tokenizer(_A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_A ): processor() def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _UpperCamelCase = processor.batch_decode(_A ) _UpperCamelCase = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A ) def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
71
1
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class lowerCAmelCase_ ( __lowercase, unittest.TestCase ): UpperCAmelCase = KandinskyVaaControlnetImgaImgPipeline UpperCAmelCase = ["image_embeds", "negative_image_embeds", "image", "hint"] UpperCAmelCase = ["image_embeds", "negative_image_embeds", "image", "hint"] UpperCAmelCase = [ "generator", "height", "width", "strength", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] UpperCAmelCase = False @property def UpperCamelCase_ ( self : Dict ): return 32 @property def UpperCamelCase_ ( self : List[Any] ): return 32 @property def UpperCamelCase_ ( self : str ): return self.time_input_dim @property def UpperCamelCase_ ( self : List[Any] ): return self.time_input_dim * 4 @property def UpperCamelCase_ ( self : Any ): return 100 @property def UpperCamelCase_ ( self : int ): torch.manual_seed(0 ) _UpperCamelCase = { '''in_channels''': 8, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image_hint''', '''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 = UNetaDConditionModel(**_A ) return model @property def UpperCamelCase_ ( self : int ): return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "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", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def UpperCamelCase_ ( self : List[Any] ): torch.manual_seed(0 ) _UpperCamelCase = VQModel(**self.dummy_movq_kwargs ) return model def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.dummy_unet _UpperCamelCase = self.dummy_movq _UpperCamelCase = { '''num_train_timesteps''': 1000, '''beta_schedule''': '''linear''', '''beta_start''': 0.0_0085, '''beta_end''': 0.012, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } _UpperCamelCase = DDIMScheduler(**_A ) _UpperCamelCase = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def UpperCamelCase_ ( self : Tuple , _A : Dict , _A : Dict=0 ): _UpperCamelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_A ) ).to(_A ) _UpperCamelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _A ) # create init_image _UpperCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(_A ) ).to(_A ) _UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] _UpperCamelCase = Image.fromarray(np.uinta(_A ) ).convert('''RGB''' ).resize((256, 256) ) # create hint _UpperCamelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(_A ) ).to(_A ) if str(_A ).startswith('''mps''' ): _UpperCamelCase = torch.manual_seed(_A ) else: _UpperCamelCase = torch.Generator(device=_A ).manual_seed(_A ) _UpperCamelCase = { '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''hint''': hint, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = '''cpu''' _UpperCamelCase = self.get_dummy_components() _UpperCamelCase = self.pipeline_class(**_A ) _UpperCamelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) _UpperCamelCase = pipe(**self.get_dummy_inputs(_A ) ) _UpperCamelCase = output.images _UpperCamelCase = pipe( **self.get_dummy_inputs(_A ) , return_dict=_A , )[0] _UpperCamelCase = image[0, -3:, -3:, -1] _UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCamelCase = np.array( [0.5498_5034, 0.5550_9365, 0.5256_1504, 0.557_0494, 0.559_3818, 0.526_3979, 0.5028_5643, 0.506_9846, 0.5119_6736] ) 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 lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Dict ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy''' ) _UpperCamelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) _UpperCamelCase = init_image.resize((512, 512) ) _UpperCamelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) _UpperCamelCase = torch.from_numpy(np.array(_A ) ).float() / 255.0 _UpperCamelCase = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) _UpperCamelCase = '''A robot, 4k photo''' _UpperCamelCase = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(_A ) _UpperCamelCase = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa ) _UpperCamelCase = pipeline.to(_A ) pipeline.set_progress_bar_config(disable=_A ) _UpperCamelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) _UpperCamelCase , _UpperCamelCase = pipe_prior( _A , image=_A , strength=0.85 , generator=_A , negative_prompt='''''' , ).to_tuple() _UpperCamelCase = pipeline( image=_A , image_embeds=_A , negative_image_embeds=_A , hint=_A , generator=_A , num_inference_steps=100 , height=512 , width=512 , strength=0.5 , output_type='''np''' , ) _UpperCamelCase = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(_A , _A )
71
def _snake_case ( __snake_case , __snake_case , __snake_case ): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__snake_case , n - 1 , __snake_case ) * a) % mod else: _UpperCamelCase = binary_exponentiation(__snake_case , n / 2 , __snake_case ) return (b * b) % mod # a prime number _lowerCAmelCase = 701 _lowerCAmelCase = 1_000_000_000 _lowerCAmelCase = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
71
1
import argparse import os import re _lowerCAmelCase = "src/diffusers" # Pattern that looks at the indentation in a line. _lowerCAmelCase = re.compile(r"^(\s*)\S") # Pattern that matches `"key":" and puts `key` in group 0. _lowerCAmelCase = re.compile(r"^\s*\"([^\"]+)\":") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. _lowerCAmelCase = re.compile(r"^\s*_import_structure\[\"([^\"]+)\"\]") # Pattern that matches `"key",` and puts `key` in group 0. _lowerCAmelCase = re.compile(r"^\s*\"([^\"]+)\",\s*$") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. _lowerCAmelCase = re.compile(r"\[([^\]]+)\]") def _snake_case ( __snake_case ): _UpperCamelCase = _re_indent.search(__snake_case ) return "" if search is None else search.groups()[0] def _snake_case ( __snake_case , __snake_case="" , __snake_case=None , __snake_case=None ): _UpperCamelCase = 0 _UpperCamelCase = code.split('''\n''' ) if start_prompt is not None: while not lines[index].startswith(__snake_case ): index += 1 _UpperCamelCase = ['''\n'''.join(lines[:index] )] else: _UpperCamelCase = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). _UpperCamelCase = [lines[index]] index += 1 while index < len(__snake_case ) and (end_prompt is None or not lines[index].startswith(__snake_case )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(__snake_case ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ''' ''' ): current_block.append(lines[index] ) blocks.append('''\n'''.join(__snake_case ) ) if index < len(__snake_case ) - 1: _UpperCamelCase = [lines[index + 1]] index += 1 else: _UpperCamelCase = [] else: blocks.append('''\n'''.join(__snake_case ) ) _UpperCamelCase = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(__snake_case ) > 0: blocks.append('''\n'''.join(__snake_case ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(__snake_case ): blocks.append('''\n'''.join(lines[index:] ) ) return blocks def _snake_case ( __snake_case ): def _inner(__snake_case ): return key(__snake_case ).lower().replace('''_''' , '''''' ) return _inner def _snake_case ( __snake_case , __snake_case=None ): # If no key is provided, we use a noop. def noop(__snake_case ): return x if key is None: _UpperCamelCase = noop # Constants are all uppercase, they go first. _UpperCamelCase = [obj for obj in objects if key(__snake_case ).isupper()] # Classes are not all uppercase but start with a capital, they go second. _UpperCamelCase = [obj for obj in objects if key(__snake_case )[0].isupper() and not key(__snake_case ).isupper()] # Functions begin with a lowercase, they go last. _UpperCamelCase = [obj for obj in objects if not key(__snake_case )[0].isupper()] _UpperCamelCase = ignore_underscore(__snake_case ) return sorted(__snake_case , key=__snake_case ) + sorted(__snake_case , key=__snake_case ) + sorted(__snake_case , key=__snake_case ) def _snake_case ( __snake_case ): # This inner function sort imports between [ ]. def _replace(__snake_case ): _UpperCamelCase = match.groups()[0] if "," not in imports: return f"""[{imports}]""" _UpperCamelCase = [part.strip().replace('''"''' , '''''' ) for part in imports.split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: _UpperCamelCase = keys[:-1] return "[" + ", ".join([f"""\"{k}\"""" for k in sort_objects(__snake_case )] ) + "]" _UpperCamelCase = import_statement.split('''\n''' ) if len(__snake_case ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. _UpperCamelCase = 2 if lines[1].strip() == '''[''' else 1 _UpperCamelCase = [(i, _re_strip_line.search(__snake_case ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] _UpperCamelCase = sort_objects(__snake_case , key=lambda __snake_case : x[1] ) _UpperCamelCase = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(__snake_case ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: _UpperCamelCase = _re_bracket_content.sub(_replace , lines[1] ) else: _UpperCamelCase = [part.strip().replace('''"''' , '''''' ) for part in lines[1].split(''',''' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: _UpperCamelCase = keys[:-1] _UpperCamelCase = get_indent(lines[1] ) + ''', '''.join([f"""\"{k}\"""" for k in sort_objects(__snake_case )] ) return "\n".join(__snake_case ) else: # Finally we have to deal with imports fitting on one line _UpperCamelCase = _re_bracket_content.sub(_replace , __snake_case ) return import_statement def _snake_case ( __snake_case , __snake_case=True ): with open(__snake_case , '''r''' ) as f: _UpperCamelCase = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 _UpperCamelCase = split_code_in_indented_blocks( __snake_case , start_prompt='''_import_structure = {''' , end_prompt='''if TYPE_CHECKING:''' ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(__snake_case ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. _UpperCamelCase = main_blocks[block_idx] _UpperCamelCase = block.split('''\n''' ) # Get to the start of the imports. _UpperCamelCase = 0 while line_idx < len(__snake_case ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: _UpperCamelCase = len(__snake_case ) else: line_idx += 1 if line_idx >= len(__snake_case ): continue # Ignore beginning and last line: they don't contain anything. _UpperCamelCase = '''\n'''.join(block_lines[line_idx:-1] ) _UpperCamelCase = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. _UpperCamelCase = split_code_in_indented_blocks(__snake_case , indent_level=__snake_case ) # We have two categories of import key: list or _import_structure[key].append/extend _UpperCamelCase = _re_direct_key if '''_import_structure''' in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. _UpperCamelCase = [(pattern.search(__snake_case ).groups()[0] if pattern.search(__snake_case ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. _UpperCamelCase = [(i, key) for i, key in enumerate(__snake_case ) if key is not None] _UpperCamelCase = [x[0] for x in sorted(__snake_case , key=lambda __snake_case : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. _UpperCamelCase = 0 _UpperCamelCase = [] for i in range(len(__snake_case ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: _UpperCamelCase = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(__snake_case ) count += 1 # And we put our main block back together with its first and last line. _UpperCamelCase = '''\n'''.join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(__snake_case ): if check_only: return True else: print(f"""Overwriting {file}.""" ) with open(__snake_case , '''w''' ) as f: f.write('''\n'''.join(__snake_case ) ) def _snake_case ( __snake_case=True ): _UpperCamelCase = [] for root, _, files in os.walk(__snake_case ): if "__init__.py" in files: _UpperCamelCase = sort_imports(os.path.join(__snake_case , '''__init__.py''' ) , check_only=__snake_case ) if result: _UpperCamelCase = [os.path.join(__snake_case , '''__init__.py''' )] if len(__snake_case ) > 0: raise ValueError(f"""Would overwrite {len(__snake_case )} files, run `make style`.""" ) if __name__ == "__main__": _lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") _lowerCAmelCase = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
71
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = (1 - _cos) / 2 _UpperCamelCase = 1 - _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = (1 + _cos) / 2 _UpperCamelCase = -1 - _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = _sin / 2 _UpperCamelCase = 0 _UpperCamelCase = -ba _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 1 - alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = 1 + alpha * big_a _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha * big_a _UpperCamelCase = 1 + alpha / big_a _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha / big_a _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = (big_a + 1) - (big_a - 1) * _cos _UpperCamelCase = (big_a + 1) + (big_a - 1) * _cos _UpperCamelCase = (big_a - 1) - (big_a + 1) * _cos _UpperCamelCase = (big_a - 1) + (big_a + 1) * _cos _UpperCamelCase = 2 * sqrt(__snake_case ) * alpha _UpperCamelCase = big_a * (pmc + aaa) _UpperCamelCase = 2 * big_a * mpc _UpperCamelCase = big_a * (pmc - aaa) _UpperCamelCase = ppmc + aaa _UpperCamelCase = -2 * pmpc _UpperCamelCase = ppmc - aaa _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = (big_a + 1) - (big_a - 1) * _cos _UpperCamelCase = (big_a + 1) + (big_a - 1) * _cos _UpperCamelCase = (big_a - 1) - (big_a + 1) * _cos _UpperCamelCase = (big_a - 1) + (big_a + 1) * _cos _UpperCamelCase = 2 * sqrt(__snake_case ) * alpha _UpperCamelCase = big_a * (ppmc + aaa) _UpperCamelCase = -2 * big_a * pmpc _UpperCamelCase = big_a * (ppmc - aaa) _UpperCamelCase = pmc + aaa _UpperCamelCase = 2 * mpc _UpperCamelCase = pmc - aaa _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
71
1
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } _lowerCAmelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): for attribute in key.split('''.''' ): _UpperCamelCase = getattr(__snake_case , __snake_case ) if weight_type is not None: _UpperCamelCase = getattr(__snake_case , __snake_case ).shape else: _UpperCamelCase = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": _UpperCamelCase = value elif weight_type == "weight_g": _UpperCamelCase = value elif weight_type == "weight_v": _UpperCamelCase = value elif weight_type == "bias": _UpperCamelCase = value else: _UpperCamelCase = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = [] _UpperCamelCase = fairseq_model.state_dict() _UpperCamelCase = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _UpperCamelCase = None for name, value in fairseq_dict.items(): _UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __snake_case , __snake_case , __snake_case , __snake_case , hf_model.config.feat_extract_norm == '''group''' , ) _UpperCamelCase = True elif name.split('''.''' )[0] == "proj": _UpperCamelCase = fairseq_model.proj _UpperCamelCase = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: _UpperCamelCase = True if "*" in mapped_key: _UpperCamelCase = name.split(__snake_case )[0].split('''.''' )[-2] _UpperCamelCase = mapped_key.replace('''*''' , __snake_case ) if "weight_g" in name: _UpperCamelCase = '''weight_g''' elif "weight_v" in name: _UpperCamelCase = '''weight_v''' elif "bias" in name: _UpperCamelCase = '''bias''' elif "weight" in name: _UpperCamelCase = '''weight''' else: _UpperCamelCase = None set_recursively(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) continue if not is_used: unused_weights.append(__snake_case ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = full_name.split('''conv_layers.''' )[-1] _UpperCamelCase = name.split('''.''' ) _UpperCamelCase = int(items[0] ) _UpperCamelCase = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__snake_case ) def _snake_case ( __snake_case ): _UpperCamelCase , _UpperCamelCase = emb.weight.shape _UpperCamelCase = nn.Linear(__snake_case , __snake_case , bias=__snake_case ) _UpperCamelCase = emb.weight.data return lin_layer def _snake_case ( __snake_case ): with open(__snake_case , '''r''' , encoding='''utf-8''' ) as f: _UpperCamelCase = f.readlines() _UpperCamelCase = [line.split(''' ''' )[0] for line in lines] _UpperCamelCase = len(__snake_case ) _UpperCamelCase = { '''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3, } vocab_dict.update(dict(zip(__snake_case , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ): _UpperCamelCase = WavaVecaConfig.from_pretrained(__snake_case ) _UpperCamelCase = SpeechaTextaConfig.from_pretrained( __snake_case , vocab_size=__snake_case , decoder_layers=__snake_case , do_stable_layer_norm=__snake_case ) _UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=__snake_case , return_attention_mask=__snake_case , ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) _UpperCamelCase = model[0].eval() # set weights for wav2vec2 encoder _UpperCamelCase = WavaVecaModel(__snake_case ) _UpperCamelCase = recursively_load_weights_wavaveca(model.encoder , __snake_case ) _UpperCamelCase = SpeechaTextaForCausalLM(__snake_case ) _UpperCamelCase , _UpperCamelCase = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__snake_case ) # set output linear layer unexpected_keys.remove('''embed_out''' ) _UpperCamelCase = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) _UpperCamelCase = SpeechEncoderDecoderModel(encoder=__snake_case , decoder=__snake_case ) _UpperCamelCase = False # add projection layer _UpperCamelCase = nn.Parameter(projection_layer.weight ) _UpperCamelCase = nn.Parameter(projection_layer.bias ) _UpperCamelCase = create_vocab_dict(__snake_case ) with open(os.path.join(__snake_case , '''vocab.json''' ) , '''w''' ) as fp: json.dump(__snake_case , __snake_case ) _UpperCamelCase = SpeechaTextaTokenizer(os.path.join(__snake_case , '''vocab.json''' ) ) tokenizer.save_pretrained(__snake_case ) _UpperCamelCase = hf_wavavec.config.to_dict() _UpperCamelCase = tokenizer.pad_token_id _UpperCamelCase = tokenizer.bos_token_id _UpperCamelCase = tokenizer.eos_token_id _UpperCamelCase = '''speech_to_text_2''' _UpperCamelCase = '''wav2vec2''' _UpperCamelCase = SpeechEncoderDecoderConfig.from_dict(__snake_case ) hf_wavavec.save_pretrained(__snake_case ) feature_extractor.save_pretrained(__snake_case ) if __name__ == "__main__": _lowerCAmelCase = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10_224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") _lowerCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
71
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json", # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "gpt_neox" def __init__( self : Union[str, Any] , _A : Union[str, Any]=5_0432 , _A : List[Any]=6144 , _A : int=44 , _A : int=64 , _A : Optional[Any]=2_4576 , _A : Any="gelu" , _A : Tuple=0.25 , _A : Union[str, Any]=1_0000 , _A : Tuple=0.0 , _A : Any=0.0 , _A : int=0.1 , _A : List[str]=2048 , _A : Dict=0.02 , _A : Optional[Any]=1e-5 , _A : Tuple=True , _A : List[Any]=0 , _A : Optional[int]=2 , _A : Optional[int]=False , _A : List[Any]=True , _A : Any=None , **_A : Any , ): super().__init__(bos_token_id=_A , eos_token_id=_A , **_A ) _UpperCamelCase = vocab_size _UpperCamelCase = max_position_embeddings _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = rotary_pct _UpperCamelCase = rotary_emb_base _UpperCamelCase = attention_dropout _UpperCamelCase = hidden_dropout _UpperCamelCase = classifier_dropout _UpperCamelCase = initializer_range _UpperCamelCase = layer_norm_eps _UpperCamelCase = use_cache _UpperCamelCase = tie_word_embeddings _UpperCamelCase = use_parallel_residual _UpperCamelCase = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( '''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' ) def UpperCamelCase_ ( self : str ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _A ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F"""got {self.rope_scaling}""" ) _UpperCamelCase = self.rope_scaling.get('''type''' , _A ) _UpperCamelCase = self.rope_scaling.get('''factor''' , _A ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}""" ) if rope_scaling_factor is None or not isinstance(_A , _A ) or rope_scaling_factor <= 1.0: raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
71
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _lowerCAmelCase = logging.getLogger(__name__) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether tp freeze the encoder."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) UpperCAmelCase = field( default="summarization", metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"}, ) UpperCAmelCase = field( default=1024, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=128, metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field(default=-1, metadata={"help": "# training examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# validation examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# test examples. -1 means use all."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Source language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Target language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "# num_beams to use for evaluation."} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."}, ) def _snake_case ( __snake_case , __snake_case , __snake_case ): logger.info(f"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(f""" {key} = {metrics[key]}""" ) save_json(__snake_case , os.path.join(__snake_case , f"""{split}_results.json""" ) ) def _snake_case ( ): # 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. _UpperCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_args_into_dataclasses() check_output_dir(__snake_case ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , __snake_case ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _UpperCamelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _UpperCamelCase = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(__snake_case , __snake_case , __snake_case ): assert hasattr(__snake_case , __snake_case ), f"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(__snake_case , __snake_case , getattr(__snake_case , __snake_case ) ) _UpperCamelCase = 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 , ) _UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=__snake_case , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(__snake_case , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: _UpperCamelCase = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(__snake_case , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(__snake_case , __snake_case ): _UpperCamelCase = tokenizer.lang_code_to_id[data_args.tgt_lang] else: _UpperCamelCase = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(__snake_case ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) _UpperCamelCase = SeqaSeqDataset # Get datasets _UpperCamelCase = ( dataset_class( __snake_case , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer _UpperCamelCase = ( build_compute_metrics_fn(data_args.task , __snake_case ) if training_args.predict_with_generate else None ) _UpperCamelCase = SeqaSeqTrainer( model=__snake_case , args=__snake_case , data_args=__snake_case , train_dataset=__snake_case , eval_dataset=__snake_case , data_collator=SeqaSeqDataCollator( __snake_case , __snake_case , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=__snake_case , tokenizer=__snake_case , ) _UpperCamelCase = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) _UpperCamelCase = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) _UpperCamelCase = train_result.metrics _UpperCamelCase = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) _UpperCamelCase = trainer.evaluate(metric_key_prefix='''val''' ) _UpperCamelCase = data_args.n_val _UpperCamelCase = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.do_predict: logger.info('''*** Predict ***''' ) _UpperCamelCase = trainer.predict(test_dataset=__snake_case , metric_key_prefix='''test''' ) _UpperCamelCase = test_output.metrics _UpperCamelCase = data_args.n_test if trainer.is_world_process_zero(): _UpperCamelCase = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.predict_with_generate: _UpperCamelCase = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=__snake_case , clean_up_tokenization_spaces=__snake_case ) _UpperCamelCase = lmap(str.strip , __snake_case ) write_txt_file(__snake_case , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(__snake_case , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def _snake_case ( __snake_case ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
71
from ..utils import DummyObject, requires_backends class lowerCAmelCase_ ( metaclass=__lowercase ): UpperCAmelCase = ["keras_nlp"] def __init__( self : Any , *_A : Dict , **_A : List[str] ): requires_backends(self , ['''keras_nlp'''] )
71
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "timm_backbone" def __init__( self : int , _A : Optional[int]=None , _A : int=3 , _A : Optional[Any]=True , _A : str=True , _A : List[str]=None , **_A : Union[str, Any] , ): super().__init__(**_A ) _UpperCamelCase = backbone _UpperCamelCase = num_channels _UpperCamelCase = features_only _UpperCamelCase = use_pretrained_backbone _UpperCamelCase = True _UpperCamelCase = out_indices if out_indices is not None else (-1,)
71
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig _lowerCAmelCase = logging.get_logger(__name__) # General docstring _lowerCAmelCase = "RegNetConfig" # Base docstring _lowerCAmelCase = "facebook/regnet-y-040" _lowerCAmelCase = [1, 1_088, 7, 7] # Image classification docstring _lowerCAmelCase = "facebook/regnet-y-040" _lowerCAmelCase = "tabby, tabby cat" _lowerCAmelCase = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : str , _A : int , _A : int = 3 , _A : int = 1 , _A : int = 1 , _A : Optional[str] = "relu" , **_A : Any , ): super().__init__(**_A ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb _UpperCamelCase = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) _UpperCamelCase = tf.keras.layers.ConvaD( filters=_A , kernel_size=_A , strides=_A , padding='''VALID''' , groups=_A , use_bias=_A , name='''convolution''' , ) _UpperCamelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) _UpperCamelCase = ACTaFN[activation] if activation is not None else tf.identity def UpperCamelCase_ ( self : Any , _A : Any ): _UpperCamelCase = self.convolution(self.padding(_A ) ) _UpperCamelCase = self.normalization(_A ) _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] , _A : RegNetConfig , **_A : Any ): super().__init__(**_A ) _UpperCamelCase = config.num_channels _UpperCamelCase = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='''embedder''' , ) def UpperCamelCase_ ( self : List[str] , _A : Optional[int] ): _UpperCamelCase = shape_list(_A )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) _UpperCamelCase = tf.transpose(_A , perm=(0, 2, 3, 1) ) _UpperCamelCase = self.embedder(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : str , _A : int , _A : int = 2 , **_A : Optional[Any] ): super().__init__(**_A ) _UpperCamelCase = tf.keras.layers.ConvaD( filters=_A , kernel_size=1 , strides=_A , use_bias=_A , name='''convolution''' ) _UpperCamelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) def UpperCamelCase_ ( self : str , _A : tf.Tensor , _A : bool = False ): return self.normalization(self.convolution(_A ) , training=_A ) class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Dict , _A : int , _A : int , **_A : Dict ): super().__init__(**_A ) _UpperCamelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_A , name='''pooler''' ) _UpperCamelCase = [ tf.keras.layers.ConvaD(filters=_A , kernel_size=1 , activation='''relu''' , name='''attention.0''' ), tf.keras.layers.ConvaD(filters=_A , kernel_size=1 , activation='''sigmoid''' , name='''attention.2''' ), ] def UpperCamelCase_ ( self : List[str] , _A : List[Any] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] _UpperCamelCase = self.pooler(_A ) for layer_module in self.attention: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = hidden_state * pooled return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , _A : int , _A : int , _A : int = 1 , **_A : str ): super().__init__(**_A ) _UpperCamelCase = in_channels != out_channels or stride != 1 _UpperCamelCase = max(1 , out_channels // config.groups_width ) _UpperCamelCase = ( TFRegNetShortCut(_A , stride=_A , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. _UpperCamelCase = [ TFRegNetConvLayer(_A , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( _A , stride=_A , groups=_A , activation=config.hidden_act , name='''layer.1''' ), TFRegNetConvLayer(_A , kernel_size=1 , activation=_A , name='''layer.2''' ), ] _UpperCamelCase = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Dict , _A : Tuple ): _UpperCamelCase = hidden_state for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = self.shortcut(_A ) hidden_state += residual _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , _A : int , _A : int , _A : int = 1 , **_A : int ): super().__init__(**_A ) _UpperCamelCase = in_channels != out_channels or stride != 1 _UpperCamelCase = max(1 , out_channels // config.groups_width ) _UpperCamelCase = ( TFRegNetShortCut(_A , stride=_A , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) _UpperCamelCase = [ TFRegNetConvLayer(_A , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( _A , stride=_A , groups=_A , activation=config.hidden_act , name='''layer.1''' ), TFRegNetSELayer(_A , reduced_channels=int(round(in_channels / 4 ) ) , name='''layer.2''' ), TFRegNetConvLayer(_A , kernel_size=1 , activation=_A , name='''layer.3''' ), ] _UpperCamelCase = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Tuple , _A : List[Any] ): _UpperCamelCase = hidden_state for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = self.shortcut(_A ) hidden_state += residual _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Tuple , _A : RegNetConfig , _A : int , _A : int , _A : int = 2 , _A : int = 2 , **_A : Union[str, Any] ): super().__init__(**_A ) _UpperCamelCase = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer _UpperCamelCase = [ # downsampling is done in the first layer with stride of 2 layer(_A , _A , _A , stride=_A , name='''layers.0''' ), *[layer(_A , _A , _A , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCamelCase_ ( self : Union[str, Any] , _A : Optional[int] ): for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , **_A : List[str] ): super().__init__(**_A ) _UpperCamelCase = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( _A , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='''stages.0''' , ) ) _UpperCamelCase = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(_A , config.depths[1:] ) ): self.stages.append(TFRegNetStage(_A , _A , _A , depth=_A , name=F"""stages.{i+1}""" ) ) def UpperCamelCase_ ( self : Optional[int] , _A : tf.Tensor , _A : bool = False , _A : bool = True ): _UpperCamelCase = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _UpperCamelCase = hidden_states + (hidden_state,) _UpperCamelCase = stage_module(_A ) if output_hidden_states: _UpperCamelCase = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=_A , hidden_states=_A ) @keras_serializable class lowerCAmelCase_ ( tf.keras.layers.Layer ): UpperCAmelCase = RegNetConfig def __init__( self : int , _A : Tuple , **_A : int ): super().__init__(**_A ) _UpperCamelCase = config _UpperCamelCase = TFRegNetEmbeddings(_A , name='''embedder''' ) _UpperCamelCase = TFRegNetEncoder(_A , name='''encoder''' ) _UpperCamelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_A , name='''pooler''' ) @unpack_inputs def UpperCamelCase_ ( self : Optional[int] , _A : tf.Tensor , _A : Optional[bool] = None , _A : Optional[bool] = None , _A : bool = False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.embedder(_A , training=_A ) _UpperCamelCase = self.encoder( _A , output_hidden_states=_A , return_dict=_A , training=_A ) _UpperCamelCase = encoder_outputs[0] _UpperCamelCase = self.pooler(_A ) # Change to NCHW output format have uniformity in the modules _UpperCamelCase = tf.transpose(_A , perm=(0, 3, 1, 2) ) _UpperCamelCase = tf.transpose(_A , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: _UpperCamelCase = tuple([tf.transpose(_A , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_A , pooler_output=_A , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = RegNetConfig UpperCAmelCase = "regnet" UpperCAmelCase = "pixel_values" @property def UpperCamelCase_ ( self : Tuple ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} _lowerCAmelCase = r"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n" _lowerCAmelCase = r"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top.", __lowercase, ) class lowerCAmelCase_ ( __lowercase ): def __init__( self : List[Any] , _A : RegNetConfig , *_A : Optional[int] , **_A : Tuple ): super().__init__(_A , *_A , **_A ) _UpperCamelCase = TFRegNetMainLayer(_A , name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(_A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_A , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCamelCase_ ( self : Any , _A : tf.Tensor , _A : Optional[bool] = None , _A : Optional[bool] = None , _A : Optional[int]=False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.regnet( pixel_values=_A , output_hidden_states=_A , return_dict=_A , training=_A , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ", __lowercase, ) class lowerCAmelCase_ ( __lowercase, __lowercase ): def __init__( self : List[Any] , _A : RegNetConfig , *_A : Any , **_A : int ): super().__init__(_A , *_A , **_A ) _UpperCamelCase = config.num_labels _UpperCamelCase = TFRegNetMainLayer(_A , name='''regnet''' ) # classification head _UpperCamelCase = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(_A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCamelCase_ ( self : str , _A : tf.Tensor = None , _A : tf.Tensor = None , _A : bool = None , _A : bool = None , _A : Any=False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.regnet( _A , output_hidden_states=_A , return_dict=_A , training=_A ) _UpperCamelCase = outputs.pooler_output if return_dict else outputs[1] _UpperCamelCase = self.classifier[0](_A ) _UpperCamelCase = self.classifier[1](_A ) _UpperCamelCase = None if labels is None else self.hf_compute_loss(labels=_A , logits=_A ) if not return_dict: _UpperCamelCase = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=_A , logits=_A , hidden_states=outputs.hidden_states )
71
1
'''simple docstring''' import math import random from typing import Any from .hill_climbing import SearchProblem def _snake_case ( __snake_case , __snake_case = True , __snake_case = math.inf , __snake_case = -math.inf , __snake_case = math.inf , __snake_case = -math.inf , __snake_case = False , __snake_case = 100 , __snake_case = 0.01 , __snake_case = 1 , ): _UpperCamelCase = False _UpperCamelCase = search_prob _UpperCamelCase = start_temperate _UpperCamelCase = [] _UpperCamelCase = 0 _UpperCamelCase = None while not search_end: _UpperCamelCase = current_state.score() if best_state is None or current_score > best_state.score(): _UpperCamelCase = current_state scores.append(SCREAMING_SNAKE_CASE_ ) iterations += 1 _UpperCamelCase = None _UpperCamelCase = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to _UpperCamelCase = random.randint(0 , len(SCREAMING_SNAKE_CASE_ ) - 1 ) # picking a random neighbor _UpperCamelCase = neighbors.pop(SCREAMING_SNAKE_CASE_ ) _UpperCamelCase = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: _UpperCamelCase = change * -1 # in case we are finding minimum if change > 0: # improves the solution _UpperCamelCase = picked_neighbor else: _UpperCamelCase = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability _UpperCamelCase = picked_neighbor _UpperCamelCase = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor _UpperCamelCase = True else: _UpperCamelCase = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def _snake_case ( __snake_case , __snake_case ): return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) _lowerCAmelCase = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) _lowerCAmelCase = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f'and 50 > y > - 5 found via hill climbing: {local_min.score()}' ) # starting the problem with initial coordinates (12, 47) _lowerCAmelCase = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) _lowerCAmelCase = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f'and 50 > y > - 5 found via hill climbing: {local_min.score()}' ) def _snake_case ( __snake_case , __snake_case ): return (3 * x**2) - (6 * y) _lowerCAmelCase = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) _lowerCAmelCase = simulated_annealing(prob, find_max=False, visualization=True) print( "The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f'{local_min.score()}' ) _lowerCAmelCase = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) _lowerCAmelCase = simulated_annealing(prob, find_max=True, visualization=True) print( "The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f'{local_min.score()}' )
700
from sklearn.metrics import mean_squared_error import datasets _lowerCAmelCase = "\\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" _lowerCAmelCase = "\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n" _lowerCAmelCase = "\nArgs:\n predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n sample_weight: array-like of shape (n_samples,), default=None\n Sample weights.\n multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"\n Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n \"raw_values\" : Returns a full set of errors in case of multioutput input.\n\n \"uniform_average\" : Errors of all outputs are averaged with uniform weight.\n\n squared : bool, default=True\n If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n mse : mean squared error.\nExamples:\n\n >>> mse_metric = datasets.load_metric(\"mse\")\n >>> predictions = [2.5, 0.0, 2, 8]\n >>> references = [3, -0.5, 2, 7]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'mse': 0.375}\n >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n >>> print(rmse_result)\n {'mse': 0.6123724356957945}\n\n If you're using multi-dimensional lists, then set the config as follows :\n\n >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")\n >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n >>> references = [[0, 2], [-1, 2], [8, -5]]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'mse': 0.7083333333333334}\n >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {'mse': array([0.41666667, 1. ])}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): def UpperCamelCase_ ( self : Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html''' ] , ) def UpperCamelCase_ ( self : Dict ): if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value('''float''' ) ), "references": datasets.Sequence(datasets.Value('''float''' ) ), } else: return { "predictions": datasets.Value('''float''' ), "references": datasets.Value('''float''' ), } def UpperCamelCase_ ( self : Any , _A : List[Any] , _A : List[str] , _A : Dict=None , _A : List[str]="uniform_average" , _A : int=True ): _UpperCamelCase = mean_squared_error( _A , _A , sample_weight=_A , multioutput=_A , squared=_A ) return {"mse": mse}
71
0
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests _lowerCAmelCase = open # noqa: we just need to have a builtin inside this module to test it properly
701
import os import re import shutil import sys import tempfile import unittest import black _lowerCAmelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. _lowerCAmelCase = " \"\"\"\n Output class for the scheduler's step function output.\n\n Args:\n prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the\n denoising loop.\n pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n The predicted denoised sample (x_{0}) based on the model output from the current timestep.\n `pred_original_sample` can be used to preview progress or for guidance.\n \"\"\"\n\n prev_sample: torch.FloatTensor\n pred_original_sample: Optional[torch.FloatTensor] = None\n" class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Any ): _UpperCamelCase = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , '''schedulers/''' ) ) _UpperCamelCase = self.diffusers_dir shutil.copy( os.path.join(_A , '''src/diffusers/schedulers/scheduling_ddpm.py''' ) , os.path.join(self.diffusers_dir , '''schedulers/scheduling_ddpm.py''' ) , ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = '''src/diffusers''' shutil.rmtree(self.diffusers_dir ) def UpperCamelCase_ ( self : Union[str, Any] , _A : Tuple , _A : Optional[Any] , _A : Dict , _A : List[str]=None ): _UpperCamelCase = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: _UpperCamelCase = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result _UpperCamelCase = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) _UpperCamelCase = black.format_str(_A , mode=_A ) _UpperCamelCase = os.path.join(self.diffusers_dir , '''new_code.py''' ) with open(_A , '''w''' , newline='''\n''' ) as f: f.write(_A ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(_A ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=_A ) with open(_A , '''r''' ) as f: self.assertTrue(f.read() , _A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = check_copies.find_code_in_diffusers('''schedulers.scheduling_ddpm.DDPMSchedulerOutput''' ) self.assertEqual(_A , _A ) def UpperCamelCase_ ( self : Optional[Any] ): # Base copy consistency self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , REFERENCE_CODE + '''\n''' , ) # With no empty line at the end self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , _A , ) # Copy consistency with rename self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , re.sub('''DDPM''' , '''Test''' , _A ) , ) # Copy consistency with a really long name _UpperCamelCase = '''TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason''' self.check_copy_consistency( F"""# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}""" , F"""{long_class_name}SchedulerOutput""" , re.sub('''Bert''' , _A , _A ) , ) # Copy consistency with overwrite self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , _A , overwrite_result=re.sub('''DDPM''' , '''Test''' , _A ) , )
71
0
import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = 'https://openaipublic.azureedge.net/jukebox/models/' _lowerCAmelCase = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _snake_case ( __snake_case ): if key.endswith('''.model.1.bias''' ) and len(key.split('''.''' ) ) > 10: _UpperCamelCase = key.replace('''.model.1.bias''' , '''.conv1d_1.bias''' ) elif key.endswith('''.model.1.weight''' ) and len(key.split('''.''' ) ) > 10: _UpperCamelCase = key.replace('''.model.1.weight''' , '''.conv1d_1.weight''' ) elif key.endswith('''.model.3.bias''' ) and len(key.split('''.''' ) ) > 10: _UpperCamelCase = key.replace('''.model.3.bias''' , '''.conv1d_2.bias''' ) elif key.endswith('''.model.3.weight''' ) and len(key.split('''.''' ) ) > 10: _UpperCamelCase = key.replace('''.model.3.weight''' , '''.conv1d_2.weight''' ) if "conditioner_blocks.0." in key: _UpperCamelCase = key.replace('''conditioner_blocks.0''' , '''conditioner_blocks''' ) if "prime_prior" in key: _UpperCamelCase = key.replace('''prime_prior''' , '''encoder''' ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: _UpperCamelCase = key.replace('''.emb.''' , '''.''' ) if key.endswith('''k''' ): # replace vqvae.X.k with vqvae.X.codebook return key.replace('''.k''' , '''.codebook''' ) if "y_emb." in key: return key.replace('''y_emb.''' , '''metadata_embedding.''' ) if "x_emb.emb." in key: _UpperCamelCase = key.replace('''0.x_emb.emb''' , '''embed_tokens''' ) if "prime_state_ln" in key: return key.replace('''prime_state_ln''' , '''encoder.final_layer_norm''' ) if ".ln" in key: return key.replace('''.ln''' , '''.layer_norm''' ) if "_ln" in key: return key.replace('''_ln''' , '''_layer_norm''' ) if "prime_state_proj" in key: return key.replace('''prime_state_proj''' , '''encoder.proj_in''' ) if "prime_x_out" in key: return key.replace('''prime_x_out''' , '''encoder.lm_head''' ) if "prior.x_out" in key: return key.replace('''x_out''' , '''fc_proj_out''' ) if "x_emb" in key: return key.replace('''x_emb''' , '''embed_tokens''' ) return key def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = {} import re _UpperCamelCase = re.compile(R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' ) _UpperCamelCase = re.compile( R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) _UpperCamelCase = re.compile(R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' ) _UpperCamelCase = re.compile(R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' ) _UpperCamelCase = re.compile( R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) _UpperCamelCase = re.compile(R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' ) _UpperCamelCase = re.compile(R'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)''' ) _UpperCamelCase = re.compile( R'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) _UpperCamelCase = re.compile(R'''conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)''' ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): _UpperCamelCase = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = regex_match.groups() _UpperCamelCase = int(groups[2] ) * 2 + int(groups[3] ) _UpperCamelCase = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" _UpperCamelCase = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): _UpperCamelCase = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = regex_match.groups() _UpperCamelCase = int(groups[2] ) * 2 + int(groups[3] ) _UpperCamelCase = {'''1''': 1, '''3''': 2}[groups[-2]] _UpperCamelCase = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" _UpperCamelCase = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" _UpperCamelCase = prefix + resnet_block _UpperCamelCase = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): _UpperCamelCase = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = regex_match.groups() _UpperCamelCase = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" _UpperCamelCase = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): _UpperCamelCase = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = regex_match.groups() _UpperCamelCase = int(groups[2] ) * 2 + int(groups[3] ) - 2 _UpperCamelCase = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" _UpperCamelCase = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): _UpperCamelCase = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = regex_match.groups() _UpperCamelCase = int(groups[2] ) * 2 + int(groups[3] ) - 2 _UpperCamelCase = {'''1''': 1, '''3''': 2}[groups[-2]] _UpperCamelCase = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" _UpperCamelCase = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" _UpperCamelCase = prefix + resnet_block _UpperCamelCase = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): _UpperCamelCase = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = regex_match.groups() _UpperCamelCase = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" _UpperCamelCase = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): _UpperCamelCase = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = regex_match.groups() _UpperCamelCase = int(groups[1] ) * 2 + int(groups[2] ) - 2 _UpperCamelCase = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" _UpperCamelCase = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): _UpperCamelCase = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = regex_match.groups() _UpperCamelCase = int(groups[1] ) * 2 + int(groups[2] ) - 2 _UpperCamelCase = {'''1''': 1, '''3''': 2}[groups[-2]] _UpperCamelCase = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" _UpperCamelCase = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" _UpperCamelCase = prefix + resnet_block _UpperCamelCase = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): _UpperCamelCase = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = regex_match.groups() _UpperCamelCase = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" _UpperCamelCase = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: _UpperCamelCase = original_key _UpperCamelCase = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: _UpperCamelCase = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) _UpperCamelCase = original_key _UpperCamelCase = original_key _UpperCamelCase = value return new_dict @torch.no_grad() def _snake_case ( __snake_case=None , __snake_case=None ): for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): _UpperCamelCase = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , '''wb''' ).write(r.content ) _UpperCamelCase = MODEL_MAPPING[model_name.split('''/''' )[-1]] _UpperCamelCase = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = JukeboxModel(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = [] _UpperCamelCase = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): _UpperCamelCase = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )['''model'''] _UpperCamelCase = {} for k in old_dic.keys(): if k.endswith('''.b''' ): _UpperCamelCase = old_dic[k] elif k.endswith('''.w''' ): _UpperCamelCase = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: _UpperCamelCase = old_dic[k] else: _UpperCamelCase = old_dic[k] _UpperCamelCase = '''vqvae''' if i == 0 else f"""priors.{3 - i}""" _UpperCamelCase = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) _UpperCamelCase = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , '''w''' ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": _lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="jukebox-5b-lyrics", type=str, help="Name of the model you\'d like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default="jukebox-5b-lyrics-converted", type=str, help="Path to the output PyTorch model directory.", ) _lowerCAmelCase = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
702
from __future__ import annotations import math class lowerCAmelCase_ : def __init__( self : int , _A : int ): _UpperCamelCase = size # approximate the overall size of segment tree with given value _UpperCamelCase = [0 for i in range(0 , 4 * size )] # create array to store lazy update _UpperCamelCase = [0 for i in range(0 , 4 * size )] _UpperCamelCase = [0 for i in range(0 , 4 * size )] # flag for lazy update def UpperCamelCase_ ( self : str , _A : int ): return idx * 2 def UpperCamelCase_ ( self : Any , _A : int ): return idx * 2 + 1 def UpperCamelCase_ ( self : Union[str, Any] , _A : int , _A : int , _A : int , _A : list[int] ): if left_element == right_element: _UpperCamelCase = a[left_element - 1] else: _UpperCamelCase = (left_element + right_element) // 2 self.build(self.left(_A ) , _A , _A , _A ) self.build(self.right(_A ) , mid + 1 , _A , _A ) _UpperCamelCase = max( self.segment_tree[self.left(_A )] , self.segment_tree[self.right(_A )] ) def UpperCamelCase_ ( self : Tuple , _A : int , _A : int , _A : int , _A : int , _A : int , _A : int ): if self.flag[idx] is True: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = False if left_element != right_element: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = self.lazy[idx] _UpperCamelCase = True _UpperCamelCase = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: _UpperCamelCase = val if left_element != right_element: _UpperCamelCase = val _UpperCamelCase = val _UpperCamelCase = True _UpperCamelCase = True return True _UpperCamelCase = (left_element + right_element) // 2 self.update(self.left(_A ) , _A , _A , _A , _A , _A ) self.update(self.right(_A ) , mid + 1 , _A , _A , _A , _A ) _UpperCamelCase = max( self.segment_tree[self.left(_A )] , self.segment_tree[self.right(_A )] ) return True def UpperCamelCase_ ( self : Any , _A : int , _A : int , _A : int , _A : int , _A : int ): if self.flag[idx] is True: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = False if left_element != right_element: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = self.lazy[idx] _UpperCamelCase = True _UpperCamelCase = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] _UpperCamelCase = (left_element + right_element) // 2 _UpperCamelCase = self.query(self.left(_A ) , _A , _A , _A , _A ) _UpperCamelCase = self.query(self.right(_A ) , mid + 1 , _A , _A , _A ) return max(_A , _A ) def __str__( self : Tuple ): return str([self.query(1 , 1 , self.size , _A , _A ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _lowerCAmelCase = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _lowerCAmelCase = 15 _lowerCAmelCase = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
71
0
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( "stable diffusion controlnet", "0.22.0", "Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.", standard_warn=False, stacklevel=3, )
703
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase = { "configuration_jukebox": [ "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "JukeboxConfig", "JukeboxPriorConfig", "JukeboxVQVAEConfig", ], "tokenization_jukebox": ["JukeboxTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST", "JukeboxModel", "JukeboxPreTrainedModel", "JukeboxVQVAE", "JukeboxPrior", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
0
from __future__ import annotations def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = [] _UpperCamelCase = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) _UpperCamelCase = result + left + right return input_list def _snake_case ( __snake_case ): if len(_lowercase ) <= 1: return input_list _UpperCamelCase = list(_lowercase ) # iteration for two-way merging _UpperCamelCase = 2 while p <= len(_lowercase ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(_lowercase ) , _lowercase ): _UpperCamelCase = i _UpperCamelCase = i + p - 1 _UpperCamelCase = (low + high + 1) // 2 _UpperCamelCase = merge(_lowercase , _lowercase , _lowercase , _lowercase ) # final merge of last two parts if p * 2 >= len(_lowercase ): _UpperCamelCase = i _UpperCamelCase = merge(_lowercase , 0 , _lowercase , len(_lowercase ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": _lowerCAmelCase = input("Enter numbers separated by a comma:\n").strip() if user_input == "": _lowerCAmelCase = [] else: _lowerCAmelCase = [int(item.strip()) for item in user_input.split(",")] print(iter_merge_sort(unsorted))
704
import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase_ ( __lowercase ): def __init__( self : int , _A : NestedDataStructureLike[PathLike] , _A : Optional[NamedSplit] = None , _A : Optional[Features] = None , _A : str = None , _A : bool = False , _A : bool = False , _A : Optional[str] = None , _A : Optional[int] = None , **_A : str , ): super().__init__( _A , split=_A , features=_A , cache_dir=_A , keep_in_memory=_A , streaming=_A , num_proc=_A , **_A , ) _UpperCamelCase = field _UpperCamelCase = path_or_paths if isinstance(_A , _A ) else {self.split: path_or_paths} _UpperCamelCase = Json( cache_dir=_A , data_files=_A , features=_A , field=_A , **_A , ) def UpperCamelCase_ ( self : List[str] ): # Build iterable dataset if self.streaming: _UpperCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None self.builder.download_and_prepare( download_config=_A , download_mode=_A , verification_mode=_A , base_path=_A , num_proc=self.num_proc , ) _UpperCamelCase = self.builder.as_dataset( split=self.split , verification_mode=_A , in_memory=self.keep_in_memory ) return dataset class lowerCAmelCase_ : def __init__( self : Optional[Any] , _A : Dataset , _A : Union[PathLike, BinaryIO] , _A : Optional[int] = None , _A : Optional[int] = None , **_A : List[str] , ): if num_proc is not None and num_proc <= 0: raise ValueError(F"""num_proc {num_proc} must be an integer > 0.""" ) _UpperCamelCase = dataset _UpperCamelCase = path_or_buf _UpperCamelCase = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _UpperCamelCase = num_proc _UpperCamelCase = '''utf-8''' _UpperCamelCase = to_json_kwargs def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = self.to_json_kwargs.pop('''path_or_buf''' , _A ) _UpperCamelCase = self.to_json_kwargs.pop('''orient''' , '''records''' ) _UpperCamelCase = self.to_json_kwargs.pop('''lines''' , True if orient == '''records''' else False ) _UpperCamelCase = self.to_json_kwargs.pop('''index''' , False if orient in ['''split''', '''table'''] else True ) _UpperCamelCase = self.to_json_kwargs.pop('''compression''' , _A ) if compression not in [None, "infer", "gzip", "bz2", "xz"]: raise NotImplementedError(F"""`datasets` currently does not support {compression} compression""" ) if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with fsspec.open(self.path_or_buf , '''wb''' , compression=_A ) as buffer: _UpperCamelCase = self._write(file_obj=_A , orient=_A , lines=_A , index=_A , **self.to_json_kwargs ) else: if compression: raise NotImplementedError( F"""The compression parameter is not supported when writing to a buffer, but compression={compression}""" ''' was passed. Please provide a local path instead.''' ) _UpperCamelCase = self._write( file_obj=self.path_or_buf , orient=_A , lines=_A , index=_A , **self.to_json_kwargs ) return written def UpperCamelCase_ ( self : Any , _A : Optional[Any] ): _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = args _UpperCamelCase = query_table( table=self.dataset.data , key=slice(_A , offset + self.batch_size ) , indices=self.dataset._indices , ) _UpperCamelCase = batch.to_pandas().to_json( path_or_buf=_A , orient=_A , lines=_A , index=_A , **_A ) if not json_str.endswith('''\n''' ): json_str += "\n" return json_str.encode(self.encoding ) def UpperCamelCase_ ( self : int , _A : BinaryIO , _A : Dict , _A : Optional[Any] , _A : Dict , **_A : str , ): _UpperCamelCase = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating json from Arrow format''' , ): _UpperCamelCase = self._batch_json((offset, orient, lines, index, to_json_kwargs) ) written += file_obj.write(_A ) else: _UpperCamelCase , _UpperCamelCase = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for json_str in logging.tqdm( pool.imap( self._batch_json , [(offset, orient, lines, index, to_json_kwargs) for offset in range(0 , _A , _A )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating json from Arrow format''' , ): written += file_obj.write(_A ) return written
71
0
import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all LED models at https://huggingface.co/models?filter=LED _lowerCAmelCase = { "vocab_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", }, "merges_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt", }, "tokenizer_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json", }, } _lowerCAmelCase = { "allenai/led-base-16384": 16_384, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def _snake_case ( ): _UpperCamelCase = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) _UpperCamelCase = bs[:] _UpperCamelCase = 0 for b in range(2**8 ): if b not in bs: bs.append(_A ) cs.append(2**8 + n ) n += 1 _UpperCamelCase = [chr(_A ) for n in cs] return dict(zip(_A , _A ) ) def _snake_case ( __snake_case ): _UpperCamelCase = set() _UpperCamelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _UpperCamelCase = char return pairs class lowerCAmelCase_ ( lowercase__ ): UpperCAmelCase = VOCAB_FILES_NAMES UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase = ["input_ids", "attention_mask"] def __init__( self : str , _A : Optional[int] , _A : Dict , _A : Union[str, Any]="replace" , _A : Optional[Any]="<s>" , _A : int="</s>" , _A : str="</s>" , _A : List[str]="<s>" , _A : Optional[int]="<unk>" , _A : List[str]="<pad>" , _A : Union[str, Any]="<mask>" , _A : Tuple=False , **_A : Optional[Any] , ): _UpperCamelCase = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else bos_token _UpperCamelCase = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else eos_token _UpperCamelCase = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else sep_token _UpperCamelCase = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else cls_token _UpperCamelCase = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else unk_token _UpperCamelCase = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it _UpperCamelCase = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token super().__init__( errors=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , add_prefix_space=__lowerCamelCase , **__lowerCamelCase , ) with open(__lowerCamelCase , encoding='''utf-8''' ) as vocab_handle: _UpperCamelCase = json.load(__lowerCamelCase ) _UpperCamelCase = {v: k for k, v in self.encoder.items()} _UpperCamelCase = errors # how to handle errors in decoding _UpperCamelCase = bytes_to_unicode() _UpperCamelCase = {v: k for k, v in self.byte_encoder.items()} with open(__lowerCamelCase , encoding='''utf-8''' ) as merges_handle: _UpperCamelCase = merges_handle.read().split('''\n''' )[1:-1] _UpperCamelCase = [tuple(merge.split() ) for merge in bpe_merges] _UpperCamelCase = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) _UpperCamelCase = {} _UpperCamelCase = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions _UpperCamelCase = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def UpperCamelCase_ ( self : Union[str, Any] ): return len(self.encoder ) def UpperCamelCase_ ( self : Union[str, Any] ): return dict(self.encoder , **self.added_tokens_encoder ) def UpperCamelCase_ ( self : Tuple , _A : Dict ): if token in self.cache: return self.cache[token] _UpperCamelCase = tuple(__lowerCamelCase ) _UpperCamelCase = get_pairs(__lowerCamelCase ) if not pairs: return token while True: _UpperCamelCase = min(__lowerCamelCase , key=lambda _A : self.bpe_ranks.get(__lowerCamelCase , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _UpperCamelCase = bigram _UpperCamelCase = [] _UpperCamelCase = 0 while i < len(__lowerCamelCase ): try: _UpperCamelCase = word.index(__lowerCamelCase , __lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _UpperCamelCase = j if word[i] == first and i < len(__lowerCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _UpperCamelCase = tuple(__lowerCamelCase ) _UpperCamelCase = new_word if len(__lowerCamelCase ) == 1: break else: _UpperCamelCase = get_pairs(__lowerCamelCase ) _UpperCamelCase = " ".join(__lowerCamelCase ) _UpperCamelCase = word return word def UpperCamelCase_ ( self : Tuple , _A : List[Any] ): _UpperCamelCase = [] for token in re.findall(self.pat , __lowerCamelCase ): _UpperCamelCase = "".join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__lowerCamelCase ).split(''' ''' ) ) return bpe_tokens def UpperCamelCase_ ( self : Any , _A : int ): return self.encoder.get(__lowerCamelCase , self.encoder.get(self.unk_token ) ) def UpperCamelCase_ ( self : List[Any] , _A : Union[str, Any] ): return self.decoder.get(__lowerCamelCase ) def UpperCamelCase_ ( self : Union[str, Any] , _A : Tuple ): _UpperCamelCase = "".join(__lowerCamelCase ) _UpperCamelCase = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def UpperCamelCase_ ( self : Optional[int] , _A : str , _A : Optional[str] = None ): if not os.path.isdir(__lowerCamelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _UpperCamelCase = os.path.join( __lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _UpperCamelCase = os.path.join( __lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(__lowerCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__lowerCamelCase , ensure_ascii=__lowerCamelCase ) + '''\n''' ) _UpperCamelCase = 0 with open(__lowerCamelCase , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _A : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) _UpperCamelCase = token_index writer.write(''' '''.join(__lowerCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def UpperCamelCase_ ( self : int , _A : List[int] , _A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _UpperCamelCase = [self.cls_token_id] _UpperCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self : Tuple , _A : List[int] , _A : Optional[List[int]] = None , _A : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1, 1] + ([0] * len(__lowerCamelCase )) + [1] def UpperCamelCase_ ( self : List[Any] , _A : List[int] , _A : Optional[List[int]] = None ): _UpperCamelCase = [self.sep_token_id] _UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCamelCase_ ( self : List[str] , _A : int , _A : Dict=False , **_A : List[str] ): _UpperCamelCase = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__lowerCamelCase ) > 0 and not text[0].isspace()): _UpperCamelCase = " " + text return (text, kwargs) def UpperCamelCase_ ( self : Dict , _A : Union[Dict[str, EncodedInput], BatchEncoding] , _A : Optional[int] = None , _A : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , _A : Optional[int] = None , _A : Optional[bool] = None , ): _UpperCamelCase = super()._pad( encoded_inputs=__lowerCamelCase , max_length=__lowerCamelCase , padding_strategy=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , ) # Load from model defaults if return_attention_mask is None: _UpperCamelCase = "attention_mask" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: _UpperCamelCase = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. _UpperCamelCase = len(encoded_inputs['''global_attention_mask'''] ) != len(__lowerCamelCase ) if needs_to_be_padded: _UpperCamelCase = len(__lowerCamelCase ) - len(encoded_inputs['''global_attention_mask'''] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` _UpperCamelCase = ( encoded_inputs["global_attention_mask"] + [-1] * difference ) elif self.padding_side == "left": _UpperCamelCase = [-1] * difference + encoded_inputs[ "global_attention_mask" ] else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return encoded_inputs
705
import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class lowerCAmelCase_ ( enum.Enum ): UpperCAmelCase = 0 UpperCAmelCase = 1 UpperCAmelCase = 2 @add_end_docstrings(__lowercase ) class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n " def __init__( self : Tuple , *_A : List[str] , **_A : str ): super().__init__(*_A , **_A ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == '''tf''' else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. _UpperCamelCase = None if self.model.config.prefix is not None: _UpperCamelCase = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. _UpperCamelCase = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = self._sanitize_parameters(prefix=_A , **self._forward_params ) _UpperCamelCase = {**self._preprocess_params, **preprocess_params} _UpperCamelCase = {**self._forward_params, **forward_params} def UpperCamelCase_ ( self : Dict , _A : Optional[int]=None , _A : Any=None , _A : Optional[int]=None , _A : List[str]=None , _A : List[Any]=None , _A : int=None , _A : Tuple=None , _A : Optional[Any]=None , **_A : Optional[int] , ): _UpperCamelCase = {} if prefix is not None: _UpperCamelCase = prefix if prefix: _UpperCamelCase = self.tokenizer( _A , padding=_A , add_special_tokens=_A , return_tensors=self.framework ) _UpperCamelCase = prefix_inputs['''input_ids'''].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( F"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected""" ''' [None, \'hole\']''' ) _UpperCamelCase = handle_long_generation preprocess_params.update(_A ) _UpperCamelCase = generate_kwargs _UpperCamelCase = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_full_text`''' ) if return_tensors is not None: raise ValueError('''`return_full_text` is mutually exclusive with `return_tensors`''' ) _UpperCamelCase = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_tensors`''' ) _UpperCamelCase = ReturnType.TENSORS if return_type is not None: _UpperCamelCase = return_type if clean_up_tokenization_spaces is not None: _UpperCamelCase = clean_up_tokenization_spaces if stop_sequence is not None: _UpperCamelCase = self.tokenizer.encode(_A , add_special_tokens=_A ) if len(_A ) > 1: warnings.warn( '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of''' ''' the stop sequence will be used as the stop sequence string in the interim.''' ) _UpperCamelCase = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCamelCase_ ( self : int , *_A : Union[str, Any] , **_A : Union[str, Any] ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({'''add_space_before_punct_symbol''': True} ) return super()._parse_and_tokenize(*_A , **_A ) def __call__( self : List[str] , _A : str , **_A : Any ): return super().__call__(_A , **_A ) def UpperCamelCase_ ( self : Optional[Any] , _A : List[str] , _A : int="" , _A : Optional[Any]=None , **_A : Optional[Any] ): _UpperCamelCase = self.tokenizer( prefix + prompt_text , padding=_A , add_special_tokens=_A , return_tensors=self.framework ) _UpperCamelCase = prompt_text if handle_long_generation == "hole": _UpperCamelCase = inputs['''input_ids'''].shape[-1] if "max_new_tokens" in generate_kwargs: _UpperCamelCase = generate_kwargs['''max_new_tokens'''] else: _UpperCamelCase = generate_kwargs.get('''max_length''' , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError('''We cannot infer how many new tokens are expected''' ) if cur_len + new_tokens > self.tokenizer.model_max_length: _UpperCamelCase = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( '''We cannot use `hole` to handle this generation the number of desired tokens exceeds the''' ''' models max length''' ) _UpperCamelCase = inputs['''input_ids'''][:, -keep_length:] if "attention_mask" in inputs: _UpperCamelCase = inputs['''attention_mask'''][:, -keep_length:] return inputs def UpperCamelCase_ ( self : Dict , _A : Optional[int] , **_A : str ): _UpperCamelCase = model_inputs['''input_ids'''] _UpperCamelCase = model_inputs.get('''attention_mask''' , _A ) # Allow empty prompts if input_ids.shape[1] == 0: _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = 1 else: _UpperCamelCase = input_ids.shape[0] _UpperCamelCase = model_inputs.pop('''prompt_text''' ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. _UpperCamelCase = generate_kwargs.pop('''prefix_length''' , 0 ) if prefix_length > 0: _UpperCamelCase = '''max_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].max_new_tokens is not None ) if not has_max_new_tokens: _UpperCamelCase = generate_kwargs.get('''max_length''' ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length _UpperCamelCase = '''min_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL _UpperCamelCase = self.model.generate(input_ids=_A , attention_mask=_A , **_A ) _UpperCamelCase = generated_sequence.shape[0] if self.framework == "pt": _UpperCamelCase = generated_sequence.reshape(_A , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": _UpperCamelCase = tf.reshape(_A , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def UpperCamelCase_ ( self : List[str] , _A : Dict , _A : Optional[Any]=ReturnType.FULL_TEXT , _A : Dict=True ): _UpperCamelCase = model_outputs['''generated_sequence'''][0] _UpperCamelCase = model_outputs['''input_ids'''] _UpperCamelCase = model_outputs['''prompt_text'''] _UpperCamelCase = generated_sequence.numpy().tolist() _UpperCamelCase = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: _UpperCamelCase = {'''generated_token_ids''': sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text _UpperCamelCase = self.tokenizer.decode( _A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: _UpperCamelCase = 0 else: _UpperCamelCase = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_A , clean_up_tokenization_spaces=_A , ) ) if return_type == ReturnType.FULL_TEXT: _UpperCamelCase = prompt_text + text[prompt_length:] else: _UpperCamelCase = text[prompt_length:] _UpperCamelCase = {'''generated_text''': all_text} records.append(_A ) return records
71
0
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ ( __lowerCamelCase ): def __init__( self : Optional[Any] , _A : Optional[int] , _A : Optional[int]=13 , _A : Optional[int]=7 , _A : Any=True , _A : List[Any]=True , _A : Tuple=True , _A : Union[str, Any]=True , _A : str=True , _A : Optional[Any]=False , _A : List[Any]=False , _A : Optional[Any]=False , _A : Optional[int]=2 , _A : int=99 , _A : List[str]=0 , _A : List[str]=32 , _A : int=5 , _A : Any=4 , _A : Dict=0.1 , _A : int=0.1 , _A : List[str]=512 , _A : Tuple=12 , _A : str=2 , _A : Tuple=0.02 , _A : Any=3 , _A : Optional[int]=4 , _A : Union[str, Any]="last" , _A : Any=None , _A : int=None , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_lengths _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = gelu_activation _UpperCamelCase = sinusoidal_embeddings _UpperCamelCase = causal _UpperCamelCase = asm _UpperCamelCase = n_langs _UpperCamelCase = vocab_size _UpperCamelCase = n_special _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _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 = summary_type _UpperCamelCase = use_proj _UpperCamelCase = scope def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase = None if self.use_input_lengths: _UpperCamelCase = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) _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] , 2 ).float() _UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) _UpperCamelCase = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def UpperCamelCase_ ( self : Union[str, Any] ): return FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , ) def UpperCamelCase_ ( self : Any , _A : Tuple , _A : str , _A : int , _A : Dict , _A : List[str] , _A : str , _A : str , _A : List[Any] , _A : Any , ): _UpperCamelCase = FlaubertModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _UpperCamelCase = model(UpperCAmelCase_ , lengths=UpperCAmelCase_ , langs=UpperCAmelCase_ ) _UpperCamelCase = model(UpperCAmelCase_ , langs=UpperCAmelCase_ ) _UpperCamelCase = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : str , _A : Dict , _A : Optional[int] , _A : Tuple , _A : int , _A : int , _A : List[Any] , _A : Any , _A : List[str] , _A : Dict , ): _UpperCamelCase = FlaubertWithLMHeadModel(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _UpperCamelCase = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self : List[str] , _A : List[Any] , _A : str , _A : Dict , _A : int , _A : Dict , _A : List[Any] , _A : Any , _A : Tuple , _A : Optional[int] , ): _UpperCamelCase = FlaubertForQuestionAnsweringSimple(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _UpperCamelCase = model(UpperCAmelCase_ ) _UpperCamelCase = model(UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self : int , _A : Optional[Any] , _A : Union[str, Any] , _A : List[str] , _A : Tuple , _A : Optional[Any] , _A : Any , _A : str , _A : Union[str, Any] , _A : List[str] , ): _UpperCamelCase = FlaubertForQuestionAnswering(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _UpperCamelCase = model(UpperCAmelCase_ ) _UpperCamelCase = model( UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , cls_index=UpperCAmelCase_ , is_impossible=UpperCAmelCase_ , p_mask=UpperCAmelCase_ , ) _UpperCamelCase = model( UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , cls_index=UpperCAmelCase_ , is_impossible=UpperCAmelCase_ , ) (_UpperCamelCase ) = result_with_labels.to_tuple() _UpperCamelCase = model(UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ ) (_UpperCamelCase ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def UpperCamelCase_ ( self : Optional[int] , _A : Optional[int] , _A : Optional[int] , _A : int , _A : List[str] , _A : Dict , _A : Optional[int] , _A : List[str] , _A : str , _A : int , ): _UpperCamelCase = FlaubertForSequenceClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _UpperCamelCase = model(UpperCAmelCase_ ) _UpperCamelCase = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self : Optional[int] , _A : int , _A : int , _A : Tuple , _A : List[Any] , _A : List[str] , _A : Dict , _A : Tuple , _A : List[str] , _A : Optional[Any] , ): _UpperCamelCase = self.num_labels _UpperCamelCase = FlaubertForTokenClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _UpperCamelCase = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Tuple , _A : Optional[Any] , _A : Tuple , _A : Any , _A : str , _A : Union[str, Any] , _A : Dict , _A : List[Any] , _A : Tuple , _A : int , ): _UpperCamelCase = self.num_choices _UpperCamelCase = FlaubertForMultipleChoice(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() _UpperCamelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _UpperCamelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _UpperCamelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _UpperCamelCase = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.prepare_config_and_inputs() ( _UpperCamelCase ) = config_and_inputs _UpperCamelCase = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase_ ( __lowerCamelCase, __lowerCamelCase, unittest.TestCase ): UpperCAmelCase = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) UpperCAmelCase = ( { "feature-extraction": FlaubertModel, "fill-mask": FlaubertWithLMHeadModel, "question-answering": FlaubertForQuestionAnsweringSimple, "text-classification": FlaubertForSequenceClassification, "token-classification": FlaubertForTokenClassification, "zero-shot": FlaubertForSequenceClassification, } if is_torch_available() else {} ) def UpperCamelCase_ ( self : Tuple , _A : str , _A : Any , _A : Optional[int] , _A : List[str] , _A : Union[str, Any] ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('''Fast''' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def UpperCamelCase_ ( self : Optional[Any] , _A : Optional[Any] , _A : Optional[Any] , _A : Union[str, Any]=False ): _UpperCamelCase = super()._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": _UpperCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_ ) _UpperCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_ ) return inputs_dict def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = FlaubertModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=UpperCAmelCase_ , emb_dim=37 ) def UpperCamelCase_ ( self : Optional[Any] ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : str ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*UpperCAmelCase_ ) def UpperCamelCase_ ( self : Any ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*UpperCAmelCase_ ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*UpperCAmelCase_ ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*UpperCAmelCase_ ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*UpperCAmelCase_ ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*UpperCAmelCase_ ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*UpperCAmelCase_ ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase = FlaubertModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @slow @require_torch_gpu def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return _UpperCamelCase = True _UpperCamelCase = model_class(config=UpperCAmelCase_ ) _UpperCamelCase = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) _UpperCamelCase = torch.jit.trace( UpperCAmelCase_ , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCAmelCase_ , os.path.join(UpperCAmelCase_ , '''traced_model.pt''' ) ) _UpperCamelCase = torch.jit.load(os.path.join(UpperCAmelCase_ , '''traced_model.pt''' ) , map_location=UpperCAmelCase_ ) loaded(inputs_dict['''input_ids'''].to(UpperCAmelCase_ ) , inputs_dict['''attention_mask'''].to(UpperCAmelCase_ ) ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = FlaubertModel.from_pretrained('''flaubert/flaubert_base_cased''' ) _UpperCamelCase = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) with torch.no_grad(): _UpperCamelCase = model(UpperCAmelCase_ )[0] _UpperCamelCase = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , UpperCAmelCase_ ) _UpperCamelCase = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase_ , atol=1e-4 ) )
706
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : Any ): _UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=_A ).to(_A ) _UpperCamelCase = AutoTokenizer.from_pretrained('''google/mt5-small''' ) _UpperCamelCase = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids _UpperCamelCase = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids _UpperCamelCase = model(input_ids.to(_A ) , labels=labels.to(_A ) ).loss _UpperCamelCase = -(labels.shape[-1] * loss.item()) _UpperCamelCase = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
71
0
import math def _snake_case ( __snake_case , __snake_case ): if ( not isinstance(__snake_case , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('''power_factor must be a valid float value between -1 and 1.''' ) return apparent_power * power_factor def _snake_case ( __snake_case , __snake_case ): if ( not isinstance(__snake_case , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('''power_factor must be a valid float value between -1 and 1.''' ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
707
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _lowerCAmelCase = logging.getLogger(__name__) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether tp freeze the encoder."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) UpperCAmelCase = field( default="summarization", metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"}, ) UpperCAmelCase = field( default=1024, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=128, metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field(default=-1, metadata={"help": "# training examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# validation examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# test examples. -1 means use all."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Source language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Target language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "# num_beams to use for evaluation."} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."}, ) def _snake_case ( __snake_case , __snake_case , __snake_case ): logger.info(f"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(f""" {key} = {metrics[key]}""" ) save_json(__snake_case , os.path.join(__snake_case , f"""{split}_results.json""" ) ) def _snake_case ( ): # 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. _UpperCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_args_into_dataclasses() check_output_dir(__snake_case ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , __snake_case ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _UpperCamelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _UpperCamelCase = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(__snake_case , __snake_case , __snake_case ): assert hasattr(__snake_case , __snake_case ), f"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(__snake_case , __snake_case , getattr(__snake_case , __snake_case ) ) _UpperCamelCase = 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 , ) _UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=__snake_case , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(__snake_case , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: _UpperCamelCase = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(__snake_case , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(__snake_case , __snake_case ): _UpperCamelCase = tokenizer.lang_code_to_id[data_args.tgt_lang] else: _UpperCamelCase = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(__snake_case ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) _UpperCamelCase = SeqaSeqDataset # Get datasets _UpperCamelCase = ( dataset_class( __snake_case , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer _UpperCamelCase = ( build_compute_metrics_fn(data_args.task , __snake_case ) if training_args.predict_with_generate else None ) _UpperCamelCase = SeqaSeqTrainer( model=__snake_case , args=__snake_case , data_args=__snake_case , train_dataset=__snake_case , eval_dataset=__snake_case , data_collator=SeqaSeqDataCollator( __snake_case , __snake_case , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=__snake_case , tokenizer=__snake_case , ) _UpperCamelCase = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) _UpperCamelCase = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) _UpperCamelCase = train_result.metrics _UpperCamelCase = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) _UpperCamelCase = trainer.evaluate(metric_key_prefix='''val''' ) _UpperCamelCase = data_args.n_val _UpperCamelCase = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.do_predict: logger.info('''*** Predict ***''' ) _UpperCamelCase = trainer.predict(test_dataset=__snake_case , metric_key_prefix='''test''' ) _UpperCamelCase = test_output.metrics _UpperCamelCase = data_args.n_test if trainer.is_world_process_zero(): _UpperCamelCase = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.predict_with_generate: _UpperCamelCase = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=__snake_case , clean_up_tokenization_spaces=__snake_case ) _UpperCamelCase = lmap(str.strip , __snake_case ) write_txt_file(__snake_case , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(__snake_case , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def _snake_case ( __snake_case ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
71
0
class lowerCAmelCase_ : def __init__( self : List[Any] , _A : list ): _UpperCamelCase = set_counts _UpperCamelCase = max(_A ) _UpperCamelCase = len(_A ) _UpperCamelCase = [1] * num_sets _UpperCamelCase = list(range(_A ) ) def UpperCamelCase_ ( self : Optional[int] , _A : int , _A : int ): _UpperCamelCase = self.get_parent(_A ) _UpperCamelCase = self.get_parent(_A ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] _UpperCamelCase = 0 _UpperCamelCase = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 _UpperCamelCase = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] _UpperCamelCase = 0 _UpperCamelCase = src_parent _UpperCamelCase = self.set_counts[src_parent] _UpperCamelCase = max(self.max_set , _A ) return True def UpperCamelCase_ ( self : int , _A : int ): if self.parents[disj_set] == disj_set: return disj_set _UpperCamelCase = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
708
from __future__ import annotations import typing from collections import Counter def _snake_case ( __snake_case ): _UpperCamelCase = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(__snake_case , max_perimeter + 1 ): _UpperCamelCase = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__snake_case ): _UpperCamelCase = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _snake_case ( __snake_case = 1000 ): _UpperCamelCase = pythagorean_triple(__snake_case ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'Perimeter {solution()} has maximum solutions')
71
0
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer _lowerCAmelCase = ['bert-base-uncased', 'bert-base-cased'] _lowerCAmelCase = 'hf-internal-testing/tiny-bert-tf-only' if is_tf_available(): class lowerCAmelCase_ ( tf.keras.Model ): def __init__( self : str , _A : str ): super().__init__() _UpperCamelCase = tokenizer _UpperCamelCase = AutoConfig.from_pretrained(_lowerCAmelCase ) _UpperCamelCase = TFAutoModel.from_config(_lowerCAmelCase ) def UpperCamelCase_ ( self : Any , _A : List[str] ): _UpperCamelCase = self.tokenizer(_lowerCAmelCase ) _UpperCamelCase = self.bert(**_lowerCAmelCase ) return out["pooler_output"] @require_tf @require_tensorflow_text class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : str ): super().setUp() _UpperCamelCase = [ BertTokenizer.from_pretrained(_lowerCAmelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false _UpperCamelCase = [TFBertTokenizer.from_pretrained(_lowerCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(_lowerCAmelCase , use_fast_bert_tokenizer=_lowerCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) _UpperCamelCase = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] _UpperCamelCase = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def UpperCamelCase_ ( self : str ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): _UpperCamelCase = tokenizer(_lowerCAmelCase , return_tensors='''tf''' , padding='''longest''' ) _UpperCamelCase = tf_tokenizer(_lowerCAmelCase ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def UpperCamelCase_ ( self : Dict ): for tf_tokenizer in self.tf_tokenizers: _UpperCamelCase = tf_tokenizer(self.paired_sentences ) _UpperCamelCase = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def UpperCamelCase_ ( self : Any ): for tf_tokenizer in self.tf_tokenizers: _UpperCamelCase = tf.function(_lowerCAmelCase ) for test_inputs in (self.test_sentences, self.paired_sentences): _UpperCamelCase = tf.constant(_lowerCAmelCase ) _UpperCamelCase = compiled_tokenizer(_lowerCAmelCase ) _UpperCamelCase = tf_tokenizer(_lowerCAmelCase ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def UpperCamelCase_ ( self : List[str] ): for tf_tokenizer in self.tf_tokenizers: _UpperCamelCase = ModelToSave(tokenizer=_lowerCAmelCase ) _UpperCamelCase = tf.convert_to_tensor(self.test_sentences ) _UpperCamelCase = model(_lowerCAmelCase ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: _UpperCamelCase = Path(_lowerCAmelCase ) / '''saved.model''' model.save(_lowerCAmelCase ) _UpperCamelCase = tf.keras.models.load_model(_lowerCAmelCase ) _UpperCamelCase = loaded_model(_lowerCAmelCase ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1e-5 )
709
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = (DPMSolverSDEScheduler,) UpperCAmelCase = 10 def UpperCamelCase_ ( self : Tuple , **_A : Union[str, Any] ): _UpperCamelCase = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''noise_sampler_seed''': 0, } config.update(**_A ) return config def UpperCamelCase_ ( self : List[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=_A ) def UpperCamelCase_ ( self : List[Any] ): for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_A , beta_end=_A ) def UpperCamelCase_ ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_A ) def UpperCamelCase_ ( self : Union[str, Any] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_8210_4492_1875 ) < 1e-2 assert abs(result_mean.item() - 0.2178_7059_6456_5277 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3521_1181_6406 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9068_9229_9652 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_1492_0043_9453 ) < 1e-2 assert abs(result_mean.item() - 0.1_6226_2890_1481_6284 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_6633_6059_5703 ) < 1e-2 assert abs(result_mean.item() - 0.1_6688_3260_0116_7297 ) < 1e-3 else: assert abs(result_sum.item() - 119.8_4875_4882_8125 ) < 1e-2 assert abs(result_mean.item() - 0.1560_5306_6253_6621 ) < 1e-3 def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps , device=_A ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter.to(_A ) * scheduler.init_noise_sigma for t in scheduler.timesteps: _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_9573_9746_0938 ) < 1e-2 assert abs(result_mean.item() - 0.2_1805_9346_0798_2635 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3536_3769_5312 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9083_8241_5771 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A , use_karras_sigmas=_A ) scheduler.set_timesteps(self.num_inference_steps , device=_A ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter.to(_A ) * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for t in scheduler.timesteps: _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_9741_3574_2188 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_6535_6445_3125 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 else: assert abs(result_sum.item() - 170.3_1352_2338_8672 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2
71
0
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split _lowerCAmelCase = datasets.load_iris() _lowerCAmelCase = np.array(data["data"]) _lowerCAmelCase = np.array(data["target"]) _lowerCAmelCase = data["target_names"] _lowerCAmelCase = train_test_split(X, y) def _snake_case ( __snake_case , __snake_case ): return np.linalg.norm(np.array(lowerCamelCase__ ) - np.array(lowerCamelCase__ ) ) def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case=5 ): _UpperCamelCase = zip(lowerCamelCase__ , lowerCamelCase__ ) # List of distances of all points from the point to be classified _UpperCamelCase = [] for data_point in data: _UpperCamelCase = euclidean_distance(data_point[0] , lowerCamelCase__ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. _UpperCamelCase = [i[1] for i in sorted(lowerCamelCase__ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified _UpperCamelCase = Counter(lowerCamelCase__ ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
710
import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class lowerCAmelCase_ : @property def UpperCamelCase_ ( self : Optional[int] ): return self.get_dummy_input() @property def UpperCamelCase_ ( self : Dict ): if self.block_type == "down": return (4, 32, 16, 16) elif self.block_type == "mid": return (4, 32, 32, 32) elif self.block_type == "up": return (4, 32, 64, 64) raise ValueError(F"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'.""" ) def UpperCamelCase_ ( self : Union[str, Any] , _A : List[str]=True , _A : Any=False , _A : Union[str, Any]=False , _A : int=False , ): _UpperCamelCase = 4 _UpperCamelCase = 32 _UpperCamelCase = (32, 32) _UpperCamelCase = torch.manual_seed(0 ) _UpperCamelCase = torch.device(_A ) _UpperCamelCase = (batch_size, num_channels) + sizes _UpperCamelCase = randn_tensor(_A , generator=_A , device=_A ) _UpperCamelCase = {'''hidden_states''': hidden_states} if include_temb: _UpperCamelCase = 128 _UpperCamelCase = randn_tensor((batch_size, temb_channels) , generator=_A , device=_A ) if include_res_hidden_states_tuple: _UpperCamelCase = torch.manual_seed(1 ) _UpperCamelCase = (randn_tensor(_A , generator=_A , device=_A ),) if include_encoder_hidden_states: _UpperCamelCase = floats_tensor((batch_size, 32, 32) ).to(_A ) if include_skip_sample: _UpperCamelCase = randn_tensor(((batch_size, 3) + sizes) , generator=_A , device=_A ) return dummy_input def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = { '''in_channels''': 32, '''out_channels''': 32, '''temb_channels''': 128, } if self.block_type == "up": _UpperCamelCase = 32 if self.block_type == "mid": init_dict.pop('''out_channels''' ) _UpperCamelCase = self.dummy_input return init_dict, inputs_dict def UpperCamelCase_ ( self : Tuple , _A : Union[str, Any] ): _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**_A ) unet_block.to(_A ) unet_block.eval() with torch.no_grad(): _UpperCamelCase = unet_block(**_A ) if isinstance(_A , _A ): _UpperCamelCase = output[0] self.assertEqual(output.shape , self.output_shape ) _UpperCamelCase = output[0, -1, -3:, -3:] _UpperCamelCase = torch.tensor(_A ).to(_A ) assert torch_all_close(output_slice.flatten() , _A , atol=5e-3 ) @unittest.skipIf(torch_device == '''mps''' , '''Training is not supported in mps''' ) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**_A ) model.to(_A ) model.train() _UpperCamelCase = model(**_A ) if isinstance(_A , _A ): _UpperCamelCase = output[0] _UpperCamelCase = torch.device(_A ) _UpperCamelCase = randn_tensor(output.shape , device=_A ) _UpperCamelCase = torch.nn.functional.mse_loss(_A , _A ) loss.backward()
71
0
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration _lowerCAmelCase = [ # tf -> hf ('/', '.'), ('layer_', 'layers.'), ('kernel', 'weight'), ('beta', 'bias'), ('gamma', 'weight'), ('pegasus', 'model'), ] _lowerCAmelCase = [ ('.output.dense', '.fc2'), ('intermediate.LayerNorm', 'final_layer_norm'), ('intermediate.dense', 'fc1'), ] _lowerCAmelCase = ( INIT_COMMON + [ ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.out_proj'), ('attention.self', 'self_attn'), ('attention.encdec.LayerNorm', 'encoder_attn_layer_norm'), ('attention.encdec_output.dense', 'encoder_attn.out_proj'), ('attention.encdec', 'encoder_attn'), ('key', 'k_proj'), ('value', 'v_proj'), ('query', 'q_proj'), ('decoder.LayerNorm', 'decoder.layernorm_embedding'), ] + END_COMMON ) _lowerCAmelCase = ( INIT_COMMON + [ ('embeddings.word_embeddings', 'shared.weight'), ('embeddings.position_embeddings', 'embed_positions.weight'), ('attention.self.LayerNorm', 'self_attn_layer_norm'), ('attention.output.dense', 'self_attn.output'), ('attention.self', 'self_attn.self'), ('encoder.LayerNorm', 'encoder.layernorm_embedding'), ] + END_COMMON ) _lowerCAmelCase = [ 'encdec/key/bias', 'encdec/query/bias', 'encdec/value/bias', 'self/key/bias', 'self/query/bias', 'self/value/bias', 'encdec_output/dense/bias', 'attention/output/dense/bias', ] def _snake_case ( __snake_case , __snake_case ): for tf_name, hf_name in patterns: _UpperCamelCase = k.replace(_lowerCAmelCase , _lowerCAmelCase ) return k def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = BigBirdPegasusConfig(**_lowerCAmelCase ) _UpperCamelCase = BigBirdPegasusForConditionalGeneration(_lowerCAmelCase ) _UpperCamelCase = torch_model.state_dict() _UpperCamelCase = {} # separating decoder weights _UpperCamelCase = {k: tf_weights[k] for k in tf_weights if k.startswith('''pegasus/decoder''' )} _UpperCamelCase = {k: tf_weights[k] for k in tf_weights if not k.startswith('''pegasus/decoder''' )} for k, v in tqdm(decoder_weights.items() , '''tf -> hf conversion''' ): _UpperCamelCase = [k.endswith(_lowerCAmelCase ) for ending in KEYS_TO_IGNORE] if any(_lowerCAmelCase ): continue _UpperCamelCase = DECODER_PATTERNS _UpperCamelCase = rename_state_dict_key(_lowerCAmelCase , _lowerCAmelCase ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): _UpperCamelCase = v.T _UpperCamelCase = torch.from_numpy(_lowerCAmelCase ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items() , '''tf -> hf conversion''' ): _UpperCamelCase = [k.endswith(_lowerCAmelCase ) for ending in KEYS_TO_IGNORE] if any(_lowerCAmelCase ): continue _UpperCamelCase = REMAINING_PATTERNS _UpperCamelCase = rename_state_dict_key(_lowerCAmelCase , _lowerCAmelCase ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['''dense''', '''query''', '''key''', '''value'''] ): _UpperCamelCase = v.T _UpperCamelCase = torch.from_numpy(_lowerCAmelCase ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" _UpperCamelCase = mapping["model.embed_positions.weight"] _UpperCamelCase = mapping.pop('''model.embed_positions.weight''' ) _UpperCamelCase = torch_model.load_state_dict(_lowerCAmelCase , strict=_lowerCAmelCase ) _UpperCamelCase = [ k for k in missing if k not in [ "final_logits_bias", "model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight", "lm_head.weight", ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def _snake_case ( __snake_case ): _UpperCamelCase = tf.train.list_variables(_lowerCAmelCase ) _UpperCamelCase = {} _UpperCamelCase = ["global_step"] for name, shape in tqdm(_lowerCAmelCase , desc='''converting tf checkpoint to dict''' ): _UpperCamelCase = any(pat in name for pat in ignore_name ) if skip_key: continue _UpperCamelCase = tf.train.load_variable(_lowerCAmelCase , _lowerCAmelCase ) _UpperCamelCase = array return tf_weights def _snake_case ( __snake_case , __snake_case , __snake_case ): _UpperCamelCase = get_tf_weights_as_numpy(_lowerCAmelCase ) _UpperCamelCase = convert_bigbird_pegasus(_lowerCAmelCase , _lowerCAmelCase ) torch_model.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": _lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("--tf_ckpt_path", type=str, help="passed to tf.train.list_variables") parser.add_argument("--save_dir", default=None, type=str, help="Path to the output PyTorch model.") _lowerCAmelCase = parser.parse_args() _lowerCAmelCase = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
711
def _snake_case ( __snake_case ): if not isinstance(__snake_case , __snake_case ): raise TypeError('''Input value must be an \'int\' type''' ) _UpperCamelCase = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
71
0
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor _lowerCAmelCase = logging.get_logger(__name__) class lowerCAmelCase_ ( UpperCamelCase_ ): def __init__( self : List[str] , *_A : int , **_A : Dict ): warnings.warn( '''The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use FlavaImageProcessor instead.''' , _a , ) super().__init__(*_a , **_a )
712
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } _lowerCAmelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): for attribute in key.split('''.''' ): _UpperCamelCase = getattr(__snake_case , __snake_case ) if weight_type is not None: _UpperCamelCase = getattr(__snake_case , __snake_case ).shape else: _UpperCamelCase = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": _UpperCamelCase = value elif weight_type == "weight_g": _UpperCamelCase = value elif weight_type == "weight_v": _UpperCamelCase = value elif weight_type == "bias": _UpperCamelCase = value else: _UpperCamelCase = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = [] _UpperCamelCase = fairseq_model.state_dict() _UpperCamelCase = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _UpperCamelCase = None for name, value in fairseq_dict.items(): _UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __snake_case , __snake_case , __snake_case , __snake_case , hf_model.config.feat_extract_norm == '''group''' , ) _UpperCamelCase = True elif name.split('''.''' )[0] == "proj": _UpperCamelCase = fairseq_model.proj _UpperCamelCase = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: _UpperCamelCase = True if "*" in mapped_key: _UpperCamelCase = name.split(__snake_case )[0].split('''.''' )[-2] _UpperCamelCase = mapped_key.replace('''*''' , __snake_case ) if "weight_g" in name: _UpperCamelCase = '''weight_g''' elif "weight_v" in name: _UpperCamelCase = '''weight_v''' elif "bias" in name: _UpperCamelCase = '''bias''' elif "weight" in name: _UpperCamelCase = '''weight''' else: _UpperCamelCase = None set_recursively(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) continue if not is_used: unused_weights.append(__snake_case ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = full_name.split('''conv_layers.''' )[-1] _UpperCamelCase = name.split('''.''' ) _UpperCamelCase = int(items[0] ) _UpperCamelCase = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__snake_case ) def _snake_case ( __snake_case ): _UpperCamelCase , _UpperCamelCase = emb.weight.shape _UpperCamelCase = nn.Linear(__snake_case , __snake_case , bias=__snake_case ) _UpperCamelCase = emb.weight.data return lin_layer def _snake_case ( __snake_case ): with open(__snake_case , '''r''' , encoding='''utf-8''' ) as f: _UpperCamelCase = f.readlines() _UpperCamelCase = [line.split(''' ''' )[0] for line in lines] _UpperCamelCase = len(__snake_case ) _UpperCamelCase = { '''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3, } vocab_dict.update(dict(zip(__snake_case , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ): _UpperCamelCase = WavaVecaConfig.from_pretrained(__snake_case ) _UpperCamelCase = SpeechaTextaConfig.from_pretrained( __snake_case , vocab_size=__snake_case , decoder_layers=__snake_case , do_stable_layer_norm=__snake_case ) _UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=__snake_case , return_attention_mask=__snake_case , ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) _UpperCamelCase = model[0].eval() # set weights for wav2vec2 encoder _UpperCamelCase = WavaVecaModel(__snake_case ) _UpperCamelCase = recursively_load_weights_wavaveca(model.encoder , __snake_case ) _UpperCamelCase = SpeechaTextaForCausalLM(__snake_case ) _UpperCamelCase , _UpperCamelCase = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__snake_case ) # set output linear layer unexpected_keys.remove('''embed_out''' ) _UpperCamelCase = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) _UpperCamelCase = SpeechEncoderDecoderModel(encoder=__snake_case , decoder=__snake_case ) _UpperCamelCase = False # add projection layer _UpperCamelCase = nn.Parameter(projection_layer.weight ) _UpperCamelCase = nn.Parameter(projection_layer.bias ) _UpperCamelCase = create_vocab_dict(__snake_case ) with open(os.path.join(__snake_case , '''vocab.json''' ) , '''w''' ) as fp: json.dump(__snake_case , __snake_case ) _UpperCamelCase = SpeechaTextaTokenizer(os.path.join(__snake_case , '''vocab.json''' ) ) tokenizer.save_pretrained(__snake_case ) _UpperCamelCase = hf_wavavec.config.to_dict() _UpperCamelCase = tokenizer.pad_token_id _UpperCamelCase = tokenizer.bos_token_id _UpperCamelCase = tokenizer.eos_token_id _UpperCamelCase = '''speech_to_text_2''' _UpperCamelCase = '''wav2vec2''' _UpperCamelCase = SpeechEncoderDecoderConfig.from_dict(__snake_case ) hf_wavavec.save_pretrained(__snake_case ) feature_extractor.save_pretrained(__snake_case ) if __name__ == "__main__": _lowerCAmelCase = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10_224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") _lowerCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
71
0
from __future__ import annotations import bisect def _snake_case ( __snake_case , __snake_case , __snake_case = 0 , __snake_case = -1 ): if hi < 0: _UpperCamelCase = len(__UpperCAmelCase ) while lo < hi: _UpperCamelCase = lo + (hi - lo) // 2 if sorted_collection[mid] < item: _UpperCamelCase = mid + 1 else: _UpperCamelCase = mid return lo def _snake_case ( __snake_case , __snake_case , __snake_case = 0 , __snake_case = -1 ): if hi < 0: _UpperCamelCase = len(__UpperCAmelCase ) while lo < hi: _UpperCamelCase = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: _UpperCamelCase = mid + 1 else: _UpperCamelCase = mid return lo def _snake_case ( __snake_case , __snake_case , __snake_case = 0 , __snake_case = -1 ): sorted_collection.insert(bisect_left(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) , __UpperCAmelCase ) def _snake_case ( __snake_case , __snake_case , __snake_case = 0 , __snake_case = -1 ): sorted_collection.insert(bisect_right(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) , __UpperCAmelCase ) def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = 0 _UpperCamelCase = len(__UpperCAmelCase ) - 1 while left <= right: _UpperCamelCase = left + (right - left) // 2 _UpperCamelCase = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: _UpperCamelCase = midpoint - 1 else: _UpperCamelCase = midpoint + 1 return None def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = bisect.bisect_left(__UpperCAmelCase , __UpperCAmelCase ) if index != len(__UpperCAmelCase ) and sorted_collection[index] == item: return index return None def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case ): if right < left: return None _UpperCamelCase = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , midpoint - 1 ) else: return binary_search_by_recursion(__UpperCAmelCase , __UpperCAmelCase , midpoint + 1 , __UpperCAmelCase ) if __name__ == "__main__": _lowerCAmelCase = input("Enter numbers separated by comma:\n").strip() _lowerCAmelCase = sorted(int(item) for item in user_input.split(",")) _lowerCAmelCase = int(input("Enter a single number to be found in the list:\n")) _lowerCAmelCase = binary_search(collection, target) if result is None: print(f'{target} was not found in {collection}.') else: print(f'{target} was found at position {result} in {collection}.')
713
from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class lowerCAmelCase_ : def __init__( self : Optional[Any] , _A : Optional[Any] , _A : List[str]=13 , _A : Union[str, Any]=7 , _A : int=True , _A : Optional[int]=True , _A : Optional[int]=True , _A : Union[str, Any]=True , _A : Optional[int]=99 , _A : Union[str, Any]=32 , _A : Dict=2 , _A : List[Any]=4 , _A : Optional[Any]=37 , _A : int="gelu" , _A : Optional[int]=0.1 , _A : str=0.1 , _A : List[str]=512 , _A : Optional[Any]=16 , _A : Optional[Any]=2 , _A : Optional[int]=0.02 , _A : str=False , _A : int=True , _A : Any="None" , _A : Dict=3 , _A : List[Any]=4 , _A : Optional[Any]=None , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_mask _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_labels _UpperCamelCase = num_choices _UpperCamelCase = relative_attention _UpperCamelCase = position_biased_input _UpperCamelCase = pos_att_type _UpperCamelCase = scope def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = None if self.use_input_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None if self.use_labels: _UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCamelCase = DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=_A , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self : Dict , _A : Tuple , _A : Tuple , _A : Union[str, Any] , _A : List[str] , _A : Optional[int] , _A : int , _A : Optional[Any] ): _UpperCamelCase = TFDebertaVaModel(config=_A ) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = [input_ids, input_mask] _UpperCamelCase = model(_A ) _UpperCamelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Dict , _A : Optional[int] , _A : Any , _A : Dict , _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any] , _A : List[str] ): _UpperCamelCase = TFDebertaVaForMaskedLM(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self : Dict , _A : Dict , _A : List[str] , _A : List[Any] , _A : List[Any] , _A : Optional[Any] , _A : Tuple , _A : int ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForSequenceClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple , _A : Dict , _A : Optional[int] , _A : Any , _A : List[Any] , _A : Dict , _A : Union[str, Any] , _A : List[str] ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForTokenClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Dict , _A : Optional[Any] , _A : Optional[int] , _A : Any , _A : List[str] , _A : str , _A : Optional[int] , _A : str ): _UpperCamelCase = TFDebertaVaForQuestionAnswering(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_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 UpperCamelCase_ ( self : Any ): _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( __lowercase, __lowercase, unittest.TestCase ): UpperCAmelCase = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) UpperCAmelCase = ( { "feature-extraction": TFDebertaVaModel, "fill-mask": TFDebertaVaForMaskedLM, "question-answering": TFDebertaVaForQuestionAnswering, "text-classification": TFDebertaVaForSequenceClassification, "token-classification": TFDebertaVaForTokenClassification, "zero-shot": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase = False UpperCAmelCase = False def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = TFDebertaVaModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_A ) @slow def UpperCamelCase_ ( self : Any ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) self.assertIsNotNone(_A ) @require_tf class lowerCAmelCase_ ( unittest.TestCase ): @unittest.skip(reason='''Model not available yet''' ) def UpperCamelCase_ ( self : List[Any] ): pass @slow def UpperCamelCase_ ( self : int ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) _UpperCamelCase = tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) _UpperCamelCase = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) _UpperCamelCase = model(_A , attention_mask=_A )[0] _UpperCamelCase = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , _A , atol=1e-4 )
71
0
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py _lowerCAmelCase = "." if __name__ == "__main__": _lowerCAmelCase = os.path.join(REPO_PATH, "utils/documentation_tests.txt") _lowerCAmelCase = [] _lowerCAmelCase = [] with open(doctest_file_path) as fp: for line in fp: _lowerCAmelCase = line.strip() _lowerCAmelCase = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: _lowerCAmelCase = "\n".join(non_existent_paths) raise ValueError(f'`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}') if all_paths != sorted(all_paths): raise ValueError("Files in `utils/documentation_tests.txt` are not in alphabetical order.")
714
def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case ): # Return True if there is node that has not iterated. _UpperCamelCase = [False] * len(__snake_case ) _UpperCamelCase = [] queue.append(__snake_case ) _UpperCamelCase = True while queue: _UpperCamelCase = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(__snake_case ) _UpperCamelCase = True _UpperCamelCase = u return visited[t] def _snake_case ( __snake_case , __snake_case , __snake_case ): # This array is filled by BFS and to store path _UpperCamelCase = [-1] * (len(__snake_case )) _UpperCamelCase = 0 while bfs(__snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = float('''Inf''' ) _UpperCamelCase = sink while s != source: # Find the minimum value in select path _UpperCamelCase = min(__snake_case , graph[parent[s]][s] ) _UpperCamelCase = parent[s] max_flow += path_flow _UpperCamelCase = sink while v != source: _UpperCamelCase = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow _UpperCamelCase = parent[v] return max_flow _lowerCAmelCase = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] _lowerCAmelCase, _lowerCAmelCase = 0, 5 print(ford_fulkerson(graph, source, sink))
71
0
import math from collections.abc import Callable def _snake_case ( __snake_case , __snake_case , __snake_case ): _UpperCamelCase = xa _UpperCamelCase = xa while True: if x_n == x_na or function(__A ) == function(__A ): raise ZeroDivisionError('''float division by zero, could not find root''' ) _UpperCamelCase = x_na - ( function(__A ) / ((function(__A ) - function(__A )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na _UpperCamelCase = x_na _UpperCamelCase = x_na def _snake_case ( __snake_case ): return math.pow(__A , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _lowerCAmelCase = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
0
import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCAmelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCAmelCase = "main" # Default branch name _lowerCAmelCase = "f2c752cfc5c0ab6f4bdec59acea69eefbee381c2" # One particular commit (not the top of `main`) _lowerCAmelCase = "aaaaaaa" # This commit does not exist, so we should 404. _lowerCAmelCase = "d9e9f15bc825e4b2c9249e9578f884bbcb5e3684" # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCAmelCase = "4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3" @contextlib.contextmanager def _snake_case ( ): print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def _snake_case ( ): print('''Bonjour!''' ) yield print('''Au revoir!''' ) class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Dict ): assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class lowerCAmelCase_ ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def UpperCamelCase_ ( self : Union[str, Any] , _A : str ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def UpperCamelCase_ ( self : int , _A : List[str] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def UpperCamelCase_ ( self : Tuple , _A : Tuple ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def UpperCamelCase_ ( self : int ): self.assertEqual(find_labels(_A ) , ['''labels'''] ) self.assertEqual(find_labels(_A ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_A ) , ['''start_positions''', '''end_positions'''] ) class lowerCAmelCase_ ( a__ ): pass self.assertEqual(find_labels(_A ) , ['''labels'''] ) @require_tf def UpperCamelCase_ ( self : Dict ): self.assertEqual(find_labels(_A ) , ['''labels'''] ) self.assertEqual(find_labels(_A ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_A ) , ['''start_positions''', '''end_positions'''] ) class lowerCAmelCase_ ( a__ ): pass self.assertEqual(find_labels(_A ) , ['''labels'''] ) @require_flax def UpperCamelCase_ ( self : str ): self.assertEqual(find_labels(_A ) , [] ) self.assertEqual(find_labels(_A ) , [] ) self.assertEqual(find_labels(_A ) , [] ) class lowerCAmelCase_ ( a__ ): pass self.assertEqual(find_labels(_A ) , [] )
716
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Any ): _UpperCamelCase = tempfile.mkdtemp() # fmt: off _UpperCamelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on _UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) _UpperCamelCase = { '''do_resize''': True, '''size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } _UpperCamelCase = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_A , _A ) def UpperCamelCase_ ( self : Tuple , **_A : Optional[Any] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : List[Any] , **_A : Union[str, Any] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : int ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _UpperCamelCase = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = self.get_image_processor() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _UpperCamelCase = self.get_image_processor(do_normalize=_A , padding_value=1.0 ) _UpperCamelCase = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = image_processor(_A , return_tensors='''np''' ) _UpperCamelCase = processor(images=_A , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = processor(text=_A ) _UpperCamelCase = tokenizer(_A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_A ): processor() def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _UpperCamelCase = processor.batch_decode(_A ) _UpperCamelCase = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A ) def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
71
0
import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from_submodules, ) from accelerate.test_utils import require_multi_gpu class lowerCAmelCase_ ( nn.Module ): def __init__( self : Any ): super().__init__() _UpperCamelCase = nn.Linear(3 , 4 ) _UpperCamelCase = nn.BatchNormad(4 ) _UpperCamelCase = nn.Linear(4 , 5 ) def UpperCamelCase_ ( self : Optional[int] , _A : List[Any] ): return self.lineara(self.batchnorm(self.lineara(__lowerCamelCase ) ) ) class lowerCAmelCase_ ( _A ): def UpperCamelCase_ ( self : Tuple , _A : List[str] , *_A : str , **_A : Optional[Any] ): return (args[0] + 1,) + args[1:], kwargs class lowerCAmelCase_ ( _A ): def UpperCamelCase_ ( self : Optional[Any] , _A : Any , _A : Tuple ): return output + 1 class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = ModelForTest() _UpperCamelCase = ModelHook() add_hook_to_module(__lowerCamelCase , __lowerCamelCase ) self.assertEqual(test_model._hf_hook , __lowerCamelCase ) self.assertTrue(hasattr(__lowerCamelCase , '''_old_forward''' ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , '''forward''' ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ['''x'''] ) remove_hook_from_module(__lowerCamelCase ) self.assertFalse(hasattr(__lowerCamelCase , '''_hf_hook''' ) ) self.assertFalse(hasattr(__lowerCamelCase , '''_old_forward''' ) ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = ModelForTest() _UpperCamelCase = ModelHook() add_hook_to_module(__lowerCamelCase , __lowerCamelCase ) add_hook_to_module(__lowerCamelCase , __lowerCamelCase , append=__lowerCamelCase ) self.assertEqual(isinstance(test_model._hf_hook , __lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(len(test_model._hf_hook.hooks ) , 2 ) self.assertTrue(hasattr(__lowerCamelCase , '''_old_forward''' ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , '''forward''' ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ['''x'''] ) remove_hook_from_module(__lowerCamelCase ) self.assertFalse(hasattr(__lowerCamelCase , '''_hf_hook''' ) ) self.assertFalse(hasattr(__lowerCamelCase , '''_old_forward''' ) ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = ModelForTest() _UpperCamelCase = torch.randn(2 , 3 ) _UpperCamelCase = test_model(x + 1 ) _UpperCamelCase = test_model(x + 2 ) _UpperCamelCase = PreForwardHook() add_hook_to_module(__lowerCamelCase , __lowerCamelCase ) _UpperCamelCase = test_model(__lowerCamelCase ) self.assertTrue(torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain _UpperCamelCase = PreForwardHook() add_hook_to_module(__lowerCamelCase , __lowerCamelCase ) _UpperCamelCase = test_model(__lowerCamelCase ) self.assertTrue(torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-5 ) ) # You need to use the sequential hook to chain two or more hooks _UpperCamelCase = SequentialHook(PreForwardHook() , PreForwardHook() ) add_hook_to_module(__lowerCamelCase , __lowerCamelCase ) _UpperCamelCase = test_model(__lowerCamelCase ) assert torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-5 ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = ModelForTest() _UpperCamelCase = torch.randn(2 , 3 ) _UpperCamelCase = test_model(__lowerCamelCase ) _UpperCamelCase = PostForwardHook() add_hook_to_module(__lowerCamelCase , __lowerCamelCase ) _UpperCamelCase = test_model(__lowerCamelCase ) self.assertTrue(torch.allclose(__lowerCamelCase , output + 1 , atol=1e-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain _UpperCamelCase = PostForwardHook() add_hook_to_module(__lowerCamelCase , __lowerCamelCase ) _UpperCamelCase = test_model(__lowerCamelCase ) self.assertTrue(torch.allclose(__lowerCamelCase , output + 1 , atol=1e-5 ) ) # You need to use the sequential hook to chain two or more hooks _UpperCamelCase = SequentialHook(PostForwardHook() , PostForwardHook() ) add_hook_to_module(__lowerCamelCase , __lowerCamelCase ) _UpperCamelCase = test_model(__lowerCamelCase ) assert torch.allclose(__lowerCamelCase , output + 2 , atol=1e-5 ) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = ModelForTest() _UpperCamelCase = torch.randn(2 , 3 ) _UpperCamelCase = test_model(__lowerCamelCase ) _UpperCamelCase = PostForwardHook() add_hook_to_module(__lowerCamelCase , __lowerCamelCase ) _UpperCamelCase = test_model(__lowerCamelCase ) self.assertTrue(torch.allclose(__lowerCamelCase , output + 1 ) ) self.assertTrue(outputa.requires_grad ) _UpperCamelCase = True _UpperCamelCase = test_model(__lowerCamelCase ) self.assertFalse(outputa.requires_grad ) @require_multi_gpu def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) # This will move each submodule on different devices add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=1 ) ) self.assertEqual(model.lineara.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device(0 ) ) self.assertEqual(model.lineara.weight.device , torch.device(1 ) ) # We can still make a forward pass. The input does not need to be on any particular device _UpperCamelCase = torch.randn(2 , 3 ) _UpperCamelCase = model(__lowerCamelCase ) self.assertEqual(output.device , torch.device(1 ) ) # We can add a general hook to put back output on same device as input. add_hook_to_module(__lowerCamelCase , AlignDevicesHook(io_same_device=__lowerCamelCase ) ) _UpperCamelCase = torch.randn(2 , 3 ).to(0 ) _UpperCamelCase = model(__lowerCamelCase ) self.assertEqual(output.device , torch.device(0 ) ) def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) # This will move each submodule on different devices _UpperCamelCase = {"execution_device": 0 if torch.cuda.is_available() else "cpu", "offload": True} add_hook_to_module(model.lineara , AlignDevicesHook(**__lowerCamelCase ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**__lowerCamelCase ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**__lowerCamelCase ) ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) # Buffers are not included in the offload by default, so are on the execution device _UpperCamelCase = torch.device(hook_kwargs['''execution_device'''] ) self.assertEqual(model.batchnorm.running_mean.device , __lowerCamelCase ) _UpperCamelCase = torch.randn(2 , 3 ) _UpperCamelCase = model(__lowerCamelCase ) self.assertEqual(output.device , __lowerCamelCase ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) # Now test with buffers included in the offload _UpperCamelCase = { "execution_device": 0 if torch.cuda.is_available() else "cpu", "offload": True, "offload_buffers": True, } add_hook_to_module(model.lineara , AlignDevicesHook(**__lowerCamelCase ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**__lowerCamelCase ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**__lowerCamelCase ) ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device('''meta''' ) ) _UpperCamelCase = torch.randn(2 , 3 ) _UpperCamelCase = model(__lowerCamelCase ) self.assertEqual(output.device , __lowerCamelCase ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) # This will move each submodule on different devices _UpperCamelCase = 0 if torch.cuda.is_available() else "cpu" attach_align_device_hook(__lowerCamelCase , execution_device=__lowerCamelCase , offload=__lowerCamelCase ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) # Buffers are not included in the offload by default, so are on the execution device _UpperCamelCase = torch.device(__lowerCamelCase ) self.assertEqual(model.batchnorm.running_mean.device , __lowerCamelCase ) _UpperCamelCase = torch.randn(2 , 3 ) _UpperCamelCase = model(__lowerCamelCase ) self.assertEqual(output.device , __lowerCamelCase ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__lowerCamelCase ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) # Now test with buffers included in the offload attach_align_device_hook(__lowerCamelCase , execution_device=__lowerCamelCase , offload=__lowerCamelCase , offload_buffers=__lowerCamelCase ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device('''meta''' ) ) _UpperCamelCase = torch.randn(2 , 3 ) _UpperCamelCase = model(__lowerCamelCase ) self.assertEqual(output.device , __lowerCamelCase ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__lowerCamelCase ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) # This will move each submodule on different devices _UpperCamelCase = 0 if torch.cuda.is_available() else "cpu" attach_align_device_hook( __lowerCamelCase , execution_device=__lowerCamelCase , offload=__lowerCamelCase , weights_map=model.state_dict() ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) # Buffers are not included in the offload by default, so are on the execution device _UpperCamelCase = torch.device(__lowerCamelCase ) self.assertEqual(model.batchnorm.running_mean.device , __lowerCamelCase ) _UpperCamelCase = torch.randn(2 , 3 ) _UpperCamelCase = model(__lowerCamelCase ) self.assertEqual(output.device , __lowerCamelCase ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__lowerCamelCase ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) # Now test with buffers included in the offload attach_align_device_hook( __lowerCamelCase , execution_device=__lowerCamelCase , offload=__lowerCamelCase , weights_map=model.state_dict() , offload_buffers=__lowerCamelCase , ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''meta''' ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device('''meta''' ) ) _UpperCamelCase = torch.randn(2 , 3 ) _UpperCamelCase = model(__lowerCamelCase ) self.assertEqual(output.device , __lowerCamelCase ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__lowerCamelCase ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.batchnorm.weight.device , torch.device('''cpu''' ) ) self.assertEqual(model.lineara.weight.device , torch.device('''cpu''' ) )
717
def _snake_case ( __snake_case , __snake_case , __snake_case ): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__snake_case , n - 1 , __snake_case ) * a) % mod else: _UpperCamelCase = binary_exponentiation(__snake_case , n / 2 , __snake_case ) return (b * b) % mod # a prime number _lowerCAmelCase = 701 _lowerCAmelCase = 1_000_000_000 _lowerCAmelCase = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
71
0
import collections import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = "▁" _lowerCAmelCase = {"vocab_file": "prophetnet.tokenizer"} _lowerCAmelCase = { "vocab_file": { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/prophetnet.tokenizer" ), } } _lowerCAmelCase = { "microsoft/xprophetnet-large-wiki100-cased": {"do_lower_case": False}, } _lowerCAmelCase = { "microsoft/xprophetnet-large-wiki100-cased": 512, } def _snake_case ( __snake_case ): _UpperCamelCase = collections.OrderedDict() with open(a_ , '''r''' , encoding='''utf-8''' ) as reader: _UpperCamelCase = reader.readlines() for index, token in enumerate(a_ ): _UpperCamelCase = token.rstrip('''\n''' ) _UpperCamelCase = index return vocab class lowerCAmelCase_ ( _UpperCAmelCase ): UpperCAmelCase = VOCAB_FILES_NAMES UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase = ["input_ids", "attention_mask"] def __init__( self : str , _A : int , _A : Tuple="[SEP]" , _A : Optional[int]="[SEP]" , _A : str="[SEP]" , _A : Union[str, Any]="[UNK]" , _A : Tuple="[PAD]" , _A : List[Any]="[CLS]" , _A : int="[MASK]" , _A : Optional[Dict[str, Any]] = None , **_A : Dict , ): _UpperCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowerCamelCase_ , eos_token=lowerCamelCase_ , sep_token=lowerCamelCase_ , unk_token=lowerCamelCase_ , pad_token=lowerCamelCase_ , cls_token=lowerCamelCase_ , mask_token=lowerCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCamelCase_ , ) try: import sentencepiece as spm except ImportError: logger.warning( '''You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece''' ''' pip install sentencepiece''' ) raise _UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(lowerCamelCase_ ) ) _UpperCamelCase = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # put special tokens and [unused] tokens into the vocab _UpperCamelCase = {'''[PAD]''': 0, '''[CLS]''': 1, '''[SEP]''': 2, '''[UNK]''': 3, '''[MASK]''': 4} for i in range(10 ): _UpperCamelCase = F"""[unused{i}]""" _UpperCamelCase = 5 + i # The first "real" token "," has position 15 in the embedding vocab and position 3 in the spm vocab _UpperCamelCase = 12 _UpperCamelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} for k in self.fairseq_tokens_to_ids.keys(): self.unique_no_split_tokens.append(lowerCamelCase_ ) def __getstate__( self : Optional[Any] ): _UpperCamelCase = self.__dict__.copy() _UpperCamelCase = None return state def __setstate__( self : Optional[int] , _A : List[str] ): _UpperCamelCase = d try: import sentencepiece as spm except ImportError: logger.warning( '''You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece''' ''' pip install sentencepiece''' ) raise # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _UpperCamelCase = {} _UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : Optional[Any] , _A : List[int] , _A : Optional[List[int]] = None , _A : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase_ , token_ids_a=lowerCamelCase_ , already_has_special_tokens=lowerCamelCase_ ) if token_ids_a is None: return ([0] * len(lowerCamelCase_ )) + [1] return ([0] * len(lowerCamelCase_ )) + [1] + ([0] * len(lowerCamelCase_ )) + [1] def UpperCamelCase_ ( self : Optional[int] , _A : List[int] , _A : Optional[List[int]] = None ): _UpperCamelCase = [self.sep_token_id] if token_ids_a is None: return len(token_ids_a + sep ) * [0] return len(token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase_ ( self : Union[str, Any] ): return len(self.sp_model ) + self.fairseq_offset def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = {self.convert_ids_to_tokens(lowerCamelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : Dict , _A : str ): return self.sp_model.encode(lowerCamelCase_ , out_type=lowerCamelCase_ ) def UpperCamelCase_ ( self : Optional[int] , _A : Any ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _UpperCamelCase = self.sp_model.PieceToId(lowerCamelCase_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def UpperCamelCase_ ( self : Dict , _A : Optional[Any] ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def UpperCamelCase_ ( self : Optional[int] , _A : Dict ): _UpperCamelCase = ''''''.join(lowerCamelCase_ ).replace(lowerCamelCase_ , ''' ''' ).strip() return out_string def UpperCamelCase_ ( self : Any , _A : str , _A : Optional[str] = None ): if not os.path.isdir(lowerCamelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _UpperCamelCase = os.path.join( lowerCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCamelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowerCamelCase_ , '''wb''' ) as fi: _UpperCamelCase = self.sp_model.serialized_model_proto() fi.write(lowerCamelCase_ ) return (out_vocab_file,) def UpperCamelCase_ ( self : Optional[Any] , _A : List[int] , _A : Optional[List[int]] = None ): if token_ids_a is None: return token_ids_a + [self.sep_token_id] _UpperCamelCase = [self.sep_token_id] return token_ids_a + sep + token_ids_a + sep
718
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = (1 - _cos) / 2 _UpperCamelCase = 1 - _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = (1 + _cos) / 2 _UpperCamelCase = -1 - _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = _sin / 2 _UpperCamelCase = 0 _UpperCamelCase = -ba _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 1 - alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = 1 + alpha * big_a _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha * big_a _UpperCamelCase = 1 + alpha / big_a _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha / big_a _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = (big_a + 1) - (big_a - 1) * _cos _UpperCamelCase = (big_a + 1) + (big_a - 1) * _cos _UpperCamelCase = (big_a - 1) - (big_a + 1) * _cos _UpperCamelCase = (big_a - 1) + (big_a + 1) * _cos _UpperCamelCase = 2 * sqrt(__snake_case ) * alpha _UpperCamelCase = big_a * (pmc + aaa) _UpperCamelCase = 2 * big_a * mpc _UpperCamelCase = big_a * (pmc - aaa) _UpperCamelCase = ppmc + aaa _UpperCamelCase = -2 * pmpc _UpperCamelCase = ppmc - aaa _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = (big_a + 1) - (big_a - 1) * _cos _UpperCamelCase = (big_a + 1) + (big_a - 1) * _cos _UpperCamelCase = (big_a - 1) - (big_a + 1) * _cos _UpperCamelCase = (big_a - 1) + (big_a + 1) * _cos _UpperCamelCase = 2 * sqrt(__snake_case ) * alpha _UpperCamelCase = big_a * (ppmc + aaa) _UpperCamelCase = -2 * big_a * pmpc _UpperCamelCase = big_a * (ppmc - aaa) _UpperCamelCase = pmc + aaa _UpperCamelCase = 2 * mpc _UpperCamelCase = pmc - aaa _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
71
0
import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib _lowerCAmelCase = get_logger() _lowerCAmelCase = None class lowerCAmelCase_ ( TensorFormatter[Mapping, "jax.Array", Mapping] ): def __init__( self : int , _A : List[str]=None , _A : Optional[int]=None , **_A : int ): super().__init__(features=__UpperCamelCase ) import jax from jaxlib.xla_client import Device if isinstance(__UpperCamelCase , __UpperCamelCase ): raise ValueError( F"""Expected {device} to be a `str` not {type(__UpperCamelCase )}, as `jaxlib.xla_extension.Device` """ '''is not serializable neither with `pickle` nor with `dill`. Instead you can surround ''' '''the device with `str()` to get its string identifier that will be internally mapped ''' '''to the actual `jaxlib.xla_extension.Device`.''' ) _UpperCamelCase = device if isinstance(__UpperCamelCase , __UpperCamelCase ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: _UpperCamelCase = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F"""Device with string identifier {self.device} not listed among the available """ F"""devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default """ F"""device: {str(jax.devices()[0] )}.""" ) _UpperCamelCase = str(jax.devices()[0] ) _UpperCamelCase = jnp_array_kwargs @staticmethod def UpperCamelCase_ ( ): import jax return {str(__UpperCamelCase ): device for device in jax.devices()} def UpperCamelCase_ ( self : Dict , _A : Any ): import jax import jax.numpy as jnp if isinstance(__UpperCamelCase , __UpperCamelCase ) and column: if all( isinstance(__UpperCamelCase , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(__UpperCamelCase , axis=0 ) return column def UpperCamelCase_ ( self : List[str] , _A : Any ): import jax import jax.numpy as jnp if isinstance(__UpperCamelCase , (str, bytes, type(__UpperCamelCase )) ): return value elif isinstance(__UpperCamelCase , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() _UpperCamelCase = {} if isinstance(__UpperCamelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: _UpperCamelCase = {'''dtype''': jnp.intaa} else: _UpperCamelCase = {'''dtype''': jnp.intaa} elif isinstance(__UpperCamelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): _UpperCamelCase = {'''dtype''': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(__UpperCamelCase , PIL.Image.Image ): _UpperCamelCase = np.asarray(__UpperCamelCase ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: _UpperCamelCase = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(__UpperCamelCase , **{**default_dtype, **self.jnp_array_kwargs} ) def UpperCamelCase_ ( self : Union[str, Any] , _A : List[str] ): import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(__UpperCamelCase , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(__UpperCamelCase , '''__array__''' ) and not isinstance(__UpperCamelCase , jax.Array ): _UpperCamelCase = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(__UpperCamelCase , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(__UpperCamelCase ) for substruct in data_struct] ) elif isinstance(__UpperCamelCase , (list, tuple) ): return self._consolidate([self.recursive_tensorize(__UpperCamelCase ) for substruct in data_struct] ) return self._tensorize(__UpperCamelCase ) def UpperCamelCase_ ( self : List[str] , _A : dict ): return map_nested(self._recursive_tensorize , __UpperCamelCase , map_list=__UpperCamelCase ) def UpperCamelCase_ ( self : Dict , _A : pa.Table ): _UpperCamelCase = self.numpy_arrow_extractor().extract_row(__UpperCamelCase ) _UpperCamelCase = self.python_features_decoder.decode_row(__UpperCamelCase ) return self.recursive_tensorize(__UpperCamelCase ) def UpperCamelCase_ ( self : Optional[int] , _A : pa.Table ): _UpperCamelCase = self.numpy_arrow_extractor().extract_column(__UpperCamelCase ) _UpperCamelCase = self.python_features_decoder.decode_column(__UpperCamelCase , pa_table.column_names[0] ) _UpperCamelCase = self.recursive_tensorize(__UpperCamelCase ) _UpperCamelCase = self._consolidate(__UpperCamelCase ) return column def UpperCamelCase_ ( self : Optional[Any] , _A : pa.Table ): _UpperCamelCase = self.numpy_arrow_extractor().extract_batch(__UpperCamelCase ) _UpperCamelCase = self.python_features_decoder.decode_batch(__UpperCamelCase ) _UpperCamelCase = self.recursive_tensorize(__UpperCamelCase ) for column_name in batch: _UpperCamelCase = self._consolidate(batch[column_name] ) return batch
719
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json", # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "gpt_neox" def __init__( self : Union[str, Any] , _A : Union[str, Any]=5_0432 , _A : List[Any]=6144 , _A : int=44 , _A : int=64 , _A : Optional[Any]=2_4576 , _A : Any="gelu" , _A : Tuple=0.25 , _A : Union[str, Any]=1_0000 , _A : Tuple=0.0 , _A : Any=0.0 , _A : int=0.1 , _A : List[str]=2048 , _A : Dict=0.02 , _A : Optional[Any]=1e-5 , _A : Tuple=True , _A : List[Any]=0 , _A : Optional[int]=2 , _A : Optional[int]=False , _A : List[Any]=True , _A : Any=None , **_A : Any , ): super().__init__(bos_token_id=_A , eos_token_id=_A , **_A ) _UpperCamelCase = vocab_size _UpperCamelCase = max_position_embeddings _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = rotary_pct _UpperCamelCase = rotary_emb_base _UpperCamelCase = attention_dropout _UpperCamelCase = hidden_dropout _UpperCamelCase = classifier_dropout _UpperCamelCase = initializer_range _UpperCamelCase = layer_norm_eps _UpperCamelCase = use_cache _UpperCamelCase = tie_word_embeddings _UpperCamelCase = use_parallel_residual _UpperCamelCase = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( '''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' ) def UpperCamelCase_ ( self : str ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _A ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' F"""got {self.rope_scaling}""" ) _UpperCamelCase = self.rope_scaling.get('''type''' , _A ) _UpperCamelCase = self.rope_scaling.get('''factor''' , _A ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"""`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}""" ) if rope_scaling_factor is None or not isinstance(_A , _A ) or rope_scaling_factor <= 1.0: raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
71
0
from itertools import product def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = sides_number _UpperCamelCase = max_face_number * dice_number _UpperCamelCase = [0] * (max_total + 1) _UpperCamelCase = 1 _UpperCamelCase = range(__snake_case , max_face_number + 1 ) for dice_numbers in product(__snake_case , repeat=__snake_case ): _UpperCamelCase = sum(__snake_case ) totals_frequencies[total] += 1 return totals_frequencies def _snake_case ( ): _UpperCamelCase = total_frequency_distribution( sides_number=4 , dice_number=9 ) _UpperCamelCase = total_frequency_distribution( sides_number=6 , dice_number=6 ) _UpperCamelCase = 0 _UpperCamelCase = 9 _UpperCamelCase = 4 * 9 _UpperCamelCase = 6 for peter_total in range(__snake_case , max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) _UpperCamelCase = (4**9) * (6**6) _UpperCamelCase = peter_wins_count / total_games_number _UpperCamelCase = round(__snake_case , ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(f'{solution() = }')
720
from ..utils import DummyObject, requires_backends class lowerCAmelCase_ ( metaclass=__lowercase ): UpperCAmelCase = ["keras_nlp"] def __init__( self : Any , *_A : Dict , **_A : List[str] ): requires_backends(self , ['''keras_nlp'''] )
71
0
def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = word.split() def justify(__snake_case , __snake_case , __snake_case ) -> str: _UpperCamelCase = max_width - width _UpperCamelCase = len(__UpperCamelCase ) if len(__UpperCamelCase ) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: _UpperCamelCase = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] _UpperCamelCase = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] _UpperCamelCase = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(__UpperCamelCase ): num_spaces_between_words_list[i] += 1 _UpperCamelCase = [] for i in range(__UpperCamelCase ): # add the word aligned_words_list.append(line[i] ) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * ''' ''' ) # just add the last word to the sentence aligned_words_list.append(line[-1] ) # join the aligned words list to form a justified line return "".join(__UpperCamelCase ) _UpperCamelCase = [] _UpperCamelCase = [] _UpperCamelCase = 0 for word in words: if width + len(__UpperCamelCase ) + len(__UpperCamelCase ) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(__UpperCamelCase ) width += len(__UpperCamelCase ) else: # justify the line and add it to result answer.append(justify(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) ) # reset new line and new width _UpperCamelCase = [word], len(__UpperCamelCase ) _UpperCamelCase = max_width - width - len(__UpperCamelCase ) answer.append(''' '''.join(__UpperCamelCase ) + (remaining_spaces + 1) * ''' ''' ) return answer if __name__ == "__main__": from doctest import testmod testmod()
721
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig _lowerCAmelCase = logging.get_logger(__name__) # General docstring _lowerCAmelCase = "RegNetConfig" # Base docstring _lowerCAmelCase = "facebook/regnet-y-040" _lowerCAmelCase = [1, 1_088, 7, 7] # Image classification docstring _lowerCAmelCase = "facebook/regnet-y-040" _lowerCAmelCase = "tabby, tabby cat" _lowerCAmelCase = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : str , _A : int , _A : int = 3 , _A : int = 1 , _A : int = 1 , _A : Optional[str] = "relu" , **_A : Any , ): super().__init__(**_A ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb _UpperCamelCase = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) _UpperCamelCase = tf.keras.layers.ConvaD( filters=_A , kernel_size=_A , strides=_A , padding='''VALID''' , groups=_A , use_bias=_A , name='''convolution''' , ) _UpperCamelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) _UpperCamelCase = ACTaFN[activation] if activation is not None else tf.identity def UpperCamelCase_ ( self : Any , _A : Any ): _UpperCamelCase = self.convolution(self.padding(_A ) ) _UpperCamelCase = self.normalization(_A ) _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Optional[Any] , _A : RegNetConfig , **_A : Any ): super().__init__(**_A ) _UpperCamelCase = config.num_channels _UpperCamelCase = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='''embedder''' , ) def UpperCamelCase_ ( self : List[str] , _A : Optional[int] ): _UpperCamelCase = shape_list(_A )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''' ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) _UpperCamelCase = tf.transpose(_A , perm=(0, 2, 3, 1) ) _UpperCamelCase = self.embedder(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : str , _A : int , _A : int = 2 , **_A : Optional[Any] ): super().__init__(**_A ) _UpperCamelCase = tf.keras.layers.ConvaD( filters=_A , kernel_size=1 , strides=_A , use_bias=_A , name='''convolution''' ) _UpperCamelCase = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='''normalization''' ) def UpperCamelCase_ ( self : str , _A : tf.Tensor , _A : bool = False ): return self.normalization(self.convolution(_A ) , training=_A ) class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Dict , _A : int , _A : int , **_A : Dict ): super().__init__(**_A ) _UpperCamelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_A , name='''pooler''' ) _UpperCamelCase = [ tf.keras.layers.ConvaD(filters=_A , kernel_size=1 , activation='''relu''' , name='''attention.0''' ), tf.keras.layers.ConvaD(filters=_A , kernel_size=1 , activation='''sigmoid''' , name='''attention.2''' ), ] def UpperCamelCase_ ( self : List[str] , _A : List[Any] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] _UpperCamelCase = self.pooler(_A ) for layer_module in self.attention: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = hidden_state * pooled return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , _A : int , _A : int , _A : int = 1 , **_A : str ): super().__init__(**_A ) _UpperCamelCase = in_channels != out_channels or stride != 1 _UpperCamelCase = max(1 , out_channels // config.groups_width ) _UpperCamelCase = ( TFRegNetShortCut(_A , stride=_A , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. _UpperCamelCase = [ TFRegNetConvLayer(_A , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( _A , stride=_A , groups=_A , activation=config.hidden_act , name='''layer.1''' ), TFRegNetConvLayer(_A , kernel_size=1 , activation=_A , name='''layer.2''' ), ] _UpperCamelCase = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Dict , _A : Tuple ): _UpperCamelCase = hidden_state for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = self.shortcut(_A ) hidden_state += residual _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , _A : int , _A : int , _A : int = 1 , **_A : int ): super().__init__(**_A ) _UpperCamelCase = in_channels != out_channels or stride != 1 _UpperCamelCase = max(1 , out_channels // config.groups_width ) _UpperCamelCase = ( TFRegNetShortCut(_A , stride=_A , name='''shortcut''' ) if should_apply_shortcut else tf.keras.layers.Activation('''linear''' , name='''shortcut''' ) ) _UpperCamelCase = [ TFRegNetConvLayer(_A , kernel_size=1 , activation=config.hidden_act , name='''layer.0''' ), TFRegNetConvLayer( _A , stride=_A , groups=_A , activation=config.hidden_act , name='''layer.1''' ), TFRegNetSELayer(_A , reduced_channels=int(round(in_channels / 4 ) ) , name='''layer.2''' ), TFRegNetConvLayer(_A , kernel_size=1 , activation=_A , name='''layer.3''' ), ] _UpperCamelCase = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Tuple , _A : List[Any] ): _UpperCamelCase = hidden_state for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) _UpperCamelCase = self.shortcut(_A ) hidden_state += residual _UpperCamelCase = self.activation(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : Tuple , _A : RegNetConfig , _A : int , _A : int , _A : int = 2 , _A : int = 2 , **_A : Union[str, Any] ): super().__init__(**_A ) _UpperCamelCase = TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer _UpperCamelCase = [ # downsampling is done in the first layer with stride of 2 layer(_A , _A , _A , stride=_A , name='''layers.0''' ), *[layer(_A , _A , _A , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCamelCase_ ( self : Union[str, Any] , _A : Optional[int] ): for layer_module in self.layers: _UpperCamelCase = layer_module(_A ) return hidden_state class lowerCAmelCase_ ( tf.keras.layers.Layer ): def __init__( self : List[Any] , _A : RegNetConfig , **_A : List[str] ): super().__init__(**_A ) _UpperCamelCase = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( _A , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='''stages.0''' , ) ) _UpperCamelCase = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(_A , config.depths[1:] ) ): self.stages.append(TFRegNetStage(_A , _A , _A , depth=_A , name=F"""stages.{i+1}""" ) ) def UpperCamelCase_ ( self : Optional[int] , _A : tf.Tensor , _A : bool = False , _A : bool = True ): _UpperCamelCase = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _UpperCamelCase = hidden_states + (hidden_state,) _UpperCamelCase = stage_module(_A ) if output_hidden_states: _UpperCamelCase = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=_A , hidden_states=_A ) @keras_serializable class lowerCAmelCase_ ( tf.keras.layers.Layer ): UpperCAmelCase = RegNetConfig def __init__( self : int , _A : Tuple , **_A : int ): super().__init__(**_A ) _UpperCamelCase = config _UpperCamelCase = TFRegNetEmbeddings(_A , name='''embedder''' ) _UpperCamelCase = TFRegNetEncoder(_A , name='''encoder''' ) _UpperCamelCase = tf.keras.layers.GlobalAveragePoolingaD(keepdims=_A , name='''pooler''' ) @unpack_inputs def UpperCamelCase_ ( self : Optional[int] , _A : tf.Tensor , _A : Optional[bool] = None , _A : Optional[bool] = None , _A : bool = False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.embedder(_A , training=_A ) _UpperCamelCase = self.encoder( _A , output_hidden_states=_A , return_dict=_A , training=_A ) _UpperCamelCase = encoder_outputs[0] _UpperCamelCase = self.pooler(_A ) # Change to NCHW output format have uniformity in the modules _UpperCamelCase = tf.transpose(_A , perm=(0, 3, 1, 2) ) _UpperCamelCase = tf.transpose(_A , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: _UpperCamelCase = tuple([tf.transpose(_A , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_A , pooler_output=_A , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = RegNetConfig UpperCAmelCase = "regnet" UpperCAmelCase = "pixel_values" @property def UpperCamelCase_ ( self : Tuple ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} _lowerCAmelCase = r"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n" _lowerCAmelCase = r"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top.", __lowercase, ) class lowerCAmelCase_ ( __lowercase ): def __init__( self : List[Any] , _A : RegNetConfig , *_A : Optional[int] , **_A : Tuple ): super().__init__(_A , *_A , **_A ) _UpperCamelCase = TFRegNetMainLayer(_A , name='''regnet''' ) @unpack_inputs @add_start_docstrings_to_model_forward(_A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_A , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCamelCase_ ( self : Any , _A : tf.Tensor , _A : Optional[bool] = None , _A : Optional[bool] = None , _A : Optional[int]=False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.regnet( pixel_values=_A , output_hidden_states=_A , return_dict=_A , training=_A , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ", __lowercase, ) class lowerCAmelCase_ ( __lowercase, __lowercase ): def __init__( self : List[Any] , _A : RegNetConfig , *_A : Any , **_A : int ): super().__init__(_A , *_A , **_A ) _UpperCamelCase = config.num_labels _UpperCamelCase = TFRegNetMainLayer(_A , name='''regnet''' ) # classification head _UpperCamelCase = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name='''classifier.1''' ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(_A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCamelCase_ ( self : str , _A : tf.Tensor = None , _A : tf.Tensor = None , _A : bool = None , _A : bool = None , _A : Any=False , ): _UpperCamelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCamelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCamelCase = self.regnet( _A , output_hidden_states=_A , return_dict=_A , training=_A ) _UpperCamelCase = outputs.pooler_output if return_dict else outputs[1] _UpperCamelCase = self.classifier[0](_A ) _UpperCamelCase = self.classifier[1](_A ) _UpperCamelCase = None if labels is None else self.hf_compute_loss(labels=_A , logits=_A ) if not return_dict: _UpperCamelCase = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=_A , logits=_A , hidden_states=outputs.hidden_states )
71
0
'''simple docstring''' def _snake_case ( __snake_case ): if len(snake_case__ ) <= 1: return lst _UpperCamelCase = 1 while i < len(snake_case__ ): if lst[i - 1] <= lst[i]: i += 1 else: _UpperCamelCase , _UpperCamelCase = lst[i], lst[i - 1] i -= 1 if i == 0: _UpperCamelCase = 1 return lst if __name__ == "__main__": _lowerCAmelCase = input("Enter numbers separated by a comma:\n").strip() _lowerCAmelCase = [int(item) for item in user_input.split(",")] print(gnome_sort(unsorted))
700
from sklearn.metrics import mean_squared_error import datasets _lowerCAmelCase = "\\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" _lowerCAmelCase = "\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n" _lowerCAmelCase = "\nArgs:\n predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n sample_weight: array-like of shape (n_samples,), default=None\n Sample weights.\n multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"\n Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n \"raw_values\" : Returns a full set of errors in case of multioutput input.\n\n \"uniform_average\" : Errors of all outputs are averaged with uniform weight.\n\n squared : bool, default=True\n If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n mse : mean squared error.\nExamples:\n\n >>> mse_metric = datasets.load_metric(\"mse\")\n >>> predictions = [2.5, 0.0, 2, 8]\n >>> references = [3, -0.5, 2, 7]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'mse': 0.375}\n >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n >>> print(rmse_result)\n {'mse': 0.6123724356957945}\n\n If you're using multi-dimensional lists, then set the config as follows :\n\n >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")\n >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n >>> references = [[0, 2], [-1, 2], [8, -5]]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'mse': 0.7083333333333334}\n >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {'mse': array([0.41666667, 1. ])}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): def UpperCamelCase_ ( self : Optional[int] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html''' ] , ) def UpperCamelCase_ ( self : Dict ): if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value('''float''' ) ), "references": datasets.Sequence(datasets.Value('''float''' ) ), } else: return { "predictions": datasets.Value('''float''' ), "references": datasets.Value('''float''' ), } def UpperCamelCase_ ( self : Any , _A : List[Any] , _A : List[str] , _A : Dict=None , _A : List[str]="uniform_average" , _A : int=True ): _UpperCamelCase = mean_squared_error( _A , _A , sample_weight=_A , multioutput=_A , squared=_A ) return {"mse": mse}
71
0
import re def _snake_case ( __snake_case ): return [char.split() for char in re.split(R'''[^ a-z A-Z 0-9 \s]''' , str_ )] def _snake_case ( __snake_case ): _UpperCamelCase = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def _snake_case ( __snake_case , __snake_case , __snake_case ): try: _UpperCamelCase = split_input(__SCREAMING_SNAKE_CASE ) if upper: _UpperCamelCase = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: _UpperCamelCase = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def _snake_case ( __snake_case ): return to_simple_case(__SCREAMING_SNAKE_CASE ) def _snake_case ( __snake_case ): try: _UpperCamelCase = to_simple_case(__SCREAMING_SNAKE_CASE ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def _snake_case ( __snake_case , __snake_case ): return to_complex_case(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''_''' ) def _snake_case ( __snake_case , __snake_case ): return to_complex_case(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , '''-''' ) if __name__ == "__main__": __import__("doctest").testmod()
701
import os import re import shutil import sys import tempfile import unittest import black _lowerCAmelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. _lowerCAmelCase = " \"\"\"\n Output class for the scheduler's step function output.\n\n Args:\n prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the\n denoising loop.\n pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n The predicted denoised sample (x_{0}) based on the model output from the current timestep.\n `pred_original_sample` can be used to preview progress or for guidance.\n \"\"\"\n\n prev_sample: torch.FloatTensor\n pred_original_sample: Optional[torch.FloatTensor] = None\n" class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Any ): _UpperCamelCase = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , '''schedulers/''' ) ) _UpperCamelCase = self.diffusers_dir shutil.copy( os.path.join(_A , '''src/diffusers/schedulers/scheduling_ddpm.py''' ) , os.path.join(self.diffusers_dir , '''schedulers/scheduling_ddpm.py''' ) , ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = '''src/diffusers''' shutil.rmtree(self.diffusers_dir ) def UpperCamelCase_ ( self : Union[str, Any] , _A : Tuple , _A : Optional[Any] , _A : Dict , _A : List[str]=None ): _UpperCamelCase = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: _UpperCamelCase = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result _UpperCamelCase = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) _UpperCamelCase = black.format_str(_A , mode=_A ) _UpperCamelCase = os.path.join(self.diffusers_dir , '''new_code.py''' ) with open(_A , '''w''' , newline='''\n''' ) as f: f.write(_A ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(_A ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=_A ) with open(_A , '''r''' ) as f: self.assertTrue(f.read() , _A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = check_copies.find_code_in_diffusers('''schedulers.scheduling_ddpm.DDPMSchedulerOutput''' ) self.assertEqual(_A , _A ) def UpperCamelCase_ ( self : Optional[Any] ): # Base copy consistency self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , REFERENCE_CODE + '''\n''' , ) # With no empty line at the end self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , _A , ) # Copy consistency with rename self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , re.sub('''DDPM''' , '''Test''' , _A ) , ) # Copy consistency with a really long name _UpperCamelCase = '''TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason''' self.check_copy_consistency( F"""# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}""" , F"""{long_class_name}SchedulerOutput""" , re.sub('''Bert''' , _A , _A ) , ) # Copy consistency with overwrite self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , _A , overwrite_result=re.sub('''DDPM''' , '''Test''' , _A ) , )
71
0
import math from numpy import inf from scipy.integrate import quad def _snake_case ( __snake_case ): if num <= 0: raise ValueError('''math domain error''' ) return quad(__snake_case , 0 , __snake_case , args=(__snake_case) )[0] def _snake_case ( __snake_case , __snake_case ): return math.pow(__snake_case , z - 1 ) * math.exp(-x ) if __name__ == "__main__": from doctest import testmod testmod()
702
from __future__ import annotations import math class lowerCAmelCase_ : def __init__( self : int , _A : int ): _UpperCamelCase = size # approximate the overall size of segment tree with given value _UpperCamelCase = [0 for i in range(0 , 4 * size )] # create array to store lazy update _UpperCamelCase = [0 for i in range(0 , 4 * size )] _UpperCamelCase = [0 for i in range(0 , 4 * size )] # flag for lazy update def UpperCamelCase_ ( self : str , _A : int ): return idx * 2 def UpperCamelCase_ ( self : Any , _A : int ): return idx * 2 + 1 def UpperCamelCase_ ( self : Union[str, Any] , _A : int , _A : int , _A : int , _A : list[int] ): if left_element == right_element: _UpperCamelCase = a[left_element - 1] else: _UpperCamelCase = (left_element + right_element) // 2 self.build(self.left(_A ) , _A , _A , _A ) self.build(self.right(_A ) , mid + 1 , _A , _A ) _UpperCamelCase = max( self.segment_tree[self.left(_A )] , self.segment_tree[self.right(_A )] ) def UpperCamelCase_ ( self : Tuple , _A : int , _A : int , _A : int , _A : int , _A : int , _A : int ): if self.flag[idx] is True: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = False if left_element != right_element: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = self.lazy[idx] _UpperCamelCase = True _UpperCamelCase = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: _UpperCamelCase = val if left_element != right_element: _UpperCamelCase = val _UpperCamelCase = val _UpperCamelCase = True _UpperCamelCase = True return True _UpperCamelCase = (left_element + right_element) // 2 self.update(self.left(_A ) , _A , _A , _A , _A , _A ) self.update(self.right(_A ) , mid + 1 , _A , _A , _A , _A ) _UpperCamelCase = max( self.segment_tree[self.left(_A )] , self.segment_tree[self.right(_A )] ) return True def UpperCamelCase_ ( self : Any , _A : int , _A : int , _A : int , _A : int , _A : int ): if self.flag[idx] is True: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = False if left_element != right_element: _UpperCamelCase = self.lazy[idx] _UpperCamelCase = self.lazy[idx] _UpperCamelCase = True _UpperCamelCase = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] _UpperCamelCase = (left_element + right_element) // 2 _UpperCamelCase = self.query(self.left(_A ) , _A , _A , _A , _A ) _UpperCamelCase = self.query(self.right(_A ) , mid + 1 , _A , _A , _A ) return max(_A , _A ) def __str__( self : Tuple ): return str([self.query(1 , 1 , self.size , _A , _A ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _lowerCAmelCase = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _lowerCAmelCase = 15 _lowerCAmelCase = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
71
0
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed _lowerCAmelCase = """true""" def _snake_case ( __snake_case , __snake_case=82 , __snake_case=16 ): set_seed(42 ) _UpperCamelCase = RegressionModel() _UpperCamelCase = deepcopy(snake_case_ ) _UpperCamelCase = RegressionDataset(length=snake_case_ ) _UpperCamelCase = DataLoader(snake_case_ , batch_size=snake_case_ ) model.to(accelerator.device ) _UpperCamelCase = accelerator.prepare(snake_case_ , snake_case_ ) return model, ddp_model, dataloader def _snake_case ( __snake_case , __snake_case=False ): _UpperCamelCase = AutoTokenizer.from_pretrained('''hf-internal-testing/mrpc-bert-base-cased''' ) _UpperCamelCase = load_dataset('''glue''' , '''mrpc''' , split='''validation''' ) def tokenize_function(__snake_case ): _UpperCamelCase = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=snake_case_ , max_length=snake_case_ ) return outputs with accelerator.main_process_first(): _UpperCamelCase = dataset.map( snake_case_ , batched=snake_case_ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) _UpperCamelCase = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(__snake_case ): if use_longest: return tokenizer.pad(snake_case_ , padding='''longest''' , return_tensors='''pt''' ) return tokenizer.pad(snake_case_ , padding='''max_length''' , max_length=128 , return_tensors='''pt''' ) return DataLoader(snake_case_ , shuffle=snake_case_ , collate_fn=snake_case_ , batch_size=16 ) def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = Accelerator(dispatch_batches=snake_case_ , split_batches=snake_case_ ) _UpperCamelCase = get_dataloader(snake_case_ , not dispatch_batches ) _UpperCamelCase = AutoModelForSequenceClassification.from_pretrained( '''hf-internal-testing/mrpc-bert-base-cased''' , return_dict=snake_case_ ) _UpperCamelCase = accelerator.prepare(snake_case_ , snake_case_ ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def _snake_case ( __snake_case , __snake_case , __snake_case ): _UpperCamelCase = [] for batch in dataloader: _UpperCamelCase = batch.values() with torch.no_grad(): _UpperCamelCase = model(snake_case_ ) _UpperCamelCase = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) _UpperCamelCase = [], [] for logit, targ in logits_and_targets: logits.append(snake_case_ ) targs.append(snake_case_ ) _UpperCamelCase = torch.cat(snake_case_ ), torch.cat(snake_case_ ) return logits, targs def _snake_case ( __snake_case , __snake_case=82 , __snake_case=False , __snake_case=False , __snake_case=16 ): _UpperCamelCase = get_basic_setup(snake_case_ , snake_case_ , snake_case_ ) _UpperCamelCase = generate_predictions(snake_case_ , snake_case_ , snake_case_ ) assert ( len(snake_case_ ) == num_samples ), f"""Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(snake_case_ )}""" def _snake_case ( __snake_case = False , __snake_case = False ): _UpperCamelCase = evaluate.load('''glue''' , '''mrpc''' ) _UpperCamelCase = get_mrpc_setup(snake_case_ , snake_case_ ) # First do baseline _UpperCamelCase = setup["no"] model.to(snake_case_ ) model.eval() for batch in dataloader: batch.to(snake_case_ ) with torch.inference_mode(): _UpperCamelCase = model(**snake_case_ ) _UpperCamelCase = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=snake_case_ , references=batch['''labels'''] ) _UpperCamelCase = metric.compute() # Then do distributed _UpperCamelCase = setup["ddp"] model.eval() for batch in dataloader: with torch.inference_mode(): _UpperCamelCase = model(**snake_case_ ) _UpperCamelCase = outputs.logits.argmax(dim=-1 ) _UpperCamelCase = batch["labels"] _UpperCamelCase = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=snake_case_ , references=snake_case_ ) _UpperCamelCase = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key] ), f"""Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n""" def _snake_case ( ): _UpperCamelCase = Accelerator(split_batches=snake_case_ , dispatch_batches=snake_case_ ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('''**Testing gather_for_metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(f"""With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`""" ) test_mrpc(snake_case_ , snake_case_ ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test torch metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: _UpperCamelCase = Accelerator(split_batches=snake_case_ , dispatch_batches=snake_case_ ) if accelerator.is_local_main_process: print(f"""With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99""" ) test_torch_metrics(snake_case_ , 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test last batch is not dropped when perfectly divisible**''' ) _UpperCamelCase = Accelerator() test_torch_metrics(snake_case_ , 512 ) accelerator.state._reset_state() def _snake_case ( __snake_case ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
703
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase = { "configuration_jukebox": [ "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "JukeboxConfig", "JukeboxPriorConfig", "JukeboxVQVAEConfig", ], "tokenization_jukebox": ["JukeboxTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST", "JukeboxModel", "JukeboxPreTrainedModel", "JukeboxVQVAE", "JukeboxPrior", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
0
import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class lowerCAmelCase_ : def __init__( self : Optional[int] , _A : List[Any] , _A : str=None , _A : List[str]=None , _A : Optional[int]=None , _A : Union[str, Any]="resnet50" , _A : Union[str, Any]=3 , _A : Any=32 , _A : str=3 , _A : Dict=True , _A : Dict=True , ): _UpperCamelCase = parent _UpperCamelCase = out_indices if out_indices is not None else [4] _UpperCamelCase = stage_names _UpperCamelCase = out_features _UpperCamelCase = backbone _UpperCamelCase = batch_size _UpperCamelCase = image_size _UpperCamelCase = num_channels _UpperCamelCase = use_pretrained_backbone _UpperCamelCase = is_training def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCamelCase = self.get_config() return config, pixel_values def UpperCamelCase_ ( self : Tuple ): return TimmBackboneConfig( image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , ) def UpperCamelCase_ ( self : Dict , _A : Optional[Any] , _A : Any ): _UpperCamelCase = TimmBackbone(config=_A ) model.to(_A ) model.eval() with torch.no_grad(): _UpperCamelCase = model(_A ) self.parent.assertEqual( result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 14, 14) , ) def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = self.prepare_config_and_inputs() _UpperCamelCase = config_and_inputs _UpperCamelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_torch @require_timm class lowerCAmelCase_ ( lowercase__, lowercase__, lowercase__, unittest.TestCase ): UpperCAmelCase = (TimmBackbone,) if is_torch_available() else () UpperCAmelCase = {"feature-extraction": TimmBackbone} if is_torch_available() else {} UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = False def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = TimmBackboneModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=_A , has_text_modality=_A ) def UpperCamelCase_ ( self : Any ): self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = "resnet18" _UpperCamelCase = "microsoft/resnet-18" _UpperCamelCase = AutoBackbone.from_pretrained(_A , use_timm_backbone=_A ) _UpperCamelCase = AutoBackbone.from_pretrained(_A ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices , (-1,) ) self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] ) _UpperCamelCase = AutoBackbone.from_pretrained(_A , use_timm_backbone=_A , out_indices=[1, 2, 3] ) _UpperCamelCase = AutoBackbone.from_pretrained(_A , out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices , transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) @unittest.skip('''TimmBackbone doesn\'t support feed forward chunking''' ) def UpperCamelCase_ ( self : Dict ): pass @unittest.skip('''TimmBackbone doesn\'t have num_hidden_layers attribute''' ) def UpperCamelCase_ ( self : Optional[Any] ): pass @unittest.skip('''TimmBackbone initialization is managed on the timm side''' ) def UpperCamelCase_ ( self : Tuple ): pass @unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''' ) def UpperCamelCase_ ( self : Dict ): pass @unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''' ) def UpperCamelCase_ ( self : Dict ): pass @unittest.skip('''TimmBackbone model cannot be created without specifying a backbone checkpoint''' ) def UpperCamelCase_ ( self : List[str] ): pass @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''' ) def UpperCamelCase_ ( self : Optional[int] ): pass @unittest.skip('''model weights aren\'t tied in TimmBackbone.''' ) def UpperCamelCase_ ( self : List[str] ): pass @unittest.skip('''model weights aren\'t tied in TimmBackbone.''' ) def UpperCamelCase_ ( self : Optional[int] ): pass @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''' ) def UpperCamelCase_ ( self : int ): pass @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''' ) def UpperCamelCase_ ( self : List[Any] ): pass @unittest.skip('''TimmBackbone doesn\'t have hidden size info in its configuration.''' ) def UpperCamelCase_ ( self : Optional[Any] ): pass @unittest.skip('''TimmBackbone doesn\'t support output_attentions.''' ) def UpperCamelCase_ ( self : int ): pass @unittest.skip('''Safetensors is not supported by timm.''' ) def UpperCamelCase_ ( self : int ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def UpperCamelCase_ ( self : int ): pass def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase = model_class(_A ) _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] , _A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase = True _UpperCamelCase = self.has_attentions # no need to test all models as different heads yield the same functionality _UpperCamelCase = self.all_model_classes[0] _UpperCamelCase = model_class(_A ) model.to(_A ) _UpperCamelCase = self._prepare_for_class(_A , _A ) _UpperCamelCase = model(**_A ) _UpperCamelCase = outputs[0][-1] # Encoder-/Decoder-only models _UpperCamelCase = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: _UpperCamelCase = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=_A ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase = model_class(_A ) model.to(_A ) model.eval() _UpperCamelCase = model(**_A ) self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) ) self.assertEqual(len(model.channels ) , len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None _UpperCamelCase = copy.deepcopy(_A ) _UpperCamelCase = None _UpperCamelCase = model_class(_A ) model.to(_A ) model.eval() _UpperCamelCase = model(**_A ) self.assertEqual(len(result.feature_maps ) , 1 ) self.assertEqual(len(model.channels ) , 1 ) # Check backbone can be initialized with fresh weights _UpperCamelCase = copy.deepcopy(_A ) _UpperCamelCase = False _UpperCamelCase = model_class(_A ) model.to(_A ) model.eval() _UpperCamelCase = model(**_A )
704
import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase_ ( __lowercase ): def __init__( self : int , _A : NestedDataStructureLike[PathLike] , _A : Optional[NamedSplit] = None , _A : Optional[Features] = None , _A : str = None , _A : bool = False , _A : bool = False , _A : Optional[str] = None , _A : Optional[int] = None , **_A : str , ): super().__init__( _A , split=_A , features=_A , cache_dir=_A , keep_in_memory=_A , streaming=_A , num_proc=_A , **_A , ) _UpperCamelCase = field _UpperCamelCase = path_or_paths if isinstance(_A , _A ) else {self.split: path_or_paths} _UpperCamelCase = Json( cache_dir=_A , data_files=_A , features=_A , field=_A , **_A , ) def UpperCamelCase_ ( self : List[str] ): # Build iterable dataset if self.streaming: _UpperCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None self.builder.download_and_prepare( download_config=_A , download_mode=_A , verification_mode=_A , base_path=_A , num_proc=self.num_proc , ) _UpperCamelCase = self.builder.as_dataset( split=self.split , verification_mode=_A , in_memory=self.keep_in_memory ) return dataset class lowerCAmelCase_ : def __init__( self : Optional[Any] , _A : Dataset , _A : Union[PathLike, BinaryIO] , _A : Optional[int] = None , _A : Optional[int] = None , **_A : List[str] , ): if num_proc is not None and num_proc <= 0: raise ValueError(F"""num_proc {num_proc} must be an integer > 0.""" ) _UpperCamelCase = dataset _UpperCamelCase = path_or_buf _UpperCamelCase = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _UpperCamelCase = num_proc _UpperCamelCase = '''utf-8''' _UpperCamelCase = to_json_kwargs def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = self.to_json_kwargs.pop('''path_or_buf''' , _A ) _UpperCamelCase = self.to_json_kwargs.pop('''orient''' , '''records''' ) _UpperCamelCase = self.to_json_kwargs.pop('''lines''' , True if orient == '''records''' else False ) _UpperCamelCase = self.to_json_kwargs.pop('''index''' , False if orient in ['''split''', '''table'''] else True ) _UpperCamelCase = self.to_json_kwargs.pop('''compression''' , _A ) if compression not in [None, "infer", "gzip", "bz2", "xz"]: raise NotImplementedError(F"""`datasets` currently does not support {compression} compression""" ) if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with fsspec.open(self.path_or_buf , '''wb''' , compression=_A ) as buffer: _UpperCamelCase = self._write(file_obj=_A , orient=_A , lines=_A , index=_A , **self.to_json_kwargs ) else: if compression: raise NotImplementedError( F"""The compression parameter is not supported when writing to a buffer, but compression={compression}""" ''' was passed. Please provide a local path instead.''' ) _UpperCamelCase = self._write( file_obj=self.path_or_buf , orient=_A , lines=_A , index=_A , **self.to_json_kwargs ) return written def UpperCamelCase_ ( self : Any , _A : Optional[Any] ): _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = args _UpperCamelCase = query_table( table=self.dataset.data , key=slice(_A , offset + self.batch_size ) , indices=self.dataset._indices , ) _UpperCamelCase = batch.to_pandas().to_json( path_or_buf=_A , orient=_A , lines=_A , index=_A , **_A ) if not json_str.endswith('''\n''' ): json_str += "\n" return json_str.encode(self.encoding ) def UpperCamelCase_ ( self : int , _A : BinaryIO , _A : Dict , _A : Optional[Any] , _A : Dict , **_A : str , ): _UpperCamelCase = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating json from Arrow format''' , ): _UpperCamelCase = self._batch_json((offset, orient, lines, index, to_json_kwargs) ) written += file_obj.write(_A ) else: _UpperCamelCase , _UpperCamelCase = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for json_str in logging.tqdm( pool.imap( self._batch_json , [(offset, orient, lines, index, to_json_kwargs) for offset in range(0 , _A , _A )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating json from Arrow format''' , ): written += file_obj.write(_A ) return written
71
0
def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = """""" for i in table: res += inp[i - 1] return res def _snake_case ( __snake_case ): return data[1:] + data[0] def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = """""" for i in range(len(__snake_case ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = int('''0b''' + data[0] + data[-1] , 2 ) _UpperCamelCase = int('''0b''' + data[1:3] , 2 ) return bin(s[row][col] )[2:] def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = message[:4] _UpperCamelCase = message[4:] _UpperCamelCase = apply_table(__snake_case , __snake_case ) _UpperCamelCase = xor(__snake_case , __snake_case ) _UpperCamelCase = apply_sbox(__snake_case , temp[:4] ) # noqa: E741 _UpperCamelCase = apply_sbox(__snake_case , temp[4:] ) _UpperCamelCase = """0""" * (2 - len(__snake_case )) + l # noqa: E741 _UpperCamelCase = """0""" * (2 - len(__snake_case )) + r _UpperCamelCase = apply_table(l + r , __snake_case ) _UpperCamelCase = xor(__snake_case , __snake_case ) return temp + right if __name__ == "__main__": _lowerCAmelCase = input("Enter 10 bit key: ") _lowerCAmelCase = input("Enter 8 bit message: ") _lowerCAmelCase = [6, 3, 7, 4, 8, 5, 10, 9] _lowerCAmelCase = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] _lowerCAmelCase = [2, 4, 3, 1] _lowerCAmelCase = [2, 6, 3, 1, 4, 8, 5, 7] _lowerCAmelCase = [4, 1, 3, 5, 7, 2, 8, 6] _lowerCAmelCase = [4, 1, 2, 3, 2, 3, 4, 1] _lowerCAmelCase = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] _lowerCAmelCase = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation _lowerCAmelCase = apply_table(key, paa_table) _lowerCAmelCase = temp[:5] _lowerCAmelCase = temp[5:] _lowerCAmelCase = left_shift(left) _lowerCAmelCase = left_shift(right) _lowerCAmelCase = apply_table(left + right, pa_table) _lowerCAmelCase = left_shift(left) _lowerCAmelCase = left_shift(right) _lowerCAmelCase = left_shift(left) _lowerCAmelCase = left_shift(right) _lowerCAmelCase = apply_table(left + right, pa_table) # encryption _lowerCAmelCase = apply_table(message, IP) _lowerCAmelCase = function(expansion, sa, sa, keya, temp) _lowerCAmelCase = temp[4:] + temp[:4] _lowerCAmelCase = function(expansion, sa, sa, keya, temp) _lowerCAmelCase = apply_table(temp, IP_inv) print("Cipher text is:", CT) # decryption _lowerCAmelCase = apply_table(CT, IP) _lowerCAmelCase = function(expansion, sa, sa, keya, temp) _lowerCAmelCase = temp[4:] + temp[:4] _lowerCAmelCase = function(expansion, sa, sa, keya, temp) _lowerCAmelCase = apply_table(temp, IP_inv) print("Plain text after decypting is:", PT)
705
import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class lowerCAmelCase_ ( enum.Enum ): UpperCAmelCase = 0 UpperCAmelCase = 1 UpperCAmelCase = 2 @add_end_docstrings(__lowercase ) class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = "\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n " def __init__( self : Tuple , *_A : List[str] , **_A : str ): super().__init__(*_A , **_A ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == '''tf''' else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. _UpperCamelCase = None if self.model.config.prefix is not None: _UpperCamelCase = self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. _UpperCamelCase = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = self._sanitize_parameters(prefix=_A , **self._forward_params ) _UpperCamelCase = {**self._preprocess_params, **preprocess_params} _UpperCamelCase = {**self._forward_params, **forward_params} def UpperCamelCase_ ( self : Dict , _A : Optional[int]=None , _A : Any=None , _A : Optional[int]=None , _A : List[str]=None , _A : List[Any]=None , _A : int=None , _A : Tuple=None , _A : Optional[Any]=None , **_A : Optional[int] , ): _UpperCamelCase = {} if prefix is not None: _UpperCamelCase = prefix if prefix: _UpperCamelCase = self.tokenizer( _A , padding=_A , add_special_tokens=_A , return_tensors=self.framework ) _UpperCamelCase = prefix_inputs['''input_ids'''].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( F"""{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected""" ''' [None, \'hole\']''' ) _UpperCamelCase = handle_long_generation preprocess_params.update(_A ) _UpperCamelCase = generate_kwargs _UpperCamelCase = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_full_text`''' ) if return_tensors is not None: raise ValueError('''`return_full_text` is mutually exclusive with `return_tensors`''' ) _UpperCamelCase = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError('''`return_text` is mutually exclusive with `return_tensors`''' ) _UpperCamelCase = ReturnType.TENSORS if return_type is not None: _UpperCamelCase = return_type if clean_up_tokenization_spaces is not None: _UpperCamelCase = clean_up_tokenization_spaces if stop_sequence is not None: _UpperCamelCase = self.tokenizer.encode(_A , add_special_tokens=_A ) if len(_A ) > 1: warnings.warn( '''Stopping on a multiple token sequence is not yet supported on transformers. The first token of''' ''' the stop sequence will be used as the stop sequence string in the interim.''' ) _UpperCamelCase = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCamelCase_ ( self : int , *_A : Union[str, Any] , **_A : Union[str, Any] ): # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({'''add_space_before_punct_symbol''': True} ) return super()._parse_and_tokenize(*_A , **_A ) def __call__( self : List[str] , _A : str , **_A : Any ): return super().__call__(_A , **_A ) def UpperCamelCase_ ( self : Optional[Any] , _A : List[str] , _A : int="" , _A : Optional[Any]=None , **_A : Optional[Any] ): _UpperCamelCase = self.tokenizer( prefix + prompt_text , padding=_A , add_special_tokens=_A , return_tensors=self.framework ) _UpperCamelCase = prompt_text if handle_long_generation == "hole": _UpperCamelCase = inputs['''input_ids'''].shape[-1] if "max_new_tokens" in generate_kwargs: _UpperCamelCase = generate_kwargs['''max_new_tokens'''] else: _UpperCamelCase = generate_kwargs.get('''max_length''' , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError('''We cannot infer how many new tokens are expected''' ) if cur_len + new_tokens > self.tokenizer.model_max_length: _UpperCamelCase = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( '''We cannot use `hole` to handle this generation the number of desired tokens exceeds the''' ''' models max length''' ) _UpperCamelCase = inputs['''input_ids'''][:, -keep_length:] if "attention_mask" in inputs: _UpperCamelCase = inputs['''attention_mask'''][:, -keep_length:] return inputs def UpperCamelCase_ ( self : Dict , _A : Optional[int] , **_A : str ): _UpperCamelCase = model_inputs['''input_ids'''] _UpperCamelCase = model_inputs.get('''attention_mask''' , _A ) # Allow empty prompts if input_ids.shape[1] == 0: _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = 1 else: _UpperCamelCase = input_ids.shape[0] _UpperCamelCase = model_inputs.pop('''prompt_text''' ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. _UpperCamelCase = generate_kwargs.pop('''prefix_length''' , 0 ) if prefix_length > 0: _UpperCamelCase = '''max_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].max_new_tokens is not None ) if not has_max_new_tokens: _UpperCamelCase = generate_kwargs.get('''max_length''' ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length _UpperCamelCase = '''min_new_tokens''' in generate_kwargs or ( '''generation_config''' in generate_kwargs and generate_kwargs['''generation_config'''].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL _UpperCamelCase = self.model.generate(input_ids=_A , attention_mask=_A , **_A ) _UpperCamelCase = generated_sequence.shape[0] if self.framework == "pt": _UpperCamelCase = generated_sequence.reshape(_A , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": _UpperCamelCase = tf.reshape(_A , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def UpperCamelCase_ ( self : List[str] , _A : Dict , _A : Optional[Any]=ReturnType.FULL_TEXT , _A : Dict=True ): _UpperCamelCase = model_outputs['''generated_sequence'''][0] _UpperCamelCase = model_outputs['''input_ids'''] _UpperCamelCase = model_outputs['''prompt_text'''] _UpperCamelCase = generated_sequence.numpy().tolist() _UpperCamelCase = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: _UpperCamelCase = {'''generated_token_ids''': sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text _UpperCamelCase = self.tokenizer.decode( _A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: _UpperCamelCase = 0 else: _UpperCamelCase = len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=_A , clean_up_tokenization_spaces=_A , ) ) if return_type == ReturnType.FULL_TEXT: _UpperCamelCase = prompt_text + text[prompt_length:] else: _UpperCamelCase = text[prompt_length:] _UpperCamelCase = {'''generated_text''': all_text} records.append(_A ) return records
71
0
_lowerCAmelCase = [ "Audio", "Array2D", "Array3D", "Array4D", "Array5D", "ClassLabel", "Features", "Sequence", "Value", "Image", "Translation", "TranslationVariableLanguages", ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value from .image import Image from .translation import Translation, TranslationVariableLanguages
706
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self : Any ): _UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=_A ).to(_A ) _UpperCamelCase = AutoTokenizer.from_pretrained('''google/mt5-small''' ) _UpperCamelCase = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids _UpperCamelCase = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids _UpperCamelCase = model(input_ids.to(_A ) , labels=labels.to(_A ) ).loss _UpperCamelCase = -(labels.shape[-1] * loss.item()) _UpperCamelCase = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
71
0
from math import isclose, sqrt def _snake_case ( __snake_case , __snake_case , __snake_case ): _UpperCamelCase = point_y / 4 / point_x _UpperCamelCase = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) _UpperCamelCase = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) _UpperCamelCase = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 _UpperCamelCase = outgoing_gradient**2 + 4 _UpperCamelCase = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) _UpperCamelCase = (point_y - outgoing_gradient * point_x) ** 2 - 100 _UpperCamelCase = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) _UpperCamelCase = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point _UpperCamelCase = x_minus if isclose(__snake_case , __snake_case ) else x_plus _UpperCamelCase = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _snake_case ( __snake_case = 1.4 , __snake_case = -9.6 ): _UpperCamelCase = 0 _UpperCamelCase = first_x_coord _UpperCamelCase = first_y_coord _UpperCamelCase = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = next_point(__snake_case , __snake_case , __snake_case ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'{solution() = }')
707
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) _lowerCAmelCase = logging.getLogger(__name__) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether tp freeze the encoder."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Whether to freeze the embeddings."} ) @dataclass class lowerCAmelCase_ : UpperCAmelCase = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) UpperCAmelCase = field( default="summarization", metadata={"help": "Task name, summarization (or summarization_{dataset} for pegasus) or translation"}, ) UpperCAmelCase = field( default=1024, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=128, metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) }, ) UpperCAmelCase = field( default=142, metadata={ "help": ( "The maximum total sequence length for test target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) UpperCAmelCase = field(default=-1, metadata={"help": "# training examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# validation examples. -1 means use all."} ) UpperCAmelCase = field(default=-1, metadata={"help": "# test examples. -1 means use all."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Source language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "Target language id for translation."} ) UpperCAmelCase = field(default=__lowercase, metadata={"help": "# num_beams to use for evaluation."} ) UpperCAmelCase = field( default=__lowercase, metadata={"help": "If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."}, ) def _snake_case ( __snake_case , __snake_case , __snake_case ): logger.info(f"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(f""" {key} = {metrics[key]}""" ) save_json(__snake_case , os.path.join(__snake_case , f"""{split}_results.json""" ) ) def _snake_case ( ): # 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. _UpperCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = parser.parse_args_into_dataclasses() check_output_dir(__snake_case ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , __snake_case ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _UpperCamelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _UpperCamelCase = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(__snake_case , __snake_case , __snake_case ): assert hasattr(__snake_case , __snake_case ), f"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(__snake_case , __snake_case , getattr(__snake_case , __snake_case ) ) _UpperCamelCase = 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 , ) _UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=__snake_case , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(__snake_case , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: _UpperCamelCase = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(__snake_case , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(__snake_case , __snake_case ): _UpperCamelCase = tokenizer.lang_code_to_id[data_args.tgt_lang] else: _UpperCamelCase = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(__snake_case ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) _UpperCamelCase = SeqaSeqDataset # Get datasets _UpperCamelCase = ( dataset_class( __snake_case , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) _UpperCamelCase = ( dataset_class( __snake_case , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer _UpperCamelCase = ( build_compute_metrics_fn(data_args.task , __snake_case ) if training_args.predict_with_generate else None ) _UpperCamelCase = SeqaSeqTrainer( model=__snake_case , args=__snake_case , data_args=__snake_case , train_dataset=__snake_case , eval_dataset=__snake_case , data_collator=SeqaSeqDataCollator( __snake_case , __snake_case , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=__snake_case , tokenizer=__snake_case , ) _UpperCamelCase = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) _UpperCamelCase = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) _UpperCamelCase = train_result.metrics _UpperCamelCase = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) _UpperCamelCase = trainer.evaluate(metric_key_prefix='''val''' ) _UpperCamelCase = data_args.n_val _UpperCamelCase = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.do_predict: logger.info('''*** Predict ***''' ) _UpperCamelCase = trainer.predict(test_dataset=__snake_case , metric_key_prefix='''test''' ) _UpperCamelCase = test_output.metrics _UpperCamelCase = data_args.n_test if trainer.is_world_process_zero(): _UpperCamelCase = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , __snake_case , training_args.output_dir ) all_metrics.update(__snake_case ) if training_args.predict_with_generate: _UpperCamelCase = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=__snake_case , clean_up_tokenization_spaces=__snake_case ) _UpperCamelCase = lmap(str.strip , __snake_case ) write_txt_file(__snake_case , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(__snake_case , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def _snake_case ( __snake_case ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
71
0
import sys def _snake_case ( __snake_case ): _UpperCamelCase = len(UpperCAmelCase__ ) _UpperCamelCase = [[0 for x in range(UpperCAmelCase__ )] for x in range(UpperCAmelCase__ )] _UpperCamelCase = [[0 for x in range(UpperCAmelCase__ )] for x in range(UpperCAmelCase__ )] for chain_length in range(2 , UpperCAmelCase__ ): for a in range(1 , n - chain_length + 1 ): _UpperCamelCase = a + chain_length - 1 _UpperCamelCase = sys.maxsize for c in range(UpperCAmelCase__ , UpperCAmelCase__ ): _UpperCamelCase = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: _UpperCamelCase = cost _UpperCamelCase = c return matrix, sol def _snake_case ( __snake_case , __snake_case , __snake_case ): if i == j: print('''A''' + str(UpperCAmelCase__ ) , end=''' ''' ) else: print('''(''' , end=''' ''' ) print_optiomal_solution(UpperCAmelCase__ , UpperCAmelCase__ , optimal_solution[i][j] ) print_optiomal_solution(UpperCAmelCase__ , optimal_solution[i][j] + 1 , UpperCAmelCase__ ) print(''')''' , end=''' ''' ) def _snake_case ( ): _UpperCamelCase = [30, 35, 15, 5, 10, 20, 25] _UpperCamelCase = len(UpperCAmelCase__ ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 _UpperCamelCase = matrix_chain_order(UpperCAmelCase__ ) print('''No. of Operation required: ''' + str(matrix[1][n - 1] ) ) print_optiomal_solution(UpperCAmelCase__ , 1 , n - 1 ) if __name__ == "__main__": main()
708
from __future__ import annotations import typing from collections import Counter def _snake_case ( __snake_case ): _UpperCamelCase = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(__snake_case , max_perimeter + 1 ): _UpperCamelCase = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__snake_case ): _UpperCamelCase = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def _snake_case ( __snake_case = 1000 ): _UpperCamelCase = pythagorean_triple(__snake_case ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(f'Perimeter {solution()} has maximum solutions')
71
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = {'''openai-gpt''': '''https://huggingface.co/openai-gpt/resolve/main/config.json'''} class lowerCAmelCase_ ( a__ ): UpperCAmelCase = """openai-gpt""" UpperCAmelCase = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : List[str] , _A : Optional[int]=4_0478 , _A : Optional[int]=512 , _A : str=768 , _A : Union[str, Any]=12 , _A : Optional[int]=12 , _A : Dict="gelu" , _A : Union[str, Any]=0.1 , _A : int=0.1 , _A : List[Any]=0.1 , _A : Optional[Any]=1e-5 , _A : List[Any]=0.02 , _A : Tuple="cls_index" , _A : str=True , _A : Optional[Any]=None , _A : str=True , _A : int=0.1 , **_A : Optional[Any] , ): _UpperCamelCase = vocab_size _UpperCamelCase = n_positions _UpperCamelCase = n_embd _UpperCamelCase = n_layer _UpperCamelCase = n_head _UpperCamelCase = afn _UpperCamelCase = resid_pdrop _UpperCamelCase = embd_pdrop _UpperCamelCase = attn_pdrop _UpperCamelCase = layer_norm_epsilon _UpperCamelCase = initializer_range _UpperCamelCase = summary_type _UpperCamelCase = summary_use_proj _UpperCamelCase = summary_activation _UpperCamelCase = summary_first_dropout _UpperCamelCase = summary_proj_to_labels super().__init__(**lowerCAmelCase__ )
709
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = (DPMSolverSDEScheduler,) UpperCAmelCase = 10 def UpperCamelCase_ ( self : Tuple , **_A : Union[str, Any] ): _UpperCamelCase = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''noise_sampler_seed''': 0, } config.update(**_A ) return config def UpperCamelCase_ ( self : List[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=_A ) def UpperCamelCase_ ( self : List[Any] ): for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_A , beta_end=_A ) def UpperCamelCase_ ( self : List[str] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_A ) def UpperCamelCase_ ( self : Union[str, Any] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_8210_4492_1875 ) < 1e-2 assert abs(result_mean.item() - 0.2178_7059_6456_5277 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3521_1181_6406 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9068_9229_9652 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config(prediction_type='''v_prediction''' ) _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_1492_0043_9453 ) < 1e-2 assert abs(result_mean.item() - 0.1_6226_2890_1481_6284 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_6633_6059_5703 ) < 1e-2 assert abs(result_mean.item() - 0.1_6688_3260_0116_7297 ) < 1e-3 else: assert abs(result_sum.item() - 119.8_4875_4882_8125 ) < 1e-2 assert abs(result_mean.item() - 0.1560_5306_6253_6621 ) < 1e-3 def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(self.num_inference_steps , device=_A ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter.to(_A ) * scheduler.init_noise_sigma for t in scheduler.timesteps: _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_9573_9746_0938 ) < 1e-2 assert abs(result_mean.item() - 0.2_1805_9346_0798_2635 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3536_3769_5312 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9083_8241_5771 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A , use_karras_sigmas=_A ) scheduler.set_timesteps(self.num_inference_steps , device=_A ) _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter.to(_A ) * scheduler.init_noise_sigma _UpperCamelCase = sample.to(_A ) for t in scheduler.timesteps: _UpperCamelCase = scheduler.scale_model_input(_A , _A ) _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step(_A , _A , _A ) _UpperCamelCase = output.prev_sample _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_9741_3574_2188 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_6535_6445_3125 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 else: assert abs(result_sum.item() - 170.3_1352_2338_8672 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2
71
0
from ..utils import DummyObject, requires_backends class lowerCAmelCase_ ( metaclass=UpperCAmelCase__ ): UpperCAmelCase = ["flax", "transformers"] def __init__( self : int , *_A : Dict , **_A : str ): requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def UpperCamelCase_ ( cls : Optional[Any] , *_A : int , **_A : Tuple ): requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def UpperCamelCase_ ( cls : List[str] , *_A : Optional[int] , **_A : Any ): requires_backends(cls , ['''flax''', '''transformers'''] ) class lowerCAmelCase_ ( metaclass=UpperCAmelCase__ ): UpperCAmelCase = ["flax", "transformers"] def __init__( self : str , *_A : int , **_A : Optional[int] ): requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def UpperCamelCase_ ( cls : str , *_A : int , **_A : str ): requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def UpperCamelCase_ ( cls : Optional[Any] , *_A : Dict , **_A : Tuple ): requires_backends(cls , ['''flax''', '''transformers'''] ) class lowerCAmelCase_ ( metaclass=UpperCAmelCase__ ): UpperCAmelCase = ["flax", "transformers"] def __init__( self : List[Any] , *_A : List[Any] , **_A : Optional[Any] ): requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def UpperCamelCase_ ( cls : Tuple , *_A : int , **_A : int ): requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def UpperCamelCase_ ( cls : List[Any] , *_A : Optional[Any] , **_A : Optional[Any] ): requires_backends(cls , ['''flax''', '''transformers'''] ) class lowerCAmelCase_ ( metaclass=UpperCAmelCase__ ): UpperCAmelCase = ["flax", "transformers"] def __init__( self : List[str] , *_A : Tuple , **_A : str ): requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def UpperCamelCase_ ( cls : List[str] , *_A : Dict , **_A : Tuple ): requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def UpperCamelCase_ ( cls : str , *_A : Dict , **_A : Any ): requires_backends(cls , ['''flax''', '''transformers'''] )
710
import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class lowerCAmelCase_ : @property def UpperCamelCase_ ( self : Optional[int] ): return self.get_dummy_input() @property def UpperCamelCase_ ( self : Dict ): if self.block_type == "down": return (4, 32, 16, 16) elif self.block_type == "mid": return (4, 32, 32, 32) elif self.block_type == "up": return (4, 32, 64, 64) raise ValueError(F"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'.""" ) def UpperCamelCase_ ( self : Union[str, Any] , _A : List[str]=True , _A : Any=False , _A : Union[str, Any]=False , _A : int=False , ): _UpperCamelCase = 4 _UpperCamelCase = 32 _UpperCamelCase = (32, 32) _UpperCamelCase = torch.manual_seed(0 ) _UpperCamelCase = torch.device(_A ) _UpperCamelCase = (batch_size, num_channels) + sizes _UpperCamelCase = randn_tensor(_A , generator=_A , device=_A ) _UpperCamelCase = {'''hidden_states''': hidden_states} if include_temb: _UpperCamelCase = 128 _UpperCamelCase = randn_tensor((batch_size, temb_channels) , generator=_A , device=_A ) if include_res_hidden_states_tuple: _UpperCamelCase = torch.manual_seed(1 ) _UpperCamelCase = (randn_tensor(_A , generator=_A , device=_A ),) if include_encoder_hidden_states: _UpperCamelCase = floats_tensor((batch_size, 32, 32) ).to(_A ) if include_skip_sample: _UpperCamelCase = randn_tensor(((batch_size, 3) + sizes) , generator=_A , device=_A ) return dummy_input def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = { '''in_channels''': 32, '''out_channels''': 32, '''temb_channels''': 128, } if self.block_type == "up": _UpperCamelCase = 32 if self.block_type == "mid": init_dict.pop('''out_channels''' ) _UpperCamelCase = self.dummy_input return init_dict, inputs_dict def UpperCamelCase_ ( self : Tuple , _A : Union[str, Any] ): _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**_A ) unet_block.to(_A ) unet_block.eval() with torch.no_grad(): _UpperCamelCase = unet_block(**_A ) if isinstance(_A , _A ): _UpperCamelCase = output[0] self.assertEqual(output.shape , self.output_shape ) _UpperCamelCase = output[0, -1, -3:, -3:] _UpperCamelCase = torch.tensor(_A ).to(_A ) assert torch_all_close(output_slice.flatten() , _A , atol=5e-3 ) @unittest.skipIf(torch_device == '''mps''' , '''Training is not supported in mps''' ) def UpperCamelCase_ ( self : Tuple ): _UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase = self.block_class(**_A ) model.to(_A ) model.train() _UpperCamelCase = model(**_A ) if isinstance(_A , _A ): _UpperCamelCase = output[0] _UpperCamelCase = torch.device(_A ) _UpperCamelCase = randn_tensor(output.shape , device=_A ) _UpperCamelCase = torch.nn.functional.mse_loss(_A , _A ) loss.backward()
71
0
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () _lowerCAmelCase = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). _lowerCAmelCase = [0, 25, 50] _lowerCAmelCase = [25, 50, 75] _lowerCAmelCase = fuzz.membership.trimf(X, abca) _lowerCAmelCase = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. _lowerCAmelCase = np.ones(75) _lowerCAmelCase = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) _lowerCAmelCase = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) _lowerCAmelCase = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) _lowerCAmelCase = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) _lowerCAmelCase = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] _lowerCAmelCase = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) _lowerCAmelCase = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] _lowerCAmelCase = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] _lowerCAmelCase = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title("Young") plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title("Middle aged") plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title("union") plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title("intersection") plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title("complement_a") plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title("difference a/b") plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title("alg_sum") plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title("alg_product") plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title("bdd_sum") plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title("bdd_difference") plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
711
def _snake_case ( __snake_case ): if not isinstance(__snake_case , __snake_case ): raise TypeError('''Input value must be an \'int\' type''' ) _UpperCamelCase = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
71
0
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = '''ylacombe/bark-small''' _UpperCamelCase = tempfile.mkdtemp() _UpperCamelCase = '''en_speaker_1''' _UpperCamelCase = '''This is a test string''' _UpperCamelCase = '''speaker_embeddings_path.json''' _UpperCamelCase = '''speaker_embeddings''' def UpperCamelCase_ ( self : str , **_A : int ): return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCamelCase__ ) def UpperCamelCase_ ( self : Optional[int] ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = BarkProcessor(tokenizer=UpperCamelCase__ ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) _UpperCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _UpperCamelCase = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) _UpperCamelCase = 35 _UpperCamelCase = 2 _UpperCamelCase = 8 _UpperCamelCase = { '''semantic_prompt''': np.ones(UpperCamelCase__ ), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len) ), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset _UpperCamelCase = processor(text=self.input_string , voice_preset=UpperCamelCase__ ) _UpperCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCamelCase__ , np.array([] ) ).tolist() ) # test loading voice preset from npz file _UpperCamelCase = os.path.join(self.tmpdirname , '''file.npz''' ) np.savez(UpperCamelCase__ , **UpperCamelCase__ ) _UpperCamelCase = processor(text=self.input_string , voice_preset=UpperCamelCase__ ) _UpperCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCamelCase__ , np.array([] ) ).tolist() ) # test loading voice preset from the hub _UpperCamelCase = processor(text=self.input_string , voice_preset=self.voice_preset ) def UpperCamelCase_ ( self : Any ): _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = BarkProcessor(tokenizer=UpperCamelCase__ ) _UpperCamelCase = processor(text=self.input_string ) _UpperCamelCase = tokenizer( self.input_string , padding='''max_length''' , max_length=256 , add_special_tokens=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , return_token_type_ids=UpperCamelCase__ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
712
import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } _lowerCAmelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): for attribute in key.split('''.''' ): _UpperCamelCase = getattr(__snake_case , __snake_case ) if weight_type is not None: _UpperCamelCase = getattr(__snake_case , __snake_case ).shape else: _UpperCamelCase = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": _UpperCamelCase = value elif weight_type == "weight_g": _UpperCamelCase = value elif weight_type == "weight_v": _UpperCamelCase = value elif weight_type == "bias": _UpperCamelCase = value else: _UpperCamelCase = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _snake_case ( __snake_case , __snake_case ): _UpperCamelCase = [] _UpperCamelCase = fairseq_model.state_dict() _UpperCamelCase = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _UpperCamelCase = None for name, value in fairseq_dict.items(): _UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __snake_case , __snake_case , __snake_case , __snake_case , hf_model.config.feat_extract_norm == '''group''' , ) _UpperCamelCase = True elif name.split('''.''' )[0] == "proj": _UpperCamelCase = fairseq_model.proj _UpperCamelCase = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: _UpperCamelCase = True if "*" in mapped_key: _UpperCamelCase = name.split(__snake_case )[0].split('''.''' )[-2] _UpperCamelCase = mapped_key.replace('''*''' , __snake_case ) if "weight_g" in name: _UpperCamelCase = '''weight_g''' elif "weight_v" in name: _UpperCamelCase = '''weight_v''' elif "bias" in name: _UpperCamelCase = '''bias''' elif "weight" in name: _UpperCamelCase = '''weight''' else: _UpperCamelCase = None set_recursively(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) continue if not is_used: unused_weights.append(__snake_case ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = full_name.split('''conv_layers.''' )[-1] _UpperCamelCase = name.split('''.''' ) _UpperCamelCase = int(items[0] ) _UpperCamelCase = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) _UpperCamelCase = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__snake_case ) def _snake_case ( __snake_case ): _UpperCamelCase , _UpperCamelCase = emb.weight.shape _UpperCamelCase = nn.Linear(__snake_case , __snake_case , bias=__snake_case ) _UpperCamelCase = emb.weight.data return lin_layer def _snake_case ( __snake_case ): with open(__snake_case , '''r''' , encoding='''utf-8''' ) as f: _UpperCamelCase = f.readlines() _UpperCamelCase = [line.split(''' ''' )[0] for line in lines] _UpperCamelCase = len(__snake_case ) _UpperCamelCase = { '''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3, } vocab_dict.update(dict(zip(__snake_case , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ): _UpperCamelCase = WavaVecaConfig.from_pretrained(__snake_case ) _UpperCamelCase = SpeechaTextaConfig.from_pretrained( __snake_case , vocab_size=__snake_case , decoder_layers=__snake_case , do_stable_layer_norm=__snake_case ) _UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=__snake_case , return_attention_mask=__snake_case , ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) _UpperCamelCase = model[0].eval() # set weights for wav2vec2 encoder _UpperCamelCase = WavaVecaModel(__snake_case ) _UpperCamelCase = recursively_load_weights_wavaveca(model.encoder , __snake_case ) _UpperCamelCase = SpeechaTextaForCausalLM(__snake_case ) _UpperCamelCase , _UpperCamelCase = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__snake_case ) # set output linear layer unexpected_keys.remove('''embed_out''' ) _UpperCamelCase = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) _UpperCamelCase = SpeechEncoderDecoderModel(encoder=__snake_case , decoder=__snake_case ) _UpperCamelCase = False # add projection layer _UpperCamelCase = nn.Parameter(projection_layer.weight ) _UpperCamelCase = nn.Parameter(projection_layer.bias ) _UpperCamelCase = create_vocab_dict(__snake_case ) with open(os.path.join(__snake_case , '''vocab.json''' ) , '''w''' ) as fp: json.dump(__snake_case , __snake_case ) _UpperCamelCase = SpeechaTextaTokenizer(os.path.join(__snake_case , '''vocab.json''' ) ) tokenizer.save_pretrained(__snake_case ) _UpperCamelCase = hf_wavavec.config.to_dict() _UpperCamelCase = tokenizer.pad_token_id _UpperCamelCase = tokenizer.bos_token_id _UpperCamelCase = tokenizer.eos_token_id _UpperCamelCase = '''speech_to_text_2''' _UpperCamelCase = '''wav2vec2''' _UpperCamelCase = SpeechEncoderDecoderConfig.from_dict(__snake_case ) hf_wavavec.save_pretrained(__snake_case ) feature_extractor.save_pretrained(__snake_case ) if __name__ == "__main__": _lowerCAmelCase = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10_224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") _lowerCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
71
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = ["image_processor", "tokenizer"] UpperCAmelCase = "ViTImageProcessor" UpperCAmelCase = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : Any , _A : str=None , _A : str=None , **_A : Dict ): _UpperCamelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _SCREAMING_SNAKE_CASE , ) _UpperCamelCase = kwargs.pop('''feature_extractor''' ) _UpperCamelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __call__( self : str , _A : str=None , _A : Union[str, Any]=None , _A : int=None , _A : int=None , **_A : int ): if text is None and visual_prompt is None and images is None: raise ValueError('''You have to specify either text, visual prompt or images.''' ) if text is not None and visual_prompt is not None: raise ValueError('''You have to specify exactly one type of prompt. Either text or visual prompt.''' ) if text is not None: _UpperCamelCase = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if visual_prompt is not None: _UpperCamelCase = self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if images is not None: _UpperCamelCase = self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if visual_prompt is not None and images is not None: _UpperCamelCase = { '''pixel_values''': image_features.pixel_values, '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: _UpperCamelCase = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: _UpperCamelCase = { '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**_SCREAMING_SNAKE_CASE ) , tensor_type=_SCREAMING_SNAKE_CASE ) def UpperCamelCase_ ( self : Dict , *_A : Any , **_A : List[str] ): return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCamelCase_ ( self : str , *_A : Union[str, Any] , **_A : Tuple ): return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def UpperCamelCase_ ( self : Tuple ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _SCREAMING_SNAKE_CASE , ) return self.image_processor_class @property def UpperCamelCase_ ( self : int ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _SCREAMING_SNAKE_CASE , ) return self.image_processor
713
from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class lowerCAmelCase_ : def __init__( self : Optional[Any] , _A : Optional[Any] , _A : List[str]=13 , _A : Union[str, Any]=7 , _A : int=True , _A : Optional[int]=True , _A : Optional[int]=True , _A : Union[str, Any]=True , _A : Optional[int]=99 , _A : Union[str, Any]=32 , _A : Dict=2 , _A : List[Any]=4 , _A : Optional[Any]=37 , _A : int="gelu" , _A : Optional[int]=0.1 , _A : str=0.1 , _A : List[str]=512 , _A : Optional[Any]=16 , _A : Optional[Any]=2 , _A : Optional[int]=0.02 , _A : str=False , _A : int=True , _A : Any="None" , _A : Dict=3 , _A : List[Any]=4 , _A : Optional[Any]=None , ): _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_mask _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_labels _UpperCamelCase = num_choices _UpperCamelCase = relative_attention _UpperCamelCase = position_biased_input _UpperCamelCase = pos_att_type _UpperCamelCase = scope def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase = None if self.use_input_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None if self.use_labels: _UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCamelCase = DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=_A , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self : Dict , _A : Tuple , _A : Tuple , _A : Union[str, Any] , _A : List[str] , _A : Optional[int] , _A : int , _A : Optional[Any] ): _UpperCamelCase = TFDebertaVaModel(config=_A ) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = [input_ids, input_mask] _UpperCamelCase = model(_A ) _UpperCamelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Dict , _A : Optional[int] , _A : Any , _A : Dict , _A : Union[str, Any] , _A : Union[str, Any] , _A : List[Any] , _A : List[str] ): _UpperCamelCase = TFDebertaVaForMaskedLM(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self : Dict , _A : Dict , _A : List[str] , _A : List[Any] , _A : List[Any] , _A : Optional[Any] , _A : Tuple , _A : int ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForSequenceClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple , _A : Dict , _A : Optional[int] , _A : Any , _A : List[Any] , _A : Dict , _A : Union[str, Any] , _A : List[str] ): _UpperCamelCase = self.num_labels _UpperCamelCase = TFDebertaVaForTokenClassification(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Dict , _A : Optional[Any] , _A : Optional[int] , _A : Any , _A : List[str] , _A : str , _A : Optional[int] , _A : str ): _UpperCamelCase = TFDebertaVaForQuestionAnswering(config=_A ) _UpperCamelCase = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _UpperCamelCase = model(_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 UpperCamelCase_ ( self : Any ): _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase_ ( __lowercase, __lowercase, unittest.TestCase ): UpperCAmelCase = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) UpperCAmelCase = ( { "feature-extraction": TFDebertaVaModel, "fill-mask": TFDebertaVaForMaskedLM, "question-answering": TFDebertaVaForQuestionAnswering, "text-classification": TFDebertaVaForSequenceClassification, "token-classification": TFDebertaVaForTokenClassification, "zero-shot": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase = False UpperCAmelCase = False def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = TFDebertaVaModelTester(self ) _UpperCamelCase = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCamelCase_ ( self : int ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_A ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_A ) def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_A ) @slow def UpperCamelCase_ ( self : Any ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) self.assertIsNotNone(_A ) @require_tf class lowerCAmelCase_ ( unittest.TestCase ): @unittest.skip(reason='''Model not available yet''' ) def UpperCamelCase_ ( self : List[Any] ): pass @slow def UpperCamelCase_ ( self : int ): _UpperCamelCase = TFDebertaVaModel.from_pretrained('''kamalkraj/deberta-v2-xlarge''' ) _UpperCamelCase = tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) _UpperCamelCase = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) _UpperCamelCase = model(_A , attention_mask=_A )[0] _UpperCamelCase = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , _A , atol=1e-4 )
71
0
from manim import * class lowerCAmelCase_ ( UpperCAmelCase__ ): def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = Rectangle(height=0.5 , width=0.5 ) _UpperCamelCase = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) _UpperCamelCase = [mem.copy() for i in range(6 )] _UpperCamelCase = [mem.copy() for i in range(6 )] _UpperCamelCase = VGroup(*_A ).arrange(_A , buff=0 ) _UpperCamelCase = VGroup(*_A ).arrange(_A , buff=0 ) _UpperCamelCase = VGroup(_A , _A ).arrange(_A , buff=0 ) _UpperCamelCase = Text('''CPU''' , font_size=24 ) _UpperCamelCase = Group(_A , _A ).arrange(_A , buff=0.5 , aligned_edge=_A ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_A ) _UpperCamelCase = [mem.copy() for i in range(1 )] _UpperCamelCase = VGroup(*_A ).arrange(_A , buff=0 ) _UpperCamelCase = Text('''GPU''' , font_size=24 ) _UpperCamelCase = Group(_A , _A ).arrange(_A , buff=0.5 , aligned_edge=_A ) gpu.align_to(_A , _A ) gpu.set_x(gpu.get_x() - 1 ) self.add(_A ) _UpperCamelCase = [mem.copy() for i in range(6 )] _UpperCamelCase = VGroup(*_A ).arrange(_A , buff=0 ) _UpperCamelCase = Text('''Model''' , font_size=24 ) _UpperCamelCase = Group(_A , _A ).arrange(_A , buff=0.5 , aligned_edge=_A ) model.move_to([3, -1.0, 0] ) self.play( Create(_A , run_time=1 ) , Create(_A , run_time=1 ) , Create(_A , run_time=1 ) , ) _UpperCamelCase = MarkupText( F"""First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.""" , font_size=24 , ) _UpperCamelCase = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) _UpperCamelCase = MarkupText( F"""<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(_A , run_time=2.5 ) , Write(_A ) , Write(_A ) ) self.add(_A ) _UpperCamelCase = [] _UpperCamelCase = [] _UpperCamelCase = [] for i, rect in enumerate(_A ): _UpperCamelCase = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(_A , opacity=0.7 ) cpu_target.move_to(_A ) cpu_target.generate_target() _UpperCamelCase = 0.46 / 4 _UpperCamelCase = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_A ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=_A , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=_A , buff=0.0 ) cpu_targs.append(_A ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(_A ) ) second_animations.append(MoveToTarget(_A , run_time=1.5 ) ) self.play(*_A ) self.play(*_A ) self.wait()
714
def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case ): # Return True if there is node that has not iterated. _UpperCamelCase = [False] * len(__snake_case ) _UpperCamelCase = [] queue.append(__snake_case ) _UpperCamelCase = True while queue: _UpperCamelCase = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(__snake_case ) _UpperCamelCase = True _UpperCamelCase = u return visited[t] def _snake_case ( __snake_case , __snake_case , __snake_case ): # This array is filled by BFS and to store path _UpperCamelCase = [-1] * (len(__snake_case )) _UpperCamelCase = 0 while bfs(__snake_case , __snake_case , __snake_case , __snake_case ): _UpperCamelCase = float('''Inf''' ) _UpperCamelCase = sink while s != source: # Find the minimum value in select path _UpperCamelCase = min(__snake_case , graph[parent[s]][s] ) _UpperCamelCase = parent[s] max_flow += path_flow _UpperCamelCase = sink while v != source: _UpperCamelCase = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow _UpperCamelCase = parent[v] return max_flow _lowerCAmelCase = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] _lowerCAmelCase, _lowerCAmelCase = 0, 5 print(ford_fulkerson(graph, source, sink))
71
0
import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} _lowerCAmelCase = { "vocab_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", }, "merges_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt", }, "tokenizer_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json", }, } _lowerCAmelCase = { "allenai/led-base-16384": 16_384, } class lowerCAmelCase_ ( lowercase__ ): UpperCAmelCase = VOCAB_FILES_NAMES UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase = LEDTokenizer UpperCAmelCase = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[Any] , _A : Optional[Any]=None , _A : Dict=None , _A : Tuple=None , _A : Union[str, Any]="replace" , _A : Tuple="<s>" , _A : Optional[Any]="</s>" , _A : Tuple="</s>" , _A : List[str]="<s>" , _A : Tuple="<unk>" , _A : Dict="<pad>" , _A : Dict="<mask>" , _A : Any=False , _A : Any=True , **_A : List[Any] , ): super().__init__( __lowercase , __lowercase , tokenizer_file=__lowercase , errors=__lowercase , bos_token=__lowercase , eos_token=__lowercase , sep_token=__lowercase , cls_token=__lowercase , unk_token=__lowercase , pad_token=__lowercase , mask_token=__lowercase , add_prefix_space=__lowercase , trim_offsets=__lowercase , **__lowercase , ) _UpperCamelCase = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , __lowercase ) != add_prefix_space: _UpperCamelCase = getattr(__lowercase , pre_tok_state.pop('''type''' ) ) _UpperCamelCase = add_prefix_space _UpperCamelCase = pre_tok_class(**__lowercase ) _UpperCamelCase = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` _UpperCamelCase = '''post_processor''' _UpperCamelCase = getattr(self.backend_tokenizer , __lowercase , __lowercase ) if tokenizer_component_instance: _UpperCamelCase = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _UpperCamelCase = tuple(state['''sep'''] ) if "cls" in state: _UpperCamelCase = tuple(state['''cls'''] ) _UpperCamelCase = False if state.get('''add_prefix_space''' , __lowercase ) != add_prefix_space: _UpperCamelCase = add_prefix_space _UpperCamelCase = True if state.get('''trim_offsets''' , __lowercase ) != trim_offsets: _UpperCamelCase = trim_offsets _UpperCamelCase = True if changes_to_apply: _UpperCamelCase = getattr(__lowercase , state.pop('''type''' ) ) _UpperCamelCase = component_class(**__lowercase ) setattr(self.backend_tokenizer , __lowercase , __lowercase ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def UpperCamelCase_ ( self : str ): if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def UpperCamelCase_ ( self : Optional[int] , _A : Dict ): _UpperCamelCase = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else value _UpperCamelCase = value def UpperCamelCase_ ( self : Any , *_A : List[Any] , **_A : Optional[Any] ): _UpperCamelCase = kwargs.get('''is_split_into_words''' , __lowercase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._batch_encode_plus(*__lowercase , **__lowercase ) def UpperCamelCase_ ( self : int , *_A : Union[str, Any] , **_A : List[str] ): _UpperCamelCase = kwargs.get('''is_split_into_words''' , __lowercase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._encode_plus(*__lowercase , **__lowercase ) def UpperCamelCase_ ( self : Optional[Any] , _A : str , _A : Optional[str] = None ): _UpperCamelCase = self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase ) def UpperCamelCase_ ( self : List[str] , _A : int , _A : Optional[int]=None ): _UpperCamelCase = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def UpperCamelCase_ ( self : int , _A : List[int] , _A : Optional[List[int]] = None ): _UpperCamelCase = [self.sep_token_id] _UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCamelCase_ ( self : Union[str, Any] , _A : Union[Dict[str, EncodedInput], BatchEncoding] , _A : Optional[int] = None , _A : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , _A : Optional[int] = None , _A : Optional[bool] = None , ): _UpperCamelCase = super()._pad( encoded_inputs=__lowercase , max_length=__lowercase , padding_strategy=__lowercase , pad_to_multiple_of=__lowercase , return_attention_mask=__lowercase , ) # Load from model defaults if return_attention_mask is None: _UpperCamelCase = '''attention_mask''' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: _UpperCamelCase = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. _UpperCamelCase = len(encoded_inputs['''global_attention_mask'''] ) != len(__lowercase ) if needs_to_be_padded: _UpperCamelCase = len(__lowercase ) - len(encoded_inputs['''global_attention_mask'''] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` _UpperCamelCase = ( encoded_inputs['''global_attention_mask'''] + [-1] * difference ) elif self.padding_side == "left": _UpperCamelCase = [-1] * difference + encoded_inputs[ '''global_attention_mask''' ] else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return encoded_inputs
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _lowerCAmelCase = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
71
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCAmelCase = { """configuration_bert""": ["""BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BertConfig""", """BertOnnxConfig"""], """tokenization_bert""": ["""BasicTokenizer""", """BertTokenizer""", """WordpieceTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = ["""BertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ """BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BertForMaskedLM""", """BertForMultipleChoice""", """BertForNextSentencePrediction""", """BertForPreTraining""", """BertForQuestionAnswering""", """BertForSequenceClassification""", """BertForTokenClassification""", """BertLayer""", """BertLMHeadModel""", """BertModel""", """BertPreTrainedModel""", """load_tf_weights_in_bert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ """TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBertEmbeddings""", """TFBertForMaskedLM""", """TFBertForMultipleChoice""", """TFBertForNextSentencePrediction""", """TFBertForPreTraining""", """TFBertForQuestionAnswering""", """TFBertForSequenceClassification""", """TFBertForTokenClassification""", """TFBertLMHeadModel""", """TFBertMainLayer""", """TFBertModel""", """TFBertPreTrainedModel""", ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = ["""TFBertTokenizer"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ """FlaxBertForCausalLM""", """FlaxBertForMaskedLM""", """FlaxBertForMultipleChoice""", """FlaxBertForNextSentencePrediction""", """FlaxBertForPreTraining""", """FlaxBertForQuestionAnswering""", """FlaxBertForSequenceClassification""", """FlaxBertForTokenClassification""", """FlaxBertModel""", """FlaxBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
716
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Any ): _UpperCamelCase = tempfile.mkdtemp() # fmt: off _UpperCamelCase = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on _UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) _UpperCamelCase = { '''do_resize''': True, '''size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } _UpperCamelCase = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_A , _A ) def UpperCamelCase_ ( self : Tuple , **_A : Optional[Any] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : List[Any] , **_A : Union[str, Any] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCamelCase_ ( self : int ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _UpperCamelCase = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = self.get_image_processor() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCamelCase_ ( self : Optional[Any] ): _UpperCamelCase = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _UpperCamelCase = self.get_image_processor(do_normalize=_A , padding_value=1.0 ) _UpperCamelCase = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = image_processor(_A , return_tensors='''np''' ) _UpperCamelCase = processor(images=_A , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = processor(text=_A ) _UpperCamelCase = tokenizer(_A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase_ ( self : Union[str, Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_A ): processor() def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _UpperCamelCase = processor.batch_decode(_A ) _UpperCamelCase = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A ) def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = self.get_image_processor() _UpperCamelCase = self.get_tokenizer() _UpperCamelCase = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) _UpperCamelCase = '''lower newer''' _UpperCamelCase = self.prepare_image_inputs() _UpperCamelCase = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
71
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = '''▁''' _lowerCAmelCase = {'''vocab_file''': '''sentencepiece.bpe.model'''} _lowerCAmelCase = { '''vocab_file''': { '''facebook/mbart-large-50-one-to-many-mmt''': ( '''https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model''' ), } } _lowerCAmelCase = { '''facebook/mbart-large-50-one-to-many-mmt''': 1_024, } # fmt: off _lowerCAmelCase = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN''', '''af_ZA''', '''az_AZ''', '''bn_IN''', '''fa_IR''', '''he_IL''', '''hr_HR''', '''id_ID''', '''ka_GE''', '''km_KH''', '''mk_MK''', '''ml_IN''', '''mn_MN''', '''mr_IN''', '''pl_PL''', '''ps_AF''', '''pt_XX''', '''sv_SE''', '''sw_KE''', '''ta_IN''', '''te_IN''', '''th_TH''', '''tl_XX''', '''uk_UA''', '''ur_PK''', '''xh_ZA''', '''gl_ES''', '''sl_SI'''] class lowerCAmelCase_ ( UpperCamelCase__ ): UpperCAmelCase = VOCAB_FILES_NAMES UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase = ["""input_ids""", """attention_mask"""] UpperCAmelCase = [] UpperCAmelCase = [] def __init__( self : Optional[int] , _A : Any , _A : Union[str, Any]=None , _A : Union[str, Any]=None , _A : Any="</s>" , _A : Optional[int]="</s>" , _A : Tuple="<s>" , _A : Union[str, Any]="<unk>" , _A : str="<pad>" , _A : Union[str, Any]="<mask>" , _A : Tuple = None , **_A : List[str] , ): # Mask token behave like a normal word, i.e. include the space before it _UpperCamelCase = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else mask_token _UpperCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs _UpperCamelCase = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=_A , tgt_lang=_A , eos_token=_A , unk_token=_A , sep_token=_A , cls_token=_A , pad_token=_A , mask_token=_A , sp_model_kwargs=self.sp_model_kwargs , **_A , ) _UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_A ) ) _UpperCamelCase = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token _UpperCamelCase = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab _UpperCamelCase = 1 _UpperCamelCase = len(self.sp_model ) _UpperCamelCase = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_A ) } _UpperCamelCase = {v: k for k, v in self.lang_code_to_id.items()} _UpperCamelCase = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) _UpperCamelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} _UpperCamelCase = src_lang if src_lang is not None else '''en_XX''' _UpperCamelCase = self.lang_code_to_id[self._src_lang] _UpperCamelCase = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def UpperCamelCase_ ( self : List[Any] ): return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def UpperCamelCase_ ( self : str ): return self._src_lang @src_lang.setter def UpperCamelCase_ ( self : str , _A : List[str] ): _UpperCamelCase = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : Union[str, Any] ): _UpperCamelCase = self.__dict__.copy() _UpperCamelCase = None return state def __setstate__( self : Tuple , _A : Tuple ): _UpperCamelCase = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _UpperCamelCase = {} _UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = {self.convert_ids_to_tokens(_A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : Optional[int] , _A : int ): return self.sp_model.encode(_A , out_type=_A ) def UpperCamelCase_ ( self : str , _A : Optional[Any] ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _UpperCamelCase = self.sp_model.PieceToId(_A ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def UpperCamelCase_ ( self : Any , _A : str ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def UpperCamelCase_ ( self : Optional[int] , _A : Any ): _UpperCamelCase = [] _UpperCamelCase = '''''' _UpperCamelCase = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_A ) + token _UpperCamelCase = True _UpperCamelCase = [] else: current_sub_tokens.append(_A ) _UpperCamelCase = False out_string += self.sp_model.decode(_A ) return out_string.strip() def UpperCamelCase_ ( self : int , _A : Optional[Any] , _A : Tuple = None ): if not os.path.isdir(_A ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return _UpperCamelCase = 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 = self.sp_model.serialized_model_proto() fi.write(_A ) return (out_vocab_file,) def UpperCamelCase_ ( self : List[Any] , _A : str , _A : Dict = None , _A : List[str] = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A ) _UpperCamelCase = [1] * len(self.prefix_tokens ) _UpperCamelCase = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(_A )) + suffix_ones return prefix_ones + ([0] * len(_A )) + ([0] * len(_A )) + suffix_ones def UpperCamelCase_ ( self : Optional[int] , _A : Tuple , _A : Optional[int] = 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 UpperCamelCase_ ( self : Tuple , _A : Optional[Any] , _A : int , _A : Optional[Any] , _A : Optional[Any] , **_A : Any ): 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 = src_lang _UpperCamelCase = self(_A , add_special_tokens=_A , return_tensors=_A , **_A ) _UpperCamelCase = self.convert_tokens_to_ids(_A ) _UpperCamelCase = tgt_lang_id return inputs def UpperCamelCase_ ( self : Tuple , _A : List[str] , _A : int = "en_XX" , _A : Dict = None , _A : int = "ro_RO" , **_A : Optional[Any] , ): _UpperCamelCase = src_lang _UpperCamelCase = tgt_lang return super().prepare_seqaseq_batch(_A , _A , **_A ) def UpperCamelCase_ ( self : List[Any] ): return self.set_src_lang_special_tokens(self.src_lang ) def UpperCamelCase_ ( self : Union[str, Any] ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def UpperCamelCase_ ( self : List[str] , _A : List[Any] ): _UpperCamelCase = self.lang_code_to_id[src_lang] _UpperCamelCase = [self.cur_lang_code_id] _UpperCamelCase = [self.eos_token_id] def UpperCamelCase_ ( self : Dict , _A : Union[str, Any] ): _UpperCamelCase = self.lang_code_to_id[tgt_lang] _UpperCamelCase = [self.cur_lang_code_id] _UpperCamelCase = [self.eos_token_id]
717
def _snake_case ( __snake_case , __snake_case , __snake_case ): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__snake_case , n - 1 , __snake_case ) * a) % mod else: _UpperCamelCase = binary_exponentiation(__snake_case , n / 2 , __snake_case ) return (b * b) % mod # a prime number _lowerCAmelCase = 701 _lowerCAmelCase = 1_000_000_000 _lowerCAmelCase = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
71
0
def _snake_case ( __snake_case ): _UpperCamelCase = len(__lowerCAmelCase ) _UpperCamelCase = len(matrix[0] ) _UpperCamelCase = min(__lowerCAmelCase , __lowerCAmelCase ) for row in range(__lowerCAmelCase ): # 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 , __lowerCAmelCase ): _UpperCamelCase = matrix[col][row] / matrix[row][row] for i in range(__lowerCAmelCase , __lowerCAmelCase ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows _UpperCamelCase = True for i in range(row + 1 , __lowerCAmelCase ): if matrix[i][row] != 0: _UpperCamelCase = matrix[i], matrix[row] _UpperCamelCase = False break if reduce: rank -= 1 for i in range(__lowerCAmelCase ): _UpperCamelCase = 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()
718
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = (1 - _cos) / 2 _UpperCamelCase = 1 - _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = (1 + _cos) / 2 _UpperCamelCase = -1 - _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = _sin / 2 _UpperCamelCase = 0 _UpperCamelCase = -ba _UpperCamelCase = 1 + alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 1 - alpha _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 + alpha _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = 1 + alpha * big_a _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha * big_a _UpperCamelCase = 1 + alpha / big_a _UpperCamelCase = -2 * _cos _UpperCamelCase = 1 - alpha / big_a _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = (big_a + 1) - (big_a - 1) * _cos _UpperCamelCase = (big_a + 1) + (big_a - 1) * _cos _UpperCamelCase = (big_a - 1) - (big_a + 1) * _cos _UpperCamelCase = (big_a - 1) + (big_a + 1) * _cos _UpperCamelCase = 2 * sqrt(__snake_case ) * alpha _UpperCamelCase = big_a * (pmc + aaa) _UpperCamelCase = 2 * big_a * mpc _UpperCamelCase = big_a * (pmc - aaa) _UpperCamelCase = ppmc + aaa _UpperCamelCase = -2 * pmpc _UpperCamelCase = ppmc - aaa _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _snake_case ( __snake_case , __snake_case , __snake_case , __snake_case = 1 / sqrt(2 ) , ): _UpperCamelCase = tau * frequency / samplerate _UpperCamelCase = sin(__snake_case ) _UpperCamelCase = cos(__snake_case ) _UpperCamelCase = _sin / (2 * q_factor) _UpperCamelCase = 10 ** (gain_db / 40) _UpperCamelCase = (big_a + 1) - (big_a - 1) * _cos _UpperCamelCase = (big_a + 1) + (big_a - 1) * _cos _UpperCamelCase = (big_a - 1) - (big_a + 1) * _cos _UpperCamelCase = (big_a - 1) + (big_a + 1) * _cos _UpperCamelCase = 2 * sqrt(__snake_case ) * alpha _UpperCamelCase = big_a * (ppmc + aaa) _UpperCamelCase = -2 * big_a * pmpc _UpperCamelCase = big_a * (ppmc - aaa) _UpperCamelCase = pmc + aaa _UpperCamelCase = 2 * mpc _UpperCamelCase = pmc - aaa _UpperCamelCase = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
71
0