code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase = {'''configuration_xlnet''': ['''XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLNetConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = ['''XLNetTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = ['''XLNetTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ '''XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLNetForMultipleChoice''', '''XLNetForQuestionAnswering''', '''XLNetForQuestionAnsweringSimple''', '''XLNetForSequenceClassification''', '''XLNetForTokenClassification''', '''XLNetLMHeadModel''', '''XLNetModel''', '''XLNetPreTrainedModel''', '''load_tf_weights_in_xlnet''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ '''TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLNetForMultipleChoice''', '''TFXLNetForQuestionAnsweringSimple''', '''TFXLNetForSequenceClassification''', '''TFXLNetForTokenClassification''', '''TFXLNetLMHeadModel''', '''TFXLNetMainLayer''', '''TFXLNetModel''', '''TFXLNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
188
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase = { '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''], '''tokenization_mvp''': ['''MvpTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = ['''MvpTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ '''MVP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MvpForCausalLM''', '''MvpForConditionalGeneration''', '''MvpForQuestionAnswering''', '''MvpForSequenceClassification''', '''MvpModel''', '''MvpPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
188
1
'''simple docstring''' import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def a ( __a , __a , __a ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ :List[Any] = OmegaConf.load(__a ) UpperCamelCase__ :Optional[int] = torch.load(__a , map_location='''cpu''' )['''model'''] UpperCamelCase__ :Any = list(state_dict.keys() ) # extract state_dict for VQVAE UpperCamelCase__ :Union[str, Any] = {} UpperCamelCase__ :str = '''first_stage_model.''' for key in keys: if key.startswith(__a ): UpperCamelCase__ :List[str] = state_dict[key] # extract state_dict for UNetLDM UpperCamelCase__ :Any = {} UpperCamelCase__ :Any = '''model.diffusion_model.''' for key in keys: if key.startswith(__a ): UpperCamelCase__ :Any = state_dict[key] UpperCamelCase__ :Union[str, Any] = config.model.params.first_stage_config.params UpperCamelCase__ :Optional[int] = config.model.params.unet_config.params UpperCamelCase__ :Optional[int] = VQModel(**__a ).eval() vqvae.load_state_dict(__a ) UpperCamelCase__ :List[Any] = UNetLDMModel(**__a ).eval() unet.load_state_dict(__a ) UpperCamelCase__ :Any = DDIMScheduler( timesteps=config.model.params.timesteps , beta_schedule='''scaled_linear''' , beta_start=config.model.params.linear_start , beta_end=config.model.params.linear_end , clip_sample=__a , ) UpperCamelCase__ :Any = LDMPipeline(__a , __a , __a ) pipeline.save_pretrained(__a ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument('''--checkpoint_path''', type=str, required=True) parser.add_argument('''--config_path''', type=str, required=True) parser.add_argument('''--output_path''', type=str, required=True) __snake_case = parser.parse_args() convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
219
'''simple docstring''' import argparse from collections import defaultdict import yaml __snake_case = '''docs/source/en/_toctree.yml''' def a ( __a ) -> int: '''simple docstring''' UpperCamelCase__ :int = defaultdict(__a ) UpperCamelCase__ :int = [] UpperCamelCase__ :int = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({'''local''': doc['''local'''], '''title''': doc['''title''']} ) else: new_doc_list.append(__a ) UpperCamelCase__ :Union[str, Any] = new_doc_list UpperCamelCase__ :Tuple = [key for key, value in counts.items() if value > 1] UpperCamelCase__ :Union[str, Any] = [] for duplicate_key in duplicates: UpperCamelCase__ :Dict = list({doc['''title'''] for doc in doc_list if doc['''local'''] == duplicate_key} ) if len(__a ) > 1: raise ValueError( f'''{duplicate_key} is present several times in the documentation table of content at ''' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if '''local''' not in counts or counts[doc['''local''']] == 1] ) UpperCamelCase__ :Union[str, Any] = sorted(__a , key=lambda __a : s["title"].lower() ) # "overview" gets special treatment and is always first if len(__a ) > 1: raise ValueError('''{doc_list} has two \'overview\' docs which is not allowed.''' ) overview_doc.extend(__a ) # Sort return overview_doc def a ( __a=False ) -> Any: '''simple docstring''' with open(__a , encoding='''utf-8''' ) as f: UpperCamelCase__ :Any = yaml.safe_load(f.read() ) # Get to the API doc UpperCamelCase__ :str = 0 while content[api_idx]["title"] != "API": api_idx += 1 UpperCamelCase__ :str = content[api_idx]['''sections'''] # Then to the model doc UpperCamelCase__ :Optional[Any] = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 UpperCamelCase__ :List[Any] = api_doc[scheduler_idx]['''sections'''] UpperCamelCase__ :Union[str, Any] = clean_doc_toc(__a ) UpperCamelCase__ :List[Any] = False if new_scheduler_doc != scheduler_doc: UpperCamelCase__ :Optional[int] = True if overwrite: UpperCamelCase__ :Dict = new_scheduler_doc if diff: if overwrite: UpperCamelCase__ :Any = api_doc with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) def a ( __a=False ) -> Optional[Any]: '''simple docstring''' with open(__a , encoding='''utf-8''' ) as f: UpperCamelCase__ :str = yaml.safe_load(f.read() ) # Get to the API doc UpperCamelCase__ :Optional[Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 UpperCamelCase__ :Any = content[api_idx]['''sections'''] # Then to the model doc UpperCamelCase__ :str = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 UpperCamelCase__ :Any = False UpperCamelCase__ :Union[str, Any] = api_doc[pipeline_idx]['''sections'''] UpperCamelCase__ :Tuple = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: UpperCamelCase__ :Dict = pipeline_doc['''section'''] UpperCamelCase__ :Optional[Any] = clean_doc_toc(__a ) if overwrite: UpperCamelCase__ :Optional[int] = new_sub_pipeline_doc new_pipeline_docs.append(__a ) # sort overall pipeline doc UpperCamelCase__ :Optional[Any] = clean_doc_toc(__a ) if new_pipeline_docs != pipeline_docs: UpperCamelCase__ :int = True if overwrite: UpperCamelCase__ :Union[str, Any] = new_pipeline_docs if diff: if overwrite: UpperCamelCase__ :Dict = api_doc with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') __snake_case = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
219
1
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. __a : Tuple = {"""LayoutLMv2Config""", """LayoutLMv3Config"""} @is_pipeline_test class _UpperCamelCase ( unittest.TestCase ): """simple docstring""" __a : Optional[Any] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __a : Dict = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: __a : Union[str, Any] = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: __a : Dict = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' __lowercase = ZeroShotClassificationPipeline( model=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , candidate_labels=['''polics''', '''health'''] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' __lowercase = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics''' ) self.assertEqual(lowerCAmelCase__ , {'''sequence''': ANY(lowerCAmelCase__ ), '''labels''': [ANY(lowerCAmelCase__ )], '''scores''': [ANY(lowerCAmelCase__ )]} ) # No kwarg __lowercase = classifier('''Who are you voting for in 2020?''' , ['''politics'''] ) self.assertEqual(lowerCAmelCase__ , {'''sequence''': ANY(lowerCAmelCase__ ), '''labels''': [ANY(lowerCAmelCase__ )], '''scores''': [ANY(lowerCAmelCase__ )]} ) __lowercase = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics'''] ) self.assertEqual(lowerCAmelCase__ , {'''sequence''': ANY(lowerCAmelCase__ ), '''labels''': [ANY(lowerCAmelCase__ )], '''scores''': [ANY(lowerCAmelCase__ )]} ) __lowercase = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics, public health''' ) self.assertEqual( lowerCAmelCase__ , {'''sequence''': ANY(lowerCAmelCase__ ), '''labels''': [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )], '''scores''': [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) __lowercase = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health'''] ) self.assertEqual( lowerCAmelCase__ , {'''sequence''': ANY(lowerCAmelCase__ ), '''labels''': [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )], '''scores''': [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) __lowercase = classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''This text is about {}''' ) self.assertEqual(lowerCAmelCase__ , {'''sequence''': ANY(lowerCAmelCase__ ), '''labels''': [ANY(lowerCAmelCase__ )], '''scores''': [ANY(lowerCAmelCase__ )]} ) # https://github.com/huggingface/transformers/issues/13846 __lowercase = classifier(['''I am happy'''] , ['''positive''', '''negative'''] ) self.assertEqual( lowerCAmelCase__ , [ {'''sequence''': ANY(lowerCAmelCase__ ), '''labels''': [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )], '''scores''': [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )]} for i in range(1 ) ] , ) __lowercase = classifier(['''I am happy''', '''I am sad'''] , ['''positive''', '''negative'''] ) self.assertEqual( lowerCAmelCase__ , [ {'''sequence''': ANY(lowerCAmelCase__ ), '''labels''': [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )], '''scores''': [ANY(lowerCAmelCase__ ), ANY(lowerCAmelCase__ )]} for i in range(2 ) ] , ) with self.assertRaises(lowerCAmelCase__ ): classifier('''''' , candidate_labels='''politics''' ) with self.assertRaises(lowerCAmelCase__ ): classifier(lowerCAmelCase__ , candidate_labels='''politics''' ) with self.assertRaises(lowerCAmelCase__ ): classifier('''Who are you voting for in 2020?''' , candidate_labels='''''' ) with self.assertRaises(lowerCAmelCase__ ): classifier('''Who are you voting for in 2020?''' , candidate_labels=lowerCAmelCase__ ) with self.assertRaises(lowerCAmelCase__ ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''Not formatting template''' , ) with self.assertRaises(lowerCAmelCase__ ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template=lowerCAmelCase__ , ) self.run_entailment_id(lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' __lowercase = zero_shot_classifier.model.config __lowercase = config.labelaid __lowercase = zero_shot_classifier.entailment_id __lowercase = {"""LABEL_0""": 0, """LABEL_1""": 1, """LABEL_2""": 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) __lowercase = {"""entailment""": 0, """neutral""": 1, """contradiction""": 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __lowercase = {"""ENTAIL""": 0, """NON-ENTAIL""": 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __lowercase = {"""ENTAIL""": 2, """NEUTRAL""": 1, """CONTR""": 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) __lowercase = original_labelaid self.assertEqual(lowerCAmelCase__ , zero_shot_classifier.entailment_id ) @require_torch def _SCREAMING_SNAKE_CASE ( self ) -> Any: '''simple docstring''' __lowercase = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( '''Who are you voting for in 2020?''' * 1_00 , candidate_labels=['''politics''', '''public health''', '''science'''] ) @require_torch def _SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' __lowercase = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) __lowercase = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(lowerCAmelCase__ ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @require_tf def _SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' __lowercase = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''tf''' , ) __lowercase = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(lowerCAmelCase__ ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @slow @require_torch def _SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' __lowercase = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''pt''' ) __lowercase = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(lowerCAmelCase__ ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) __lowercase = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=lowerCAmelCase__ , ) self.assertEqual( nested_simplify(lowerCAmelCase__ ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , ) @slow @require_tf def _SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: '''simple docstring''' __lowercase = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''tf''' ) __lowercase = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(lowerCAmelCase__ ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) __lowercase = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=lowerCAmelCase__ , ) self.assertEqual( nested_simplify(lowerCAmelCase__ ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.817, 0.713, 0.018, 0.018], } , )
210
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def _snake_case( SCREAMING_SNAKE_CASE__ ) -> Optional[Any]: if "cls_token" in name: lowercase : List[Any] = name.replace("""cls_token""" , """vit.embeddings.cls_token""" ) if "mask_token" in name: lowercase : Any = name.replace("""mask_token""" , """decoder.mask_token""" ) if "decoder_pos_embed" in name: lowercase : str = name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: lowercase : List[str] = name.replace("""pos_embed""" , """vit.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: lowercase : Tuple = name.replace("""patch_embed.proj""" , """vit.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: lowercase : int = name.replace("""patch_embed.norm""" , """vit.embeddings.norm""" ) if "decoder_blocks" in name: lowercase : Tuple = name.replace("""decoder_blocks""" , """decoder.decoder_layers""" ) if "blocks" in name: lowercase : List[Any] = name.replace("""blocks""" , """vit.encoder.layer""" ) if "attn.proj" in name: lowercase : List[str] = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: lowercase : Union[str, Any] = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: lowercase : Optional[Any] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: lowercase : Union[str, Any] = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: lowercase : Dict = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: lowercase : Dict = name.replace("""mlp.fc2""" , """output.dense""" ) if "decoder_embed" in name: lowercase : List[str] = name.replace("""decoder_embed""" , """decoder.decoder_embed""" ) if "decoder_norm" in name: lowercase : Dict = name.replace("""decoder_norm""" , """decoder.decoder_norm""" ) if "decoder_pred" in name: lowercase : List[str] = name.replace("""decoder_pred""" , """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name: lowercase : Tuple = name.replace("""norm.weight""" , """vit.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name: lowercase : int = name.replace("""norm.bias""" , """vit.layernorm.bias""" ) return name def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[Any]: for key in orig_state_dict.copy().keys(): lowercase : List[Any] = orig_state_dict.pop(SCREAMING_SNAKE_CASE__ ) if "qkv" in key: lowercase : int = key.split(""".""" ) lowercase : List[str] = int(key_split[1] ) if "decoder_blocks" in key: lowercase : Tuple = config.decoder_hidden_size lowercase : int = """decoder.decoder_layers.""" if "weight" in key: lowercase : List[Any] = val[:dim, :] lowercase : Tuple = val[dim : dim * 2, :] lowercase : List[Any] = val[-dim:, :] elif "bias" in key: lowercase : str = val[:dim] lowercase : Dict = val[dim : dim * 2] lowercase : Union[str, Any] = val[-dim:] else: lowercase : Tuple = config.hidden_size lowercase : Union[str, Any] = """vit.encoder.layer.""" if "weight" in key: lowercase : Tuple = val[:dim, :] lowercase : List[str] = val[dim : dim * 2, :] lowercase : Dict = val[-dim:, :] elif "bias" in key: lowercase : Any = val[:dim] lowercase : str = val[dim : dim * 2] lowercase : Union[str, Any] = val[-dim:] else: lowercase : Union[str, Any] = val return orig_state_dict def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> int: lowercase : int = ViTMAEConfig() if "large" in checkpoint_url: lowercase : Dict = 1_024 lowercase : str = 4_096 lowercase : Optional[Any] = 24 lowercase : Optional[Any] = 16 elif "huge" in checkpoint_url: lowercase : int = 14 lowercase : List[Any] = 1_280 lowercase : int = 5_120 lowercase : List[Any] = 32 lowercase : Any = 16 lowercase : List[str] = ViTMAEForPreTraining(SCREAMING_SNAKE_CASE__ ) lowercase : Optional[Any] = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location="""cpu""" )["""model"""] lowercase : Tuple = ViTMAEImageProcessor(size=config.image_size ) lowercase : Optional[int] = convert_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) model.load_state_dict(SCREAMING_SNAKE_CASE__ ) model.eval() lowercase : Union[str, Any] = """https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg""" lowercase : Union[str, Any] = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ) lowercase : Optional[Any] = ViTMAEImageProcessor(size=config.image_size ) lowercase : List[Any] = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) lowercase : int = model(**SCREAMING_SNAKE_CASE__ ) lowercase : str = outputs.logits if "large" in checkpoint_url: lowercase : List[Any] = torch.tensor( [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]] ) elif "huge" in checkpoint_url: lowercase : Tuple = torch.tensor( [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]] ) else: lowercase : List[str] = torch.tensor( [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) print(f"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth""", type=str, help="""URL of the checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowercase : List[Any] = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
20
0
import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def snake_case_ ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Optional[int]=1024 , lowerCAmelCase_ : Union[str, Any]=1024 , lowerCAmelCase_ : Any=False , **lowerCAmelCase_ : List[Any] ): __lowercase : List[str] = AutoTokenizer.from_pretrained(lowerCamelCase__ ) __lowercase : Optional[Any] = SeqaSeqDataset(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , type_path="""train""" , **lowerCamelCase__ ) __lowercase : List[str] = tok.pad_token_id def get_lens(lowerCAmelCase_ : str ): __lowercase : int = tqdm( DataLoader(lowerCamelCase__ , batch_size=512 , num_workers=8 , shuffle=lowerCamelCase__ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) __lowercase : str = [] for batch in dl: __lowercase : str = batch['''input_ids'''].ne(lowerCamelCase__ ).sum(1 ).tolist() __lowercase : str = batch['''labels'''].ne(lowerCamelCase__ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(lowerCamelCase__ , lowerCamelCase__ ): max_lens.append(max(lowerCamelCase__ , lowerCamelCase__ ) ) else: max_lens.extend(lowerCamelCase__ ) return max_lens __lowercase : Any = get_lens(lowerCamelCase__ ) __lowercase : Optional[Any] = SeqaSeqDataset(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , type_path="""val""" , **lowerCamelCase__ ) __lowercase : Any = get_lens(lowerCamelCase__ ) pickle_save(lowerCamelCase__ , train_ds.len_file ) pickle_save(lowerCamelCase__ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
354
from scipy.stats import spearmanr import datasets lowerCamelCase : List[str] = ''' The Spearman rank-order correlation coefficient is a measure of the relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Positive correlations imply that as data in dataset x increases, so does data in dataset y. Negative correlations imply that as x increases, y decreases. Correlations of -1 or +1 imply an exact monotonic relationship. Unlike the Pearson correlation, the Spearman correlation does not assume that both datasets are normally distributed. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Spearman correlation at least as extreme as the one computed from these datasets. The p-values are not entirely reliable but are probably reasonable for datasets larger than 500 or so. ''' lowerCamelCase : List[str] = ''' Args: predictions (`List[float]`): Predicted labels, as returned by a model. references (`List[float]`): Ground truth labels. return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns only the spearmanr score. Defaults to `False`. Returns: spearmanr (`float`): Spearman correlation coefficient. p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input. Examples: Example 1: >>> spearmanr_metric = datasets.load_metric("spearmanr") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4]) >>> print(results) {\'spearmanr\': -0.7} Example 2: >>> spearmanr_metric = datasets.load_metric("spearmanr") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], ... predictions=[10, 9, 2.5, 6, 4], ... return_pvalue=True) >>> print(results[\'spearmanr\']) -0.7 >>> print(round(results[\'spearmanr_pvalue\'], 2)) 0.19 ''' lowerCamelCase : Union[str, Any] = r'''\ @book{kokoska2000crc, title={CRC standard probability and statistics tables and formulae}, author={Kokoska, Stephen and Zwillinger, Daniel}, year={2000}, publisher={Crc Press} } @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def lowerCAmelCase ( self : Tuple ) -> Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""float""" ), """references""": datasets.Value("""float""" ), } ) , reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"""] , ) def lowerCAmelCase ( self : List[Any] , __a : str , __a : Any , __a : Optional[int]=False ) -> List[str]: """simple docstring""" __lowercase : Optional[Any] = spearmanr(__a , __a ) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
306
0
def _snake_case( SCREAMING_SNAKE_CASE__ ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence lowercase : List[str] = gray_code_sequence_string(SCREAMING_SNAKE_CASE__ ) # # convert them to integers for i in range(len(SCREAMING_SNAKE_CASE__ ) ): lowercase : List[Any] = int(sequence[i] , 2 ) return sequence def _snake_case( SCREAMING_SNAKE_CASE__ ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] lowercase : Union[str, Any] = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits lowercase : Optional[int] = gray_code_sequence_string(bit_count - 1 ) lowercase : Tuple = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): lowercase : Any = """0""" + smaller_sequence[i] sequence.append(SCREAMING_SNAKE_CASE__ ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): lowercase : Dict = """1""" + smaller_sequence[i] sequence.append(SCREAMING_SNAKE_CASE__ ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
20
from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING lowercase : Any = logging.get_logger(__name__) @add_end_docstrings(lowerCAmelCase ) class __snake_case ( lowerCAmelCase ): def __init__( self ,*snake_case ,**snake_case ): '''simple docstring''' super().__init__(*snake_case ,**snake_case ) requires_backends(self ,"""vision""" ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == """tf""" else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def _SCREAMING_SNAKE_CASE ( self ,snake_case=None ): '''simple docstring''' lowercase : List[Any] = {} if top_k is not None: lowercase : int = top_k return {}, {}, postprocess_params def __call__( self ,snake_case ,**snake_case ): '''simple docstring''' return super().__call__(snake_case ,**snake_case ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' lowercase : Any = load_image(snake_case ) lowercase : List[Any] = self.image_processor(images=snake_case ,return_tensors=self.framework ) return model_inputs def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' lowercase : int = self.model(**snake_case ) return model_outputs def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case=5 ): '''simple docstring''' if top_k > self.model.config.num_labels: lowercase : Tuple = self.model.config.num_labels if self.framework == "pt": lowercase : str = model_outputs.logits.softmax(-1 )[0] lowercase , lowercase : Dict = probs.topk(snake_case ) elif self.framework == "tf": lowercase : Optional[int] = stable_softmax(model_outputs.logits ,axis=-1 )[0] lowercase : Union[str, Any] = tf.math.top_k(snake_case ,k=snake_case ) lowercase , lowercase : List[str] = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(f"Unsupported framework: {self.framework}" ) lowercase : Tuple = scores.tolist() lowercase : Dict = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(snake_case ,snake_case )]
20
1
import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version UpperCAmelCase : List[Any] = 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""") UpperCAmelCase : Optional[int] = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) UpperCAmelCase : List[str] = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class __lowerCAmelCase : _lowercase : Optional[str] = field( default="""cifar10""" , metadata={"""help""": """Name of a dataset from the datasets package"""}) _lowercase : Optional[str] = field( default=UpperCamelCase__ , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}) _lowercase : Optional[str] = field( default=UpperCamelCase__ , metadata={"""help""": """The column name of the images in the files. If not set, will try to use 'image' or 'img'."""} , ) _lowercase : Optional[str] = field(default=UpperCamelCase__ , metadata={"""help""": """A folder containing the training data."""}) _lowercase : Optional[str] = field(default=UpperCamelCase__ , metadata={"""help""": """A folder containing the validation data."""}) _lowercase : Optional[float] = field( default=0.1_5 , metadata={"""help""": """Percent to split off of train for validation."""}) _lowercase : int = field(default=32 , metadata={"""help""": """The size of the square patches to use for masking."""}) _lowercase : float = field( default=0.6 , metadata={"""help""": """Percentage of patches to mask."""} , ) _lowercase : Optional[int] = field( default=UpperCamelCase__ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) _lowercase : Optional[int] = field( default=UpperCamelCase__ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : List[str] ={} if self.train_dir is not None: a__ : Tuple =self.train_dir if self.validation_dir is not None: a__ : Optional[Any] =self.validation_dir a__ : List[str] =data_files if data_files else None @dataclass class __lowerCAmelCase : _lowercase : str = field( default=UpperCamelCase__ , metadata={ """help""": ( """The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a """ """checkpoint identifier on the hub. """ """Don't set if you want to train a model from scratch.""" ) } , ) _lowercase : Optional[str] = field( default=UpperCamelCase__ , metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(UpperCamelCase__)} , ) _lowercase : Optional[str] = field( default=UpperCamelCase__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}) _lowercase : Optional[str] = field( default=UpperCamelCase__ , 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""" ) } , ) _lowercase : Optional[str] = field( default=UpperCamelCase__ , metadata={"""help""": """Where do you want to store (cache) the pretrained models/datasets downloaded from the hub"""} , ) _lowercase : str = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) _lowercase : str = field(default=UpperCamelCase__ , metadata={"""help""": """Name or path of preprocessor config."""}) _lowercase : bool = field( default=UpperCamelCase__ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) _lowercase : Optional[int] = field( default=UpperCamelCase__ , metadata={ """help""": ( """The size (resolution) of each image. If not specified, will use `image_size` of the configuration.""" ) } , ) _lowercase : Optional[int] = field( default=UpperCamelCase__ , metadata={ """help""": ( """The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration.""" ) } , ) _lowercase : Optional[int] = field( default=UpperCamelCase__ , metadata={"""help""": """Stride to use for the encoder."""} , ) class __lowerCAmelCase : def __init__( self , lowerCAmelCase__=1_9_2 , lowerCAmelCase__=3_2 , lowerCAmelCase__=4 , lowerCAmelCase__=0.6 ) -> List[Any]: '''simple docstring''' a__ : Optional[Any] =input_size a__ : Dict =mask_patch_size a__ : List[Any] =model_patch_size a__ : Optional[Any] =mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError("Input size must be divisible by mask patch size" ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError("Mask patch size must be divisible by model patch size" ) a__ : Tuple =self.input_size // self.mask_patch_size a__ : Dict =self.mask_patch_size // self.model_patch_size a__ : Any =self.rand_size**2 a__ : Optional[int] =int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self ) -> Optional[Any]: '''simple docstring''' a__ : List[str] =np.random.permutation(self.token_count )[: self.mask_count] a__ : str =np.zeros(self.token_count , dtype=lowerCAmelCase__ ) a__ : List[str] =1 a__ : Union[str, Any] =mask.reshape((self.rand_size, self.rand_size) ) a__ : Tuple =mask.repeat(self.scale , axis=0 ).repeat(self.scale , axis=1 ) return torch.tensor(mask.flatten() ) def _A ( SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" a__ : int =torch.stack([example["pixel_values"] for example in examples] ) a__ : List[str] =torch.stack([example["mask"] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def _A ( ): """simple docstring""" a__ : int =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. a__ : List[Any] =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: a__ : str =parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_mim" , SCREAMING_SNAKE_CASE , SCREAMING_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() a__ : Union[str, Any] =training_args.get_process_log_level() logger.setLevel(SCREAMING_SNAKE_CASE ) transformers.utils.logging.set_verbosity(SCREAMING_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. a__ : str =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: a__ : Union[str, Any] =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. a__ : Optional[Any] =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. a__ : Optional[int] =None if "validation" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , SCREAMING_SNAKE_CASE ) and data_args.train_val_split > 0.0: a__ : str =ds["train"].train_test_split(data_args.train_val_split ) a__ : Optional[int] =split["train"] a__ : Dict =split["test"] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. a__ : Tuple ={ "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name_or_path: a__ : int =AutoConfig.from_pretrained(model_args.config_name_or_path , **SCREAMING_SNAKE_CASE ) elif model_args.model_name_or_path: a__ : Optional[Any] =AutoConfig.from_pretrained(model_args.model_name_or_path , **SCREAMING_SNAKE_CASE ) else: a__ : Dict =CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch." ) if model_args.config_overrides is not None: logger.info(f'''Overriding config: {model_args.config_overrides}''' ) config.update_from_string(model_args.config_overrides ) logger.info(f'''New config: {config}''' ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(SCREAMING_SNAKE_CASE , "decoder_type" ): a__ : Optional[Any] ="simmim" # adapt config a__ : List[Any] =model_args.image_size if model_args.image_size is not None else config.image_size a__ : Union[str, Any] =model_args.patch_size if model_args.patch_size is not None else config.patch_size a__ : List[Any] =( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { "image_size": model_args.image_size, "patch_size": model_args.patch_size, "encoder_stride": model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: a__ : Dict =AutoImageProcessor.from_pretrained(model_args.image_processor_name , **SCREAMING_SNAKE_CASE ) elif model_args.model_name_or_path: a__ : str =AutoImageProcessor.from_pretrained(model_args.model_name_or_path , **SCREAMING_SNAKE_CASE ) else: a__ : Tuple ={ conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } a__ : Any =IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: a__ : Dict =AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("Training new model from scratch" ) a__ : int =AutoModelForMaskedImageModeling.from_config(SCREAMING_SNAKE_CASE ) if training_args.do_train: a__ : Optional[Any] =ds["train"].column_names else: a__ : Dict =ds["validation"].column_names if data_args.image_column_name is not None: a__ : List[str] =data_args.image_column_name elif "image" in column_names: a__ : str ="image" elif "img" in column_names: a__ : int ="img" else: a__ : Optional[Any] =column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py a__ : str =Compose( [ Lambda(lambda SCREAMING_SNAKE_CASE : img.convert("RGB" ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size , scale=(0.6_7, 1.0) , ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) # create mask generator a__ : Optional[int] =MaskGenerator( input_size=model_args.image_size , mask_patch_size=data_args.mask_patch_size , model_patch_size=model_args.patch_size , mask_ratio=data_args.mask_ratio , ) def preprocess_images(SCREAMING_SNAKE_CASE : str ): a__ : int =[transforms(SCREAMING_SNAKE_CASE ) for image in examples[image_column_name]] a__ : Tuple =[mask_generator() for i in range(len(examples[image_column_name] ) )] return examples if training_args.do_train: if "train" not in ds: raise ValueError("--do_train requires a train dataset" ) if data_args.max_train_samples is not None: a__ : List[Any] =ds["train"].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(SCREAMING_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: a__ : int =( ds["validation"].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(SCREAMING_SNAKE_CASE ) # Initialize our trainer a__ : Union[str, Any] =Trainer( model=SCREAMING_SNAKE_CASE , args=SCREAMING_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=SCREAMING_SNAKE_CASE , data_collator=SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: a__ : Optional[Any] =None if training_args.resume_from_checkpoint is not None: a__ : List[str] =training_args.resume_from_checkpoint elif last_checkpoint is not None: a__ : int =last_checkpoint a__ : Optional[int] =trainer.train(resume_from_checkpoint=SCREAMING_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: a__ : str =trainer.evaluate() trainer.log_metrics("eval" , SCREAMING_SNAKE_CASE ) trainer.save_metrics("eval" , SCREAMING_SNAKE_CASE ) # Write model card and (optionally) push to hub a__ : Tuple ={ "finetuned_from": model_args.model_name_or_path, "tasks": "masked-image-modeling", "dataset": data_args.dataset_name, "tags": ["masked-image-modeling"], } if training_args.push_to_hub: trainer.push_to_hub(**SCREAMING_SNAKE_CASE ) else: trainer.create_model_card(**SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
365
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __lowerCAmelCase ( UpperCamelCase__): def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Optional[int] =self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowerCAmelCase__ , "tf_padding" ) ) self.parent.assertTrue(hasattr(lowerCAmelCase__ , "depth_multiplier" ) ) class __lowerCAmelCase : def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=1_3 , lowerCAmelCase__=3 , lowerCAmelCase__=3_2 , lowerCAmelCase__=0.25 , lowerCAmelCase__=8 , lowerCAmelCase__=True , lowerCAmelCase__=1_0_2_4 , lowerCAmelCase__=3_2 , lowerCAmelCase__="relu6" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.02 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=1_0 , lowerCAmelCase__=None , ) -> Dict: '''simple docstring''' a__ : int =parent a__ : Optional[Any] =batch_size a__ : Tuple =num_channels a__ : Dict =image_size a__ : Union[str, Any] =depth_multiplier a__ : List[str] =min_depth a__ : Dict =tf_padding a__ : Any =int(last_hidden_size * depth_multiplier ) a__ : Tuple =output_stride a__ : Optional[Any] =hidden_act a__ : str =classifier_dropout_prob a__ : int =use_labels a__ : List[Any] =is_training a__ : List[str] =num_labels a__ : Dict =initializer_range a__ : Tuple =scope def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : Union[str, Any] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a__ : Any =None a__ : List[Any] =None if self.use_labels: a__ : Dict =ids_tensor([self.batch_size] , self.num_labels ) a__ : Tuple =ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) a__ : Optional[Any] =self.get_config() return config, pixel_values, labels, pixel_labels def _lowercase ( self ) -> str: '''simple docstring''' return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' a__ : Union[str, Any] =MobileNetVaModel(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() a__ : str =model(lowerCAmelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> str: '''simple docstring''' a__ : Any =self.num_labels a__ : Dict =MobileNetVaForImageClassification(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() a__ : Optional[int] =model(lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self ) -> str: '''simple docstring''' a__ : str =self.prepare_config_and_inputs() a__ , a__ , a__ , a__ : List[str] =config_and_inputs a__ : Tuple ={"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase): _lowercase : List[str] = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () _lowercase : Optional[int] = ( {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification} if is_torch_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Optional[int] = False _lowercase : List[str] = False _lowercase : str = False def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : Optional[Any] =MobileNetVaModelTester(self ) a__ : Optional[Any] =MobileNetVaConfigTester(self , config_class=lowerCAmelCase__ , has_text_modality=lowerCAmelCase__ ) def _lowercase ( self ) -> Dict: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds" ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings" ) def _lowercase ( self ) -> List[str]: '''simple docstring''' pass @unittest.skip(reason="MobileNetV1 does not output attentions" ) def _lowercase ( self ) -> Any: '''simple docstring''' pass def _lowercase ( self ) -> str: '''simple docstring''' a__ , a__ : Optional[int] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Optional[int] =model_class(lowerCAmelCase__ ) a__ : str =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : Optional[int] =[*signature.parameters.keys()] a__ : Union[str, Any] =["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCAmelCase__ ) def _lowercase ( self ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase__ ) def _lowercase ( self ) -> List[str]: '''simple docstring''' def check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): a__ : int =model_class(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() with torch.no_grad(): a__ : List[Any] =model(**self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ ) ) a__ : Optional[int] =outputs.hidden_states a__ : Optional[int] =2_6 self.assertEqual(len(lowerCAmelCase__ ) , lowerCAmelCase__ ) a__ , a__ : Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Optional[int] =True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a__ : Union[str, Any] =True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def _lowercase ( self ) -> Any: '''simple docstring''' a__ : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__ ) @slow def _lowercase ( self ) -> Any: '''simple docstring''' for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : List[str] =MobileNetVaModel.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) def _A ( ): """simple docstring""" a__ : Optional[Any] =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase): @cached_property def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224" ) if is_vision_available() else None ) @slow def _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : str =MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224" ).to(lowerCAmelCase__ ) a__ : Optional[Any] =self.default_image_processor a__ : Optional[int] =prepare_img() a__ : Optional[int] =image_processor(images=lowerCAmelCase__ , return_tensors="pt" ).to(lowerCAmelCase__ ) # forward pass with torch.no_grad(): a__ : int =model(**lowerCAmelCase__ ) # verify the logits a__ : str =torch.Size((1, 1_0_0_1) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase__ ) a__ : int =torch.tensor([-4.17_39, -1.12_33, 3.12_05] ).to(lowerCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase__ , atol=1E-4 ) )
148
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = "▁" SCREAMING_SNAKE_CASE__ = {"vocab_file": "sentencepiece.bpe.model"} SCREAMING_SNAKE_CASE__ = { "vocab_file": { "xlm-roberta-base": "https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model", "xlm-roberta-large": "https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model", "xlm-roberta-large-finetuned-conll02-dutch": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll02-spanish": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll03-english": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model" ), "xlm-roberta-large-finetuned-conll03-german": ( "https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model" ), } } SCREAMING_SNAKE_CASE__ = { "xlm-roberta-base": 512, "xlm-roberta-large": 512, "xlm-roberta-large-finetuned-conll02-dutch": 512, "xlm-roberta-large-finetuned-conll02-spanish": 512, "xlm-roberta-large-finetuned-conll03-english": 512, "xlm-roberta-large-finetuned-conll03-german": 512, } class lowercase ( _UpperCAmelCase ): _SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE = ['input_ids', 'attention_mask'] def __init__( self , lowercase , lowercase="<s>" , lowercase="</s>" , lowercase="</s>" , lowercase="<s>" , lowercase="<unk>" , lowercase="<pad>" , lowercase="<mask>" , lowercase = None , **lowercase , ) -> None: # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase = AddedToken(lowercase , lstrip=lowercase , rstrip=lowercase ) if isinstance(lowercase , lowercase ) else mask_token lowerCAmelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=lowercase , eos_token=lowercase , unk_token=lowercase , sep_token=lowercase , cls_token=lowercase , pad_token=lowercase , mask_token=lowercase , sp_model_kwargs=self.sp_model_kwargs , **lowercase , ) lowerCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(lowercase ) ) lowerCAmelCase = 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 lowerCAmelCase = {"""<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 lowerCAmelCase = 1 lowerCAmelCase = len(self.sp_model ) + self.fairseq_offset lowerCAmelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Optional[Any]: lowerCAmelCase = self.__dict__.copy() lowerCAmelCase = None lowerCAmelCase = self.sp_model.serialized_model_proto() return state def __setstate__( self , lowercase ) -> int: lowerCAmelCase = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowerCAmelCase = {} lowerCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _snake_case ( self , lowercase , lowercase = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase = [self.cls_token_id] lowerCAmelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _snake_case ( self , lowercase , lowercase = None , lowercase = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase , token_ids_a=lowercase , already_has_special_tokens=lowercase ) if token_ids_a is None: return [1] + ([0] * len(lowercase )) + [1] return [1] + ([0] * len(lowercase )) + [1, 1] + ([0] * len(lowercase )) + [1] def _snake_case ( self , lowercase , lowercase = None ) -> List[int]: lowerCAmelCase = [self.sep_token_id] lowerCAmelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _snake_case ( self ) -> Optional[Any]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def _snake_case ( self ) -> str: lowerCAmelCase = {self.convert_ids_to_tokens(lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , lowercase ) -> List[str]: return self.sp_model.encode(lowercase , out_type=lowercase ) def _snake_case ( self , lowercase ) -> Tuple: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowerCAmelCase = self.sp_model.PieceToId(lowercase ) # 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 _snake_case ( self , lowercase ) -> List[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 _snake_case ( self , lowercase ) -> List[Any]: lowerCAmelCase = """""".join(lowercase ).replace(lowercase , """ """ ).strip() return out_string def _snake_case ( self , lowercase , lowercase = None ) -> Tuple[str]: if not os.path.isdir(lowercase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase = os.path.join( lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase ) elif not os.path.isfile(self.vocab_file ): with open(lowercase , """wb""" ) as fi: lowerCAmelCase = self.sp_model.serialized_model_proto() fi.write(lowercase ) return (out_vocab_file,)
46
'''simple docstring''' def __lowerCamelCase ( A__ ) -> list: """simple docstring""" UpperCamelCase = len(A__ ) for i in range(1 , A__ ): UpperCamelCase = collection[i] UpperCamelCase = 0 UpperCamelCase = i - 1 while low <= high: UpperCamelCase = (low + high) // 2 if val < collection[mid]: UpperCamelCase = mid - 1 else: UpperCamelCase = mid + 1 for j in range(A__ , A__ , -1 ): UpperCamelCase = collection[j - 1] UpperCamelCase = val return collection if __name__ == "__main__": _lowerCamelCase : int = input("Enter numbers separated by a comma:\n").strip() _lowerCamelCase : Union[str, Any] = [int(item) for item in user_input.split(",")] print(binary_insertion_sort(unsorted))
28
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE :str = { 'configuration_poolformer': [ 'POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PoolFormerConfig', 'PoolFormerOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Optional[Any] = ['PoolFormerFeatureExtractor'] SCREAMING_SNAKE_CASE :Any = ['PoolFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Optional[Any] = [ 'POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'PoolFormerForImageClassification', 'PoolFormerModel', 'PoolFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure)
124
import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = CTRLTokenizer snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : Dict ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __A = ["adapt", "re@@", "a@@", "apt", "c@@", "t", "<unk>"] __A = dict(zip(A ,range(len(A ) ) ) ) __A = ["#version: 0.2", "a p", "ap t</w>", "r e", "a d", "ad apt</w>", ""] __A = {"unk_token": "<unk>"} __A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] ) __A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file ,"w" ,encoding="utf-8" ) as fp: fp.write(json.dumps(A ) + "\n" ) with open(self.merges_file ,"w" ,encoding="utf-8" ) as fp: fp.write("\n".join(A ) ) def UpperCamelCase_ ( self : List[str] ,**A : List[str] ): kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname ,**A ) def UpperCamelCase_ ( self : Optional[int] ,A : Tuple ): __A = "adapt react readapt apt" __A = "adapt react readapt apt" return input_text, output_text def UpperCamelCase_ ( self : Any ): __A = CTRLTokenizer(self.vocab_file ,self.merges_file ,**self.special_tokens_map ) __A = "adapt react readapt apt" __A = "adapt re@@ a@@ c@@ t re@@ adapt apt".split() __A = tokenizer.tokenize(A ) self.assertListEqual(A ,A ) __A = tokens + [tokenizer.unk_token] __A = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) ,A )
124
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig UpperCAmelCase : List[str] ={ """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class _lowercase (lowerCamelCase__ ): '''simple docstring''' lowercase__ = """albert""" def __init__( self , snake_case__=3_0000 , snake_case__=128 , snake_case__=4096 , snake_case__=12 , snake_case__=1 , snake_case__=64 , snake_case__=1_6384 , snake_case__=1 , snake_case__="gelu_new" , snake_case__=0 , snake_case__=0 , snake_case__=512 , snake_case__=2 , snake_case__=0.02 , snake_case__=1e-12 , snake_case__=0.1 , snake_case__="absolute" , snake_case__=0 , snake_case__=2 , snake_case__=3 , **snake_case__ , ): '''simple docstring''' super().__init__(pad_token_id=_snake_case , bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case ) UpperCamelCase_ = vocab_size UpperCamelCase_ = embedding_size UpperCamelCase_ = hidden_size UpperCamelCase_ = num_hidden_layers UpperCamelCase_ = num_hidden_groups UpperCamelCase_ = num_attention_heads UpperCamelCase_ = inner_group_num UpperCamelCase_ = hidden_act UpperCamelCase_ = intermediate_size UpperCamelCase_ = hidden_dropout_prob UpperCamelCase_ = attention_probs_dropout_prob UpperCamelCase_ = max_position_embeddings UpperCamelCase_ = type_vocab_size UpperCamelCase_ = initializer_range UpperCamelCase_ = layer_norm_eps UpperCamelCase_ = classifier_dropout_prob UpperCamelCase_ = position_embedding_type class _lowercase (lowerCamelCase__ ): '''simple docstring''' @property def _lowerCamelCase ( self ): '''simple docstring''' if self.task == "multiple-choice": UpperCamelCase_ = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCamelCase_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
128
from math import isqrt, loga def _UpperCAmelCase ( snake_case ): """simple docstring""" _lowerCAmelCase = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , snake_case , snake_case ): _lowerCAmelCase = False return [i for i in range(2 , snake_case ) if is_prime[i]] def _UpperCAmelCase ( snake_case = 80_08_00 , snake_case = 80_08_00 ): """simple docstring""" _lowerCAmelCase = degree * loga(snake_case ) _lowerCAmelCase = int(snake_case ) _lowerCAmelCase = calculate_prime_numbers(snake_case ) _lowerCAmelCase = 0 _lowerCAmelCase = 0 _lowerCAmelCase = len(snake_case ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"{solution() = }")
82
0
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer snake_case : Any = logging.get_logger(__name__) snake_case : Tuple = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} snake_case : int = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } snake_case : Any = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } snake_case : Any = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } snake_case : List[Any] = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } snake_case : int = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } snake_case : Union[str, Any] = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } snake_case : Tuple = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } snake_case : Tuple = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } snake_case : int = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class _snake_case ( snake_case ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase__ = DPRContextEncoderTokenizer class _snake_case ( snake_case ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase__ = DPRQuestionEncoderTokenizer snake_case : Union[str, Any] = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) snake_case : str = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) snake_case : Union[str, Any] = R"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(snake_case ) class _snake_case : def __call__( self , _a , _a = None , _a = None , _a = False , _a = False , _a = None , _a = None , _a = None , **_a , ): if titles is None and texts is None: return super().__call__( _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) elif titles is None or texts is None: __magic_name__ : List[Any] = titles if texts is None else texts return super().__call__( _a , _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) __magic_name__ : int = titles if not isinstance(_a , _a ) else [titles] __magic_name__ : Union[str, Any] = texts if not isinstance(_a , _a ) else [texts] __magic_name__ : Dict = len(_a ) __magic_name__ : str = questions if not isinstance(_a , _a ) else [questions] * n_passages assert len(_a ) == len( _a ), f'''There should be as many titles than texts but got {len(_a )} titles and {len(_a )} texts.''' __magic_name__ : List[Any] = super().__call__(_a , _a , padding=_a , truncation=_a )["input_ids"] __magic_name__ : List[str] = super().__call__(_a , add_special_tokens=_a , padding=_a , truncation=_a )["input_ids"] __magic_name__ : Tuple = { "input_ids": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_a , _a ) ] } if return_attention_mask is not False: __magic_name__ : Dict = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) __magic_name__ : Optional[Any] = attention_mask return self.pad(_a , padding=_a , max_length=_a , return_tensors=_a ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a = 16 , _a = 64 , _a = 4 , ): __magic_name__ : int = reader_input["input_ids"] __magic_name__ , __magic_name__ , __magic_name__ : Dict = reader_output[:3] __magic_name__ : Dict = len(_a ) __magic_name__ : List[str] = sorted(range(_a ) , reverse=_a , key=relevance_logits.__getitem__ ) __magic_name__ : List[DPRReaderOutput] = [] for doc_id in sorted_docs: __magic_name__ : Optional[int] = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence __magic_name__ : str = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: __magic_name__ : Tuple = sequence_ids.index(self.pad_token_id ) else: __magic_name__ : List[Any] = len(_a ) __magic_name__ : Optional[int] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_a , top_spans=_a , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_a , start_index=_a , end_index=_a , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_a ) >= num_spans: break return nbest_spans_predictions[:num_spans] def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a , ): __magic_name__ : int = [] for start_index, start_score in enumerate(_a ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) __magic_name__ : str = sorted(_a , key=lambda _a : x[1] , reverse=_a ) __magic_name__ : str = [] for (start_index, end_index), score in scores: assert start_index <= end_index, f'''Wrong span indices: [{start_index}:{end_index}]''' __magic_name__ : Tuple = end_index - start_index + 1 assert length <= max_answer_length, f'''Span is too long: {length} > {max_answer_length}''' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_a ) == top_spans: break return chosen_span_intervals @add_end_docstrings(snake_case ) class _snake_case ( snake_case , snake_case ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = READER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ = READER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase__ = ['input_ids', 'attention_mask'] UpperCamelCase__ = DPRReaderTokenizer
41
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # 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. # this script dumps information about the environment import os import sys import transformers snake_case : Any = "3" print("Python version:", sys.version) print("transformers version:", transformers.__version__) try: import torch print("Torch version:", torch.__version__) print("Cuda available:", torch.cuda.is_available()) print("Cuda version:", torch.version.cuda) print("CuDNN version:", torch.backends.cudnn.version()) print("Number of GPUs available:", torch.cuda.device_count()) print("NCCL version:", torch.cuda.nccl.version()) except ImportError: print("Torch version:", None) try: import deepspeed print("DeepSpeed version:", deepspeed.__version__) except ImportError: print("DeepSpeed version:", None) try: import tensorflow as tf print("TensorFlow version:", tf.__version__) print("TF GPUs available:", bool(tf.config.list_physical_devices("GPU"))) print("Number of TF GPUs available:", len(tf.config.list_physical_devices("GPU"))) except ImportError: print("TensorFlow version:", None)
41
1
"""simple docstring""" import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.models.auto.modeling_flax_auto import FlaxAutoModel from transformers.models.bert.modeling_flax_bert import FlaxBertModel from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel @require_flax class lowercase ( unittest.TestCase ): @slow def _snake_case ( self ) -> List[str]: for model_name in ["bert-base-cased", "bert-large-uncased"]: with self.subTest(lowercase ): lowerCAmelCase = AutoConfig.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) self.assertIsInstance(lowercase , lowercase ) lowerCAmelCase = FlaxAutoModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) self.assertIsInstance(lowercase , lowercase ) @slow def _snake_case ( self ) -> List[Any]: for model_name in ["roberta-base", "roberta-large"]: with self.subTest(lowercase ): lowerCAmelCase = AutoConfig.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) self.assertIsInstance(lowercase , lowercase ) lowerCAmelCase = FlaxAutoModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) self.assertIsInstance(lowercase , lowercase ) @slow def _snake_case ( self ) -> Dict: for model_name in ["bert-base-cased", "bert-large-uncased"]: lowerCAmelCase = AutoTokenizer.from_pretrained(lowercase ) lowerCAmelCase = FlaxBertModel.from_pretrained(lowercase ) lowerCAmelCase = tokenizer("""Do you support jax jitted function?""" , return_tensors=TensorType.JAX ) @jax.jit def eval(**lowercase ): return model(**lowercase ) eval(**lowercase ).block_until_ready() @slow def _snake_case ( self ) -> str: for model_name in ["roberta-base", "roberta-large"]: lowerCAmelCase = AutoTokenizer.from_pretrained(lowercase ) lowerCAmelCase = FlaxRobertaModel.from_pretrained(lowercase ) lowerCAmelCase = tokenizer("""Do you support jax jitted function?""" , return_tensors=TensorType.JAX ) @jax.jit def eval(**lowercase ): return model(**lowercase ) eval(**lowercase ).block_until_ready() def _snake_case ( self ) -> Dict: with self.assertRaisesRegex( lowercase , """bert-base is not a local folder and is not a valid model identifier""" ): lowerCAmelCase = FlaxAutoModel.from_pretrained("""bert-base""" ) def _snake_case ( self ) -> int: with self.assertRaisesRegex( lowercase , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): lowerCAmelCase = FlaxAutoModel.from_pretrained(lowercase , revision="""aaaaaa""" ) def _snake_case ( self ) -> Tuple: with self.assertRaisesRegex( lowercase , """hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack""" , ): lowerCAmelCase = FlaxAutoModel.from_pretrained("""hf-internal-testing/config-no-model""" ) def _snake_case ( self ) -> Dict: with self.assertRaisesRegex(lowercase , """Use `from_pt=True` to load this model""" ): lowerCAmelCase = FlaxAutoModel.from_pretrained("""hf-internal-testing/tiny-bert-pt-only""" )
46
"""simple docstring""" 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 lowercase ( _UpperCAmelCase ): def __init__( self , lowercase , lowercase=13 , lowercase=7 , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=False , lowercase=False , lowercase=False , lowercase=2 , lowercase=99 , lowercase=0 , lowercase=32 , lowercase=5 , lowercase=4 , lowercase=0.1 , lowercase=0.1 , lowercase=512 , lowercase=12 , lowercase=2 , lowercase=0.02 , lowercase=3 , lowercase=4 , lowercase="last" , lowercase=None , lowercase=None , ) -> int: lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = seq_length lowerCAmelCase = is_training lowerCAmelCase = use_input_lengths lowerCAmelCase = use_token_type_ids lowerCAmelCase = use_labels lowerCAmelCase = gelu_activation lowerCAmelCase = sinusoidal_embeddings lowerCAmelCase = causal lowerCAmelCase = asm lowerCAmelCase = n_langs lowerCAmelCase = vocab_size lowerCAmelCase = n_special lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = max_position_embeddings lowerCAmelCase = type_vocab_size lowerCAmelCase = type_sequence_label_size lowerCAmelCase = initializer_range lowerCAmelCase = num_labels lowerCAmelCase = num_choices lowerCAmelCase = summary_type lowerCAmelCase = use_proj lowerCAmelCase = scope def _snake_case ( self ) -> int: lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase = None if self.use_input_lengths: lowerCAmelCase = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length lowerCAmelCase = None if self.use_token_type_ids: lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) lowerCAmelCase = None lowerCAmelCase = None lowerCAmelCase = None if self.use_labels: lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase = ids_tensor([self.batch_size] , 2 ).float() lowerCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _snake_case ( self ) -> List[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 _snake_case ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> Any: lowerCAmelCase = FlaubertModel(config=lowercase ) model.to(lowercase ) model.eval() lowerCAmelCase = model(lowercase , lengths=lowercase , langs=lowercase ) lowerCAmelCase = model(lowercase , langs=lowercase ) lowerCAmelCase = model(lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> Tuple: lowerCAmelCase = FlaubertWithLMHeadModel(lowercase ) model.to(lowercase ) model.eval() lowerCAmelCase = model(lowercase , token_type_ids=lowercase , labels=lowercase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> str: lowerCAmelCase = FlaubertForQuestionAnsweringSimple(lowercase ) model.to(lowercase ) model.eval() lowerCAmelCase = model(lowercase ) lowerCAmelCase = model(lowercase , start_positions=lowercase , end_positions=lowercase ) 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 _snake_case ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> Dict: lowerCAmelCase = FlaubertForQuestionAnswering(lowercase ) model.to(lowercase ) model.eval() lowerCAmelCase = model(lowercase ) lowerCAmelCase = model( lowercase , start_positions=lowercase , end_positions=lowercase , cls_index=lowercase , is_impossible=lowercase , p_mask=lowercase , ) lowerCAmelCase = model( lowercase , start_positions=lowercase , end_positions=lowercase , cls_index=lowercase , is_impossible=lowercase , ) ((lowerCAmelCase) , ) = result_with_labels.to_tuple() lowerCAmelCase = model(lowercase , start_positions=lowercase , end_positions=lowercase ) ((lowerCAmelCase) , ) = 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 _snake_case ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> int: lowerCAmelCase = FlaubertForSequenceClassification(lowercase ) model.to(lowercase ) model.eval() lowerCAmelCase = model(lowercase ) lowerCAmelCase = model(lowercase , labels=lowercase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _snake_case ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> int: lowerCAmelCase = self.num_labels lowerCAmelCase = FlaubertForTokenClassification(lowercase ) model.to(lowercase ) model.eval() lowerCAmelCase = model(lowercase , attention_mask=lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> Tuple: lowerCAmelCase = self.num_choices lowerCAmelCase = FlaubertForMultipleChoice(config=lowercase ) model.to(lowercase ) model.eval() lowerCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase = model( lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self ) -> List[Any]: lowerCAmelCase = self.prepare_config_and_inputs() ( ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ) = config_and_inputs lowerCAmelCase = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class lowercase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE = ( { 'feature-extraction': FlaubertModel, 'fill-mask': FlaubertWithLMHeadModel, 'question-answering': FlaubertForQuestionAnsweringSimple, 'text-classification': FlaubertForSequenceClassification, 'token-classification': FlaubertForTokenClassification, 'zero-shot': FlaubertForSequenceClassification, } if is_torch_available() else {} ) def _snake_case ( self , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[int]: 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 _snake_case ( self , lowercase , lowercase , lowercase=False ) -> Optional[Any]: lowerCAmelCase = super()._prepare_for_class(lowercase , lowercase , return_labels=lowercase ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": lowerCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowercase ) lowerCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowercase ) return inputs_dict def _snake_case ( self ) -> List[str]: lowerCAmelCase = FlaubertModelTester(self ) lowerCAmelCase = ConfigTester(self , config_class=lowercase , emb_dim=37 ) def _snake_case ( self ) -> Tuple: self.config_tester.run_common_tests() def _snake_case ( self ) -> Tuple: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*lowercase ) def _snake_case ( self ) -> Tuple: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*lowercase ) def _snake_case ( self ) -> Optional[int]: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*lowercase ) def _snake_case ( self ) -> Union[str, Any]: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*lowercase ) def _snake_case ( self ) -> Any: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*lowercase ) def _snake_case ( self ) -> Any: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*lowercase ) def _snake_case ( self ) -> Any: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*lowercase ) @slow def _snake_case ( self ) -> Tuple: for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase = FlaubertModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @slow @require_torch_gpu def _snake_case ( self ) -> List[Any]: lowerCAmelCase , lowerCAmelCase = 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 lowerCAmelCase = True lowerCAmelCase = model_class(config=lowercase ) lowerCAmelCase = self._prepare_for_class(lowercase , lowercase ) lowerCAmelCase = torch.jit.trace( lowercase , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(lowercase , os.path.join(lowercase , """traced_model.pt""" ) ) lowerCAmelCase = torch.jit.load(os.path.join(lowercase , """traced_model.pt""" ) , map_location=lowercase ) loaded(inputs_dict["""input_ids"""].to(lowercase ) , inputs_dict["""attention_mask"""].to(lowercase ) ) @require_torch class lowercase ( unittest.TestCase ): @slow def _snake_case ( self ) -> Optional[int]: lowerCAmelCase = FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased""" ) lowerCAmelCase = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) with torch.no_grad(): lowerCAmelCase = model(lowercase )[0] lowerCAmelCase = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , lowercase ) lowerCAmelCase = torch.tensor( [[[-2.6_251, -1.4_298, -0.0_227], [-2.8_510, -1.6_387, 0.2_258], [-2.8_114, -1.1_832, -0.3_066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowercase , atol=1e-4 ) )
46
1
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { "asapp/sew-tiny-100k": "https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json", # See all SEW models at https://huggingface.co/models?filter=sew } class lowerCamelCase ( __lowerCAmelCase ): snake_case_ = '''sew''' def __init__( self, lowercase_=32, lowercase_=768, lowercase_=12, lowercase_=12, lowercase_=3072, lowercase_=2, lowercase_="gelu", lowercase_=0.1, lowercase_=0.1, lowercase_=0.1, lowercase_=0.0, lowercase_=0.1, lowercase_=0.1, lowercase_=0.02, lowercase_=1E-5, lowercase_="group", lowercase_="gelu", lowercase_=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512), lowercase_=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1), lowercase_=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1), lowercase_=False, lowercase_=128, lowercase_=16, lowercase_=True, lowercase_=0.05, lowercase_=10, lowercase_=2, lowercase_=0.0, lowercase_=10, lowercase_=0, lowercase_="mean", lowercase_=False, lowercase_=False, lowercase_=256, lowercase_=0, lowercase_=1, lowercase_=2, **lowercase_, ) -> List[Any]: super().__init__(**lowercase_, pad_token_id=lowercase_, bos_token_id=lowercase_, eos_token_id=lowercase_ ) snake_case = hidden_size snake_case = feat_extract_norm snake_case = feat_extract_activation snake_case = list(lowercase_ ) snake_case = list(lowercase_ ) snake_case = list(lowercase_ ) snake_case = conv_bias snake_case = num_conv_pos_embeddings snake_case = num_conv_pos_embedding_groups snake_case = len(self.conv_dim ) snake_case = num_hidden_layers snake_case = intermediate_size snake_case = squeeze_factor snake_case = hidden_act snake_case = num_attention_heads snake_case = hidden_dropout snake_case = attention_dropout snake_case = activation_dropout snake_case = feat_proj_dropout snake_case = final_dropout snake_case = layerdrop snake_case = layer_norm_eps snake_case = initializer_range snake_case = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect.' 'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,' F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 snake_case = apply_spec_augment snake_case = mask_time_prob snake_case = mask_time_length snake_case = mask_time_min_masks snake_case = mask_feature_prob snake_case = mask_feature_length snake_case = mask_feature_min_masks # ctc loss snake_case = ctc_loss_reduction snake_case = ctc_zero_infinity # sequence classification snake_case = use_weighted_layer_sum snake_case = classifier_proj_size @property def _lowerCamelCase ( self ) -> Union[str, Any]: return functools.reduce(operator.mul, self.conv_stride, 1 )
332
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/config.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/config.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/config.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/config.json", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json", "roberta-large-openai-detector": "https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json", } class lowerCamelCase ( __lowerCAmelCase ): snake_case_ = '''roberta''' def __init__( self, lowercase_=50265, lowercase_=768, lowercase_=12, lowercase_=12, lowercase_=3072, lowercase_="gelu", lowercase_=0.1, lowercase_=0.1, lowercase_=512, lowercase_=2, lowercase_=0.02, lowercase_=1E-12, lowercase_=1, lowercase_=0, lowercase_=2, lowercase_="absolute", lowercase_=True, lowercase_=None, **lowercase_, ) -> Tuple: super().__init__(pad_token_id=lowercase_, bos_token_id=lowercase_, eos_token_id=lowercase_, **lowercase_ ) snake_case = vocab_size snake_case = hidden_size snake_case = num_hidden_layers snake_case = num_attention_heads snake_case = hidden_act snake_case = intermediate_size snake_case = hidden_dropout_prob snake_case = attention_probs_dropout_prob snake_case = max_position_embeddings snake_case = type_vocab_size snake_case = initializer_range snake_case = layer_norm_eps snake_case = position_embedding_type snake_case = use_cache snake_case = classifier_dropout class lowerCamelCase ( __lowerCAmelCase ): @property def _lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": snake_case = {0: 'batch', 1: 'choice', 2: 'sequence'} else: snake_case = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
332
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json", } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : Optional[int] = 'focalnet' def __init__( self , _a=224 , _a=4 , _a=3 , _a=96 , _a=False , _a=[192, 384, 768, 768] , _a=[2, 2, 6, 2] , _a=[2, 2, 2, 2] , _a=[3, 3, 3, 3] , _a="gelu" , _a=4.0 , _a=0.0 , _a=0.1 , _a=False , _a=1E-4 , _a=False , _a=False , _a=False , _a=0.02 , _a=1E-5 , _a=32 , _a=None , _a=None , **_a , ): super().__init__(**_a ) __a = image_size __a = patch_size __a = num_channels __a = embed_dim __a = use_conv_embed __a = hidden_sizes __a = depths __a = focal_levels __a = focal_windows __a = hidden_act __a = mlp_ratio __a = hidden_dropout_prob __a = drop_path_rate __a = use_layerscale __a = layerscale_value __a = use_post_layernorm __a = use_post_layernorm_in_modulation __a = normalize_modulator __a = initializer_range __a = layer_norm_eps __a = encoder_stride __a = ['''stem'''] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] __a , __a = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
45
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class __A : '''simple docstring''' def __init__( self , __lowerCAmelCase , __lowerCAmelCase=9_9 , __lowerCAmelCase=1_3 , __lowerCAmelCase=7 , __lowerCAmelCase=9 , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=False , __lowerCAmelCase=3_2 , __lowerCAmelCase=5 , __lowerCAmelCase=4 , __lowerCAmelCase=3_7 , __lowerCAmelCase=8 , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.002 , __lowerCAmelCase=1 , __lowerCAmelCase=0 , __lowerCAmelCase=0 , __lowerCAmelCase=None , __lowerCAmelCase=None , ): '''simple docstring''' lowerCamelCase__ = parent lowerCamelCase__ = batch_size lowerCamelCase__ = encoder_seq_length lowerCamelCase__ = decoder_seq_length # For common tests lowerCamelCase__ = self.decoder_seq_length lowerCamelCase__ = is_training lowerCamelCase__ = use_attention_mask lowerCamelCase__ = use_labels lowerCamelCase__ = vocab_size lowerCamelCase__ = hidden_size lowerCamelCase__ = num_hidden_layers lowerCamelCase__ = num_attention_heads lowerCamelCase__ = d_ff lowerCamelCase__ = relative_attention_num_buckets lowerCamelCase__ = dropout_rate lowerCamelCase__ = initializer_factor lowerCamelCase__ = eos_token_id lowerCamelCase__ = pad_token_id lowerCamelCase__ = decoder_start_token_id lowerCamelCase__ = None lowerCamelCase__ = decoder_layers def __lowerCamelCase ( self ): '''simple docstring''' return TaConfig.from_pretrained('''google/umt5-base''' ) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , ): '''simple docstring''' if attention_mask is None: lowerCamelCase__ = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: lowerCamelCase__ = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: lowerCamelCase__ = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=__lowerCAmelCase ) if decoder_head_mask is None: lowerCamelCase__ = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=__lowerCAmelCase ) if cross_attn_head_mask is None: lowerCamelCase__ = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=__lowerCAmelCase ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) lowerCamelCase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input lowerCamelCase__ = input_ids.clamp(self.pad_token_id + 1 ) lowerCamelCase__ = decoder_input_ids.clamp(self.pad_token_id + 1 ) lowerCamelCase__ = self.get_config() lowerCamelCase__ = config.num_attention_heads lowerCamelCase__ = self.prepare_inputs_dict(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return config, input_dict def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ , lowerCamelCase__ = self.prepare_config_and_inputs() return config, inputs_dict def __lowerCamelCase ( self ): '''simple docstring''' return TaConfig( vocab_size=1_6_6 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __lowerCamelCase ( self ): '''simple docstring''' return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ): '''simple docstring''' lowerCamelCase__ = UMTaModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() lowerCamelCase__ = model( input_ids=__lowerCAmelCase , decoder_input_ids=__lowerCAmelCase , attention_mask=__lowerCAmelCase , decoder_attention_mask=__lowerCAmelCase , ) lowerCamelCase__ = model(input_ids=__lowerCAmelCase , decoder_input_ids=__lowerCAmelCase ) lowerCamelCase__ = result.last_hidden_state lowerCamelCase__ = result.past_key_values lowerCamelCase__ = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(__lowerCAmelCase ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ): '''simple docstring''' lowerCamelCase__ = UMTaModel(config=__lowerCAmelCase ).get_decoder().to(__lowerCAmelCase ).eval() # first forward pass lowerCamelCase__ = model(__lowerCAmelCase , use_cache=__lowerCAmelCase ) lowerCamelCase__ = model(__lowerCAmelCase ) lowerCamelCase__ = model(__lowerCAmelCase , use_cache=__lowerCAmelCase ) self.parent.assertTrue(len(__lowerCAmelCase ) == len(__lowerCAmelCase ) ) self.parent.assertTrue(len(__lowerCAmelCase ) == len(__lowerCAmelCase ) + 1 ) lowerCamelCase__ , lowerCamelCase__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowerCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and lowerCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) lowerCamelCase__ = model(__lowerCAmelCase )['''last_hidden_state'''] lowerCamelCase__ = model(__lowerCAmelCase , past_key_values=__lowerCAmelCase )['''last_hidden_state'''] # select random slice lowerCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowerCamelCase__ = output_from_no_past[:, -1, random_slice_idx].detach() lowerCamelCase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase , ): '''simple docstring''' lowerCamelCase__ = UMTaModel(config=__lowerCAmelCase ).to(__lowerCAmelCase ).half().eval() lowerCamelCase__ = model(**__lowerCAmelCase )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(__lowerCAmelCase ).any().item() ) @require_torch class __A ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) lowerCAmelCase_ = (UMTaForConditionalGeneration,) if is_torch_available() else () lowerCAmelCase_ = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) lowerCAmelCase_ = True lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = True lowerCAmelCase_ = True # The small UMT5 model needs higher percentages for CPU/MP tests lowerCAmelCase_ = [0.8, 0.9] def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.model_tester.prepare_config_and_inputs() lowerCamelCase__ = UMTaModel(config_and_inputs[0] ).to(__lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( __lowerCAmelCase , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F'{tmpdirname}/t5_test.onnx' , export_params=__lowerCAmelCase , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*__lowerCAmelCase ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] lowerCamelCase__ = self.model_tester.prepare_config_and_inputs() lowerCamelCase__ = config_and_inputs[0] lowerCamelCase__ = UMTaForConditionalGeneration(__lowerCAmelCase ).eval() model.to(__lowerCAmelCase ) lowerCamelCase__ = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=__lowerCAmelCase ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=__lowerCAmelCase ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=__lowerCAmelCase ), } for attn_name, (name, mask) in zip(__lowerCAmelCase , head_masking.items() ): lowerCamelCase__ = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": lowerCamelCase__ = torch.ones( config.num_decoder_layers , config.num_heads , device=__lowerCAmelCase ) lowerCamelCase__ = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=__lowerCAmelCase , return_dict_in_generate=__lowerCAmelCase , **__lowerCAmelCase , ) # We check the state of decoder_attentions and cross_attentions just from the last step lowerCamelCase__ = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def __lowerCamelCase ( self ): '''simple docstring''' pass @require_torch @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): '''simple docstring''' @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=__lowerCAmelCase ).to(__lowerCAmelCase ) lowerCamelCase__ = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=__lowerCAmelCase , legacy=__lowerCAmelCase ) lowerCamelCase__ = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] lowerCamelCase__ = tokenizer(__lowerCAmelCase , return_tensors='''pt''' , padding=__lowerCAmelCase ).input_ids # fmt: off lowerCamelCase__ = torch.tensor( [ [ 3_8_5_3_0, 2_1_0_7_0_3, 2_5_6_2_9_9, 1_4_1_0, 2_5_6_2_9_8, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 8_2_6, 3_2_1, 6_7_1, 2_5_9_2_2, 2_5_6_2_9_9, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_4_6_0, 3_3_9, 3_1_2, 1_9_0_1_4, 1_0_6_2_0, 7_5_8, 2_5_6_2_9_9, 2_3_5_5,2_7_4, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 5_1_7, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 3_0_1, 2_5_6_2_9_8, 2_7_5, 1_1_9_9_8_3,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 3_2_0, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 2_2_3_4, 2_8_9, 2_2_7_5, 3_3_3,6_1_3_9_1, 2_8_9, 2_5_6_2_9_8, 5_4_3, 2_5_6_2_9_7, 1_6_8_7_1_4, 3_2_9, 2_5_6_2_9_6,2_7_4, 1], ] ) # fmt: on torch.testing.assert_allclose(__lowerCAmelCase , __lowerCAmelCase ) lowerCamelCase__ = model.generate(input_ids.to(__lowerCAmelCase ) ) lowerCamelCase__ = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] lowerCamelCase__ = tokenizer.batch_decode(__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase )
209
0
'''simple docstring''' from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function a : Any = 1.054571817E-34 # unit of ℏ : J * s a : Any = 3E8 # unit of c : m * s^-1 def __lowerCamelCase ( _lowercase , _lowercase , _lowercase ) -> dict[str, float]: if (force, area, distance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if force < 0: raise ValueError("""Magnitude of force can not be negative""" ) if distance < 0: raise ValueError("""Distance can not be negative""" ) if area < 0: raise ValueError("""Area can not be negative""" ) if force == 0: UpperCAmelCase : Union[str, Any] = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 2_4_0 * (distance) ** 4 ) return {"force": force} elif area == 0: UpperCAmelCase : Tuple = (2_4_0 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: UpperCAmelCase : Tuple = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (2_4_0 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError("""One and only one argument must be 0""" ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
338
'''simple docstring''' a : Dict = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def __lowerCamelCase ( ) -> None: UpperCAmelCase : Optional[int] = input("""Enter message: """ ) UpperCAmelCase : Dict = input("""Enter key [alphanumeric]: """ ) UpperCAmelCase : Optional[Any] = input("""Encrypt/Decrypt [e/d]: """ ) if mode.lower().startswith("""e""" ): UpperCAmelCase : List[str] = """encrypt""" UpperCAmelCase : List[str] = encrypt_message(_lowercase , _lowercase ) elif mode.lower().startswith("""d""" ): UpperCAmelCase : Tuple = """decrypt""" UpperCAmelCase : str = decrypt_message(_lowercase , _lowercase ) print(F'''\n{mode.title()}ed message:''' ) print(_lowercase ) def __lowerCamelCase ( _lowercase , _lowercase ) -> str: return translate_message(_lowercase , _lowercase , """encrypt""" ) def __lowerCamelCase ( _lowercase , _lowercase ) -> str: return translate_message(_lowercase , _lowercase , """decrypt""" ) def __lowerCamelCase ( _lowercase , _lowercase , _lowercase ) -> str: UpperCAmelCase : Optional[int] = [] UpperCAmelCase : Optional[Any] = 0 UpperCAmelCase : Tuple = key.upper() for symbol in message: UpperCAmelCase : Dict = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(_lowercase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(_lowercase ): UpperCAmelCase : Optional[int] = 0 else: translated.append(_lowercase ) return "".join(_lowercase ) if __name__ == "__main__": main()
338
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): """simple docstring""" lowercase_ : Optional[int] = len(__SCREAMING_SNAKE_CASE ) + 1 lowercase_ : Tuple = len(__SCREAMING_SNAKE_CASE ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. lowercase_ : List[Any] = [[0 for i in range(__SCREAMING_SNAKE_CASE )] for j in range(__SCREAMING_SNAKE_CASE )] # since string of zero length match pattern of zero length lowercase_ : Optional[int] = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , __SCREAMING_SNAKE_CASE ): lowercase_ : Dict = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , __SCREAMING_SNAKE_CASE ): lowercase_ : List[Any] = dp[0][j - 2] if pattern[j - 1] == '''*''' else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , __SCREAMING_SNAKE_CASE ): for j in range(1 , __SCREAMING_SNAKE_CASE ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": lowercase_ : str = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: lowercase_ : int = 1 elif pattern[j - 2] in (input_string[i - 1], "."): lowercase_ : Tuple = dp[i - 1][j] else: lowercase_ : List[Any] = 0 else: lowercase_ : Dict = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") _lowercase : Any = "aab" _lowercase : List[Any] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f"""{input_string} matches the given pattern {pattern}""") else: print(f"""{input_string} does not match with the given pattern {pattern}""")
93
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : int = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = {} def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) if nodea not in self.connections: self.add_node(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = probability def _snake_case ( self ): """simple docstring""" return list(self.connections ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = 0 lowercase_ : Tuple = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : List[Any] = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : str = Counter(graph.get_nodes() ) lowercase_ : Any = start for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : int = graph.transition(__SCREAMING_SNAKE_CASE ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
93
1
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def _lowercase ( __snake_case ) -> Dict: if not isinstance(__snake_case ,__snake_case ): raise TypeError("Undefined for non-integers" ) elif precision < 1: raise ValueError("Undefined for non-natural numbers" ) __lowerCAmelCase : Optional[int] = precision __lowerCAmelCase : Tuple = ceil(precision / 14 ) __lowerCAmelCase : Dict = 426_880 * Decimal(10_005 ).sqrt() __lowerCAmelCase : List[str] = 1 __lowerCAmelCase : Tuple = 13_591_409 __lowerCAmelCase : Optional[Any] = Decimal(__snake_case ) for k in range(1 ,__snake_case ): __lowerCAmelCase : Dict = factorial(6 * k ) // (factorial(3 * k ) * factorial(__snake_case ) ** 3) linear_term += 545_140_134 exponential_term *= -262_537_412_640_768_000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": __snake_case : Any = 50 print(F"""The first {n} digits of pi is: {pi(n)}""")
356
"""simple docstring""" import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def _lowercase ( __snake_case ) -> Optional[Any]: __lowerCAmelCase : str = fname.split(os.path.sep )[-1] return re.search(r"^(.*)_\d+\.jpg$" ,__snake_case ).groups()[0] class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Dict=None , _SCREAMING_SNAKE_CASE: Any=None) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : str = file_names __lowerCAmelCase : Optional[int] = image_transform __lowerCAmelCase : List[Any] = label_to_id def __len__( self: Union[str, Any]) -> int: """simple docstring""" return len(self.file_names) def __getitem__( self: List[Any] , _SCREAMING_SNAKE_CASE: Optional[Any]) -> Optional[int]: """simple docstring""" __lowerCAmelCase : int = self.file_names[idx] __lowerCAmelCase : List[str] = PIL.Image.open(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Tuple = raw_image.convert("RGB") if self.image_transform is not None: __lowerCAmelCase : Union[str, Any] = self.image_transform(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Dict = extract_label(_SCREAMING_SNAKE_CASE) if self.label_to_id is not None: __lowerCAmelCase : str = self.label_to_id[label] return {"image": image, "label": label} def _lowercase ( __snake_case ,__snake_case ) -> Optional[int]: # Initialize accelerator if args.with_tracking: __lowerCAmelCase : str = Accelerator( cpu=args.cpu ,mixed_precision=args.mixed_precision ,log_with="all" ,project_dir=args.project_dir ) else: __lowerCAmelCase : Any = Accelerator(cpu=args.cpu ,mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __lowerCAmelCase : int = config["lr"] __lowerCAmelCase : Union[str, Any] = int(config["num_epochs"] ) __lowerCAmelCase : Tuple = int(config["seed"] ) __lowerCAmelCase : Tuple = int(config["batch_size"] ) __lowerCAmelCase : int = config["image_size"] if not isinstance(__snake_case ,(list, tuple) ): __lowerCAmelCase : Tuple = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps ,"isdigit" ): if args.checkpointing_steps == "epoch": __lowerCAmelCase : Optional[Any] = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): __lowerCAmelCase : Dict = int(args.checkpointing_steps ) else: raise ValueError( F"""Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.""" ) else: __lowerCAmelCase : int = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: __lowerCAmelCase : Dict = os.path.split(__snake_case )[-1].split("." )[0] accelerator.init_trackers(__snake_case ,__snake_case ) # Grab all the image filenames __lowerCAmelCase : Union[str, Any] = [os.path.join(args.data_dir ,__snake_case ) for fname in os.listdir(args.data_dir ) if fname.endswith(".jpg" )] # Build the label correspondences __lowerCAmelCase : Union[str, Any] = [extract_label(__snake_case ) for fname in file_names] __lowerCAmelCase : Any = list(set(__snake_case ) ) id_to_label.sort() __lowerCAmelCase : Optional[Any] = {lbl: i for i, lbl in enumerate(__snake_case )} # Set the seed before splitting the data. np.random.seed(__snake_case ) torch.manual_seed(__snake_case ) torch.cuda.manual_seed_all(__snake_case ) # Split our filenames between train and validation __lowerCAmelCase : List[str] = np.random.permutation(len(__snake_case ) ) __lowerCAmelCase : Dict = int(0.8 * len(__snake_case ) ) __lowerCAmelCase : str = random_perm[:cut] __lowerCAmelCase : Optional[int] = random_perm[cut:] # For training we use a simple RandomResizedCrop __lowerCAmelCase : str = Compose([RandomResizedCrop(__snake_case ,scale=(0.5, 1.0) ), ToTensor()] ) __lowerCAmelCase : List[str] = PetsDataset( [file_names[i] for i in train_split] ,image_transform=__snake_case ,label_to_id=__snake_case ) # For evaluation, we use a deterministic Resize __lowerCAmelCase : Union[str, Any] = Compose([Resize(__snake_case ), ToTensor()] ) __lowerCAmelCase : List[str] = PetsDataset([file_names[i] for i in eval_split] ,image_transform=__snake_case ,label_to_id=__snake_case ) # Instantiate dataloaders. __lowerCAmelCase : Union[str, Any] = DataLoader(__snake_case ,shuffle=__snake_case ,batch_size=__snake_case ,num_workers=4 ) __lowerCAmelCase : Any = DataLoader(__snake_case ,shuffle=__snake_case ,batch_size=__snake_case ,num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __lowerCAmelCase : int = create_model("resnet50d" ,pretrained=__snake_case ,num_classes=len(__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). __lowerCAmelCase : List[str] = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): __lowerCAmelCase : Any = False for param in model.get_classifier().parameters(): __lowerCAmelCase : List[Any] = True # We normalize the batches of images to be a bit faster. __lowerCAmelCase : Optional[Any] = torch.tensor(model.default_cfg["mean"] )[None, :, None, None].to(accelerator.device ) __lowerCAmelCase : int = torch.tensor(model.default_cfg["std"] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer __lowerCAmelCase : int = torch.optim.Adam(params=model.parameters() ,lr=lr / 25 ) # Instantiate learning rate scheduler __lowerCAmelCase : List[Any] = OneCycleLR(optimizer=__snake_case ,max_lr=__snake_case ,epochs=__snake_case ,steps_per_epoch=len(__snake_case ) ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Tuple = accelerator.prepare( __snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) # We need to keep track of how many total steps we have iterated over __lowerCAmelCase : Dict = 0 # We also need to keep track of the starting epoch so files are named properly __lowerCAmelCase : List[str] = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(F"""Resumed from checkpoint: {args.resume_from_checkpoint}""" ) accelerator.load_state(args.resume_from_checkpoint ) __lowerCAmelCase : Optional[Any] = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint __lowerCAmelCase : Optional[int] = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) __lowerCAmelCase : Optional[Any] = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` __lowerCAmelCase : str = os.path.splitext(__snake_case )[0] if "epoch" in training_difference: __lowerCAmelCase : Dict = int(training_difference.replace("epoch_" ,"" ) ) + 1 __lowerCAmelCase : Optional[Any] = None else: __lowerCAmelCase : Any = int(training_difference.replace("step_" ,"" ) ) __lowerCAmelCase : Optional[int] = resume_step // len(__snake_case ) resume_step -= starting_epoch * len(__snake_case ) # Now we train the model for epoch in range(__snake_case ,__snake_case ): model.train() if args.with_tracking: __lowerCAmelCase : Any = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step __lowerCAmelCase : Optional[int] = accelerator.skip_first_batches(__snake_case ,__snake_case ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader __lowerCAmelCase : Optional[int] = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. __lowerCAmelCase : List[Any] = {k: v.to(accelerator.device ) for k, v in batch.items()} __lowerCAmelCase : Union[str, Any] = (batch["image"] - mean) / std __lowerCAmelCase : Optional[int] = model(__snake_case ) __lowerCAmelCase : List[str] = torch.nn.functional.cross_entropy(__snake_case ,batch["label"] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(__snake_case ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(__snake_case ,__snake_case ): __lowerCAmelCase : List[Any] = F"""step_{overall_step}""" if overall_step % checkpointing_steps == 0: if args.output_dir is not None: __lowerCAmelCase : Tuple = os.path.join(args.output_dir ,__snake_case ) accelerator.save_state(__snake_case ) model.eval() __lowerCAmelCase : int = 0 __lowerCAmelCase : Optional[int] = 0 for step, batch in enumerate(__snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True`. __lowerCAmelCase : Tuple = {k: v.to(accelerator.device ) for k, v in batch.items()} __lowerCAmelCase : Optional[Any] = (batch["image"] - mean) / std with torch.no_grad(): __lowerCAmelCase : Optional[Any] = model(__snake_case ) __lowerCAmelCase : List[str] = outputs.argmax(dim=-1 ) __lowerCAmelCase , __lowerCAmelCase : Optional[int] = accelerator.gather_for_metrics((predictions, batch["label"]) ) __lowerCAmelCase : str = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() __lowerCAmelCase : Optional[Any] = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}: {100 * eval_metric:.2f}""" ) if args.with_tracking: accelerator.log( { "accuracy": 100 * eval_metric, "train_loss": total_loss.item() / len(__snake_case ), "epoch": epoch, } ,step=__snake_case ,) if checkpointing_steps == "epoch": __lowerCAmelCase : Tuple = F"""epoch_{epoch}""" if args.output_dir is not None: __lowerCAmelCase : Optional[Any] = os.path.join(args.output_dir ,__snake_case ) accelerator.save_state(__snake_case ) if args.with_tracking: accelerator.end_training() def _lowercase ( ) -> Tuple: __lowerCAmelCase : Union[str, Any] = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument("--data_dir" ,required=__snake_case ,help="The data folder on disk." ) parser.add_argument("--fp16" ,action="store_true" ,help="If passed, will use FP16 training." ) 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." ) parser.add_argument( "--checkpointing_steps" ,type=__snake_case ,default=__snake_case ,help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch." ,) parser.add_argument( "--output_dir" ,type=__snake_case ,default="." ,help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory." ,) parser.add_argument( "--resume_from_checkpoint" ,type=__snake_case ,default=__snake_case ,help="If the training should continue from a checkpoint folder." ,) parser.add_argument( "--with_tracking" ,action="store_true" ,help="Whether to load in all available experiment trackers from the environment and use them for logging." ,) parser.add_argument( "--project_dir" ,type=__snake_case ,default="logs" ,help="Location on where to store experiment tracking logs` and relevent project information" ,) __lowerCAmelCase : List[Any] = parser.parse_args() __lowerCAmelCase : List[Any] = {"lr": 3e-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 224} training_function(__snake_case ,__snake_case ) if __name__ == "__main__": main()
58
0
"""simple docstring""" import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class lowercase : @staticmethod def _snake_case ( *lowercase , **lowercase ) -> Union[str, Any]: pass def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Image ): '''simple docstring''' lowerCAmelCase = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Image ): '''simple docstring''' lowerCAmelCase = np.array(SCREAMING_SNAKE_CASE ) lowerCAmelCase = npimg.shape return {"hash": hashimage(SCREAMING_SNAKE_CASE ), "shape": shape} @is_pipeline_test @require_vision @require_torch class lowercase ( unittest.TestCase ): _SCREAMING_SNAKE_CASE = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) _SCREAMING_SNAKE_CASE = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def _snake_case ( self , lowercase , lowercase , lowercase ) -> Optional[Any]: lowerCAmelCase = MaskGenerationPipeline(model=lowercase , image_processor=lowercase ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def _snake_case ( self , lowercase , lowercase ) -> List[Any]: pass @require_tf @unittest.skip("""Image segmentation not implemented in TF""" ) def _snake_case ( self ) -> Dict: pass @slow @require_torch def _snake_case ( self ) -> str: lowerCAmelCase = pipeline("""mask-generation""" , model="""facebook/sam-vit-huge""" ) lowerCAmelCase = image_segmenter("""http://images.cocodataset.org/val2017/000000039769.jpg""" , points_per_batch=256 ) # Shortening by hashing lowerCAmelCase = [] for i, o in enumerate(outputs["""masks"""] ): new_outupt += [{"mask": mask_to_test_readable(lowercase ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(lowercase , decimals=4 ) , [ {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (480, 640)}, """scores""": 1.0_444}, {"""mask""": {"""hash""": """6affa964c6""", """shape""": (480, 640)}, """scores""": 1.021}, {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (480, 640)}, """scores""": 1.0_167}, {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (480, 640)}, """scores""": 1.0_132}, {"""mask""": {"""hash""": """fe8065c197""", """shape""": (480, 640)}, """scores""": 1.0_053}, {"""mask""": {"""hash""": """e2d0b7a0b7""", """shape""": (480, 640)}, """scores""": 0.9_967}, {"""mask""": {"""hash""": """453c7844bd""", """shape""": (480, 640)}, """scores""": 0.993}, {"""mask""": {"""hash""": """3d44f2926d""", """shape""": (480, 640)}, """scores""": 0.9_909}, {"""mask""": {"""hash""": """64033ddc3f""", """shape""": (480, 640)}, """scores""": 0.9_879}, {"""mask""": {"""hash""": """801064ff79""", """shape""": (480, 640)}, """scores""": 0.9_834}, {"""mask""": {"""hash""": """6172f276ef""", """shape""": (480, 640)}, """scores""": 0.9_716}, {"""mask""": {"""hash""": """b49e60e084""", """shape""": (480, 640)}, """scores""": 0.9_612}, {"""mask""": {"""hash""": """a811e775fd""", """shape""": (480, 640)}, """scores""": 0.9_599}, {"""mask""": {"""hash""": """a6a8ebcf4b""", """shape""": (480, 640)}, """scores""": 0.9_552}, {"""mask""": {"""hash""": """9d8257e080""", """shape""": (480, 640)}, """scores""": 0.9_532}, {"""mask""": {"""hash""": """32de6454a8""", """shape""": (480, 640)}, """scores""": 0.9_516}, {"""mask""": {"""hash""": """af3d4af2c8""", """shape""": (480, 640)}, """scores""": 0.9_499}, {"""mask""": {"""hash""": """3c6db475fb""", """shape""": (480, 640)}, """scores""": 0.9_483}, {"""mask""": {"""hash""": """c290813fb9""", """shape""": (480, 640)}, """scores""": 0.9_464}, {"""mask""": {"""hash""": """b6f0b8f606""", """shape""": (480, 640)}, """scores""": 0.943}, {"""mask""": {"""hash""": """92ce16bfdf""", """shape""": (480, 640)}, """scores""": 0.943}, {"""mask""": {"""hash""": """c749b25868""", """shape""": (480, 640)}, """scores""": 0.9_408}, {"""mask""": {"""hash""": """efb6cab859""", """shape""": (480, 640)}, """scores""": 0.9_335}, {"""mask""": {"""hash""": """1ff2eafb30""", """shape""": (480, 640)}, """scores""": 0.9_326}, {"""mask""": {"""hash""": """788b798e24""", """shape""": (480, 640)}, """scores""": 0.9_262}, {"""mask""": {"""hash""": """abea804f0e""", """shape""": (480, 640)}, """scores""": 0.8_999}, {"""mask""": {"""hash""": """7b9e8ddb73""", """shape""": (480, 640)}, """scores""": 0.8_986}, {"""mask""": {"""hash""": """cd24047c8a""", """shape""": (480, 640)}, """scores""": 0.8_984}, {"""mask""": {"""hash""": """6943e6bcbd""", """shape""": (480, 640)}, """scores""": 0.8_873}, {"""mask""": {"""hash""": """b5f47c9191""", """shape""": (480, 640)}, """scores""": 0.8_871} ] , ) # fmt: on @require_torch @slow def _snake_case ( self ) -> Union[str, Any]: lowerCAmelCase = """facebook/sam-vit-huge""" lowerCAmelCase = pipeline("""mask-generation""" , model=lowercase ) lowerCAmelCase = image_segmenter( """http://images.cocodataset.org/val2017/000000039769.jpg""" , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing lowerCAmelCase = [] for i, o in enumerate(outputs["""masks"""] ): new_outupt += [{"mask": mask_to_test_readable(lowercase ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(lowercase , decimals=4 ) , [ {"""mask""": {"""hash""": """115ad19f5f""", """shape""": (480, 640)}, """scores""": 1.0_444}, {"""mask""": {"""hash""": """6affa964c6""", """shape""": (480, 640)}, """scores""": 1.0_210}, {"""mask""": {"""hash""": """dfe28a0388""", """shape""": (480, 640)}, """scores""": 1.0_167}, {"""mask""": {"""hash""": """c0a5f4a318""", """shape""": (480, 640)}, """scores""": 1.0_132}, {"""mask""": {"""hash""": """fe8065c197""", """shape""": (480, 640)}, """scores""": 1.0_053}, ] , )
46
'''simple docstring''' import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings __a = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__ ) class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = field(default=_a , metadata={"help": "Whether to use SortishSampler or not."} ) lowercase = field( default=_a , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase = field( default=_a , metadata={ "help": ( "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `max_length` value of the model configuration." ) } , ) lowercase = field( default=_a , metadata={ "help": ( "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `num_beams` value of the model configuration." ) } , ) lowercase = field( default=_a , metadata={ "help": "Model id, file path or url pointing to a GenerationConfig json file, to use during prediction." } , ) def lowerCamelCase ( self : List[str] ): snake_case__ : int = super().to_dict() for k, v in d.items(): if isinstance(snake_case_ , snake_case_ ): snake_case__ : Optional[int] = v.to_dict() return d
35
0
import argparse import torch from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel from transformers.utils import logging logging.set_verbosity_info() def __UpperCamelCase (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: # Initialise PyTorch model lowercase__ = FunnelConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(F"""Building PyTorch model from configuration: {config}""" ) lowercase__ = FunnelBaseModel(_SCREAMING_SNAKE_CASE ) if base_model else FunnelModel(_SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tf_weights_in_funnel(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.""", ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--base_model""", action="""store_true""", help="""Whether you want just the base model (no decoder) or not.""" ) lowercase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model )
351
import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> Union[str, Any]: lowercase__ = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', '_float_tensor', 'decoder.output_projection.weight', ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> Dict: lowercase__ , lowercase__ = emb.weight.shape lowercase__ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE ) lowercase__ = emb.weight.data return lin_layer def __UpperCamelCase (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="facebook/mbart-large-en-ro" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False ) -> str: lowercase__ = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )['model'] remove_ignore_keys_(_SCREAMING_SNAKE_CASE ) lowercase__ = state_dict['encoder.embed_tokens.weight'].shape[0] lowercase__ = MBartConfig.from_pretrained(_SCREAMING_SNAKE_CASE , vocab_size=_SCREAMING_SNAKE_CASE ) if mbart_aa and finetuned: lowercase__ = 'relu' lowercase__ = state_dict['decoder.embed_tokens.weight'] lowercase__ = MBartForConditionalGeneration(_SCREAMING_SNAKE_CASE ) model.model.load_state_dict(_SCREAMING_SNAKE_CASE ) if finetuned: lowercase__ = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """fairseq_path""", type=str, help="""bart.large, bart.large.cnn or a path to a model.pt on local filesystem.""" ) parser.add_argument("""pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument( """--hf_config""", default="""facebook/mbart-large-cc25""", type=str, help="""Which huggingface architecture to use: mbart-large""", ) parser.add_argument("""--mbart_50""", action="""store_true""", help="""whether the model is mMART-50 checkpoint""") parser.add_argument("""--finetuned""", action="""store_true""", help="""whether the model is a fine-tuned checkpoint""") lowercase_ = parser.parse_args() lowercase_ = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
269
0
"""simple docstring""" import os from pathlib import Path def __lowerCAmelCase (): from torch.utils.cpp_extension import load __lowerCAmelCase : Dict = Path(_UpperCamelCase ).resolve().parent.parent.parent / 'kernels' / 'deformable_detr' __lowerCAmelCase : int = [ root / filename for filename in [ 'vision.cpp', os.path.join('cpu' , 'ms_deform_attn_cpu.cpp' ), os.path.join('cuda' , 'ms_deform_attn_cuda.cu' ), ] ] load( 'MultiScaleDeformableAttention' , _UpperCamelCase , with_cuda=_UpperCamelCase , extra_include_paths=[str(_UpperCamelCase )] , extra_cflags=['-DWITH_CUDA=1'] , extra_cuda_cflags=[ '-DCUDA_HAS_FP16=1', '-D__CUDA_NO_HALF_OPERATORS__', '-D__CUDA_NO_HALF_CONVERSIONS__', '-D__CUDA_NO_HALF2_OPERATORS__', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
86
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (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 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
0
"""simple docstring""" import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCAmelCase : Optional[int] = logging.get_logger(__name__) _lowerCAmelCase : Dict = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} _lowerCAmelCase : Tuple = { "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } _lowerCAmelCase : str = { "allenai/longformer-base-4096": 40_96, "allenai/longformer-large-4096": 40_96, "allenai/longformer-large-4096-finetuned-triviaqa": 40_96, "allenai/longformer-base-4096-extra.pos.embd.only": 40_96, "allenai/longformer-large-4096-extra.pos.embd.only": 40_96, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def __snake_case ( ) -> List[Any]: '''simple docstring''' _UpperCAmelCase : str = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) _UpperCAmelCase : Any = bs[:] _UpperCAmelCase : Tuple = 0 for b in range(2**8 ): if b not in bs: bs.append(SCREAMING_SNAKE_CASE__ ) cs.append(2**8 + n ) n += 1 _UpperCAmelCase : Union[str, Any] = [chr(SCREAMING_SNAKE_CASE__ ) for n in cs] return dict(zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) def __snake_case ( SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> int: '''simple docstring''' _UpperCAmelCase : int = set() _UpperCAmelCase : int = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _UpperCAmelCase : Optional[int] = char return pairs class UpperCAmelCase_ ( _UpperCamelCase ): __SCREAMING_SNAKE_CASE : List[str] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : List[str] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Union[str, Any] = ['input_ids', 'attention_mask'] def __init__( self : Optional[Any] , A : int , A : Any , A : List[str]="replace" , A : List[Any]="<s>" , A : int="</s>" , A : Union[str, Any]="</s>" , A : Tuple="<s>" , A : str="<unk>" , A : Dict="<pad>" , A : Optional[Any]="<mask>" , A : Tuple=False , **A : Dict , ): _UpperCAmelCase : Tuple = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else bos_token _UpperCAmelCase : int = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else eos_token _UpperCAmelCase : int = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else sep_token _UpperCAmelCase : Dict = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else cls_token _UpperCAmelCase : Optional[int] = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else unk_token _UpperCAmelCase : Dict = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it _UpperCAmelCase : Dict = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else mask_token super().__init__( errors=A , bos_token=A , eos_token=A , unk_token=A , sep_token=A , cls_token=A , pad_token=A , mask_token=A , add_prefix_space=A , **A , ) with open(A , encoding="utf-8" ) as vocab_handle: _UpperCAmelCase : Union[str, Any] = json.load(A ) _UpperCAmelCase : List[str] = {v: k for k, v in self.encoder.items()} _UpperCAmelCase : Dict = errors # how to handle errors in decoding _UpperCAmelCase : List[str] = bytes_to_unicode() _UpperCAmelCase : Dict = {v: k for k, v in self.byte_encoder.items()} with open(A , encoding="utf-8" ) as merges_handle: _UpperCAmelCase : Union[str, Any] = merges_handle.read().split("\n" )[1:-1] _UpperCAmelCase : Union[str, Any] = [tuple(merge.split() ) for merge in bpe_merges] _UpperCAmelCase : List[str] = dict(zip(A , range(len(A ) ) ) ) _UpperCAmelCase : Tuple = {} _UpperCAmelCase : Optional[Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions _UpperCAmelCase : Optional[int] = re.compile(R"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property def snake_case_ ( self : Optional[Any] ): return len(self.encoder ) def snake_case_ ( self : List[str] ): return dict(self.encoder , **self.added_tokens_encoder ) def snake_case_ ( self : Tuple , A : Union[str, Any] ): if token in self.cache: return self.cache[token] _UpperCAmelCase : Optional[int] = tuple(A ) _UpperCAmelCase : Optional[Any] = get_pairs(A ) if not pairs: return token while True: _UpperCAmelCase : Optional[int] = min(A , key=lambda A : self.bpe_ranks.get(A , float("inf" ) ) ) if bigram not in self.bpe_ranks: break _UpperCAmelCase , _UpperCAmelCase : str = bigram _UpperCAmelCase : Dict = [] _UpperCAmelCase : Union[str, Any] = 0 while i < len(A ): try: _UpperCAmelCase : int = word.index(A , A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _UpperCAmelCase : Dict = j if word[i] == first and i < len(A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _UpperCAmelCase : Optional[Any] = tuple(A ) _UpperCAmelCase : Dict = new_word if len(A ) == 1: break else: _UpperCAmelCase : Optional[int] = get_pairs(A ) _UpperCAmelCase : Any = " ".join(A ) _UpperCAmelCase : int = word return word def snake_case_ ( self : Optional[int] , A : List[str] ): _UpperCAmelCase : str = [] for token in re.findall(self.pat , A ): _UpperCAmelCase : Optional[Any] = "".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(A ).split(" " ) ) return bpe_tokens def snake_case_ ( self : Optional[int] , A : Union[str, Any] ): return self.encoder.get(A , self.encoder.get(self.unk_token ) ) def snake_case_ ( self : Union[str, Any] , A : List[str] ): return self.decoder.get(A ) def snake_case_ ( self : Dict , A : int ): _UpperCAmelCase : Tuple = "".join(A ) _UpperCAmelCase : Dict = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def snake_case_ ( self : int , A : str , A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return _UpperCAmelCase : List[Any] = os.path.join( A , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) _UpperCAmelCase : Any = os.path.join( A , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(A , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=A , ensure_ascii=A ) + "\n" ) _UpperCAmelCase : Optional[Any] = 0 with open(A , "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 : Any = token_index writer.write(" ".join(A ) + "\n" ) index += 1 return vocab_file, merge_file def snake_case_ ( 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 : List[Any] = [self.cls_token_id] _UpperCAmelCase : List[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def snake_case_ ( 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=A , token_ids_a=A , already_has_special_tokens=A ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def snake_case_ ( self : str , A : List[int] , A : Optional[List[int]] = None ): _UpperCAmelCase : Optional[Any] = [self.sep_token_id] _UpperCAmelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def snake_case_ ( self : str , A : List[str] , A : List[str]=False , **A : List[str] ): _UpperCAmelCase : Optional[Any] = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(A ) > 0 and not text[0].isspace()): _UpperCAmelCase : List[Any] = " " + text return (text, kwargs)
202
"""simple docstring""" import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCAmelCase : Optional[int] = logging.get_logger(__name__) _lowerCAmelCase : Dict = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} _lowerCAmelCase : Tuple = { "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } _lowerCAmelCase : str = { "allenai/longformer-base-4096": 40_96, "allenai/longformer-large-4096": 40_96, "allenai/longformer-large-4096-finetuned-triviaqa": 40_96, "allenai/longformer-base-4096-extra.pos.embd.only": 40_96, "allenai/longformer-large-4096-extra.pos.embd.only": 40_96, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def __snake_case ( ) -> List[Any]: '''simple docstring''' _UpperCAmelCase : str = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) _UpperCAmelCase : Any = bs[:] _UpperCAmelCase : Tuple = 0 for b in range(2**8 ): if b not in bs: bs.append(SCREAMING_SNAKE_CASE__ ) cs.append(2**8 + n ) n += 1 _UpperCAmelCase : Union[str, Any] = [chr(SCREAMING_SNAKE_CASE__ ) for n in cs] return dict(zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) def __snake_case ( SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> int: '''simple docstring''' _UpperCAmelCase : int = set() _UpperCAmelCase : int = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _UpperCAmelCase : Optional[int] = char return pairs class UpperCAmelCase_ ( _UpperCamelCase ): __SCREAMING_SNAKE_CASE : List[str] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : List[str] = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : Union[str, Any] = ['input_ids', 'attention_mask'] def __init__( self : Optional[Any] , A : int , A : Any , A : List[str]="replace" , A : List[Any]="<s>" , A : int="</s>" , A : Union[str, Any]="</s>" , A : Tuple="<s>" , A : str="<unk>" , A : Dict="<pad>" , A : Optional[Any]="<mask>" , A : Tuple=False , **A : Dict , ): _UpperCAmelCase : Tuple = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else bos_token _UpperCAmelCase : int = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else eos_token _UpperCAmelCase : int = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else sep_token _UpperCAmelCase : Dict = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else cls_token _UpperCAmelCase : Optional[int] = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else unk_token _UpperCAmelCase : Dict = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it _UpperCAmelCase : Dict = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else mask_token super().__init__( errors=A , bos_token=A , eos_token=A , unk_token=A , sep_token=A , cls_token=A , pad_token=A , mask_token=A , add_prefix_space=A , **A , ) with open(A , encoding="utf-8" ) as vocab_handle: _UpperCAmelCase : Union[str, Any] = json.load(A ) _UpperCAmelCase : List[str] = {v: k for k, v in self.encoder.items()} _UpperCAmelCase : Dict = errors # how to handle errors in decoding _UpperCAmelCase : List[str] = bytes_to_unicode() _UpperCAmelCase : Dict = {v: k for k, v in self.byte_encoder.items()} with open(A , encoding="utf-8" ) as merges_handle: _UpperCAmelCase : Union[str, Any] = merges_handle.read().split("\n" )[1:-1] _UpperCAmelCase : Union[str, Any] = [tuple(merge.split() ) for merge in bpe_merges] _UpperCAmelCase : List[str] = dict(zip(A , range(len(A ) ) ) ) _UpperCAmelCase : Tuple = {} _UpperCAmelCase : Optional[Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions _UpperCAmelCase : Optional[int] = re.compile(R"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property def snake_case_ ( self : Optional[Any] ): return len(self.encoder ) def snake_case_ ( self : List[str] ): return dict(self.encoder , **self.added_tokens_encoder ) def snake_case_ ( self : Tuple , A : Union[str, Any] ): if token in self.cache: return self.cache[token] _UpperCAmelCase : Optional[int] = tuple(A ) _UpperCAmelCase : Optional[Any] = get_pairs(A ) if not pairs: return token while True: _UpperCAmelCase : Optional[int] = min(A , key=lambda A : self.bpe_ranks.get(A , float("inf" ) ) ) if bigram not in self.bpe_ranks: break _UpperCAmelCase , _UpperCAmelCase : str = bigram _UpperCAmelCase : Dict = [] _UpperCAmelCase : Union[str, Any] = 0 while i < len(A ): try: _UpperCAmelCase : int = word.index(A , A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _UpperCAmelCase : Dict = j if word[i] == first and i < len(A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _UpperCAmelCase : Optional[Any] = tuple(A ) _UpperCAmelCase : Dict = new_word if len(A ) == 1: break else: _UpperCAmelCase : Optional[int] = get_pairs(A ) _UpperCAmelCase : Any = " ".join(A ) _UpperCAmelCase : int = word return word def snake_case_ ( self : Optional[int] , A : List[str] ): _UpperCAmelCase : str = [] for token in re.findall(self.pat , A ): _UpperCAmelCase : Optional[Any] = "".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(A ).split(" " ) ) return bpe_tokens def snake_case_ ( self : Optional[int] , A : Union[str, Any] ): return self.encoder.get(A , self.encoder.get(self.unk_token ) ) def snake_case_ ( self : Union[str, Any] , A : List[str] ): return self.decoder.get(A ) def snake_case_ ( self : Dict , A : int ): _UpperCAmelCase : Tuple = "".join(A ) _UpperCAmelCase : Dict = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def snake_case_ ( self : int , A : str , A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return _UpperCAmelCase : List[Any] = os.path.join( A , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) _UpperCAmelCase : Any = os.path.join( A , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(A , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=A , ensure_ascii=A ) + "\n" ) _UpperCAmelCase : Optional[Any] = 0 with open(A , "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 : Any = token_index writer.write(" ".join(A ) + "\n" ) index += 1 return vocab_file, merge_file def snake_case_ ( 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 : List[Any] = [self.cls_token_id] _UpperCAmelCase : List[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def snake_case_ ( 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=A , token_ids_a=A , already_has_special_tokens=A ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def snake_case_ ( self : str , A : List[int] , A : Optional[List[int]] = None ): _UpperCAmelCase : Optional[Any] = [self.sep_token_id] _UpperCAmelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def snake_case_ ( self : str , A : List[str] , A : List[str]=False , **A : List[str] ): _UpperCAmelCase : Optional[Any] = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(A ) > 0 and not text[0].isspace()): _UpperCAmelCase : List[Any] = " " + text return (text, kwargs)
202
1
'''simple docstring''' import cva import numpy as np class A__ : def __init__( self : Tuple , _a : float , _a : int ) -> List[Any]: '''simple docstring''' if k in (0.04, 0.06): _SCREAMING_SNAKE_CASE =k _SCREAMING_SNAKE_CASE =window_size else: raise ValueError('invalid k value' ) def __str__( self : Any ) -> str: '''simple docstring''' return str(self.k ) def A ( self : Optional[int] , _a : str ) -> tuple[cva.Mat, list[list[int]]]: '''simple docstring''' _SCREAMING_SNAKE_CASE =cva.imread(_a , 0 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =img.shape _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =img.copy() _SCREAMING_SNAKE_CASE =cva.cvtColor(_a , cva.COLOR_GRAY2RGB ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =np.gradient(_a ) _SCREAMING_SNAKE_CASE =dx**2 _SCREAMING_SNAKE_CASE =dy**2 _SCREAMING_SNAKE_CASE =dx * dy _SCREAMING_SNAKE_CASE =0.04 _SCREAMING_SNAKE_CASE =self.window_size // 2 for y in range(_a , h - offset ): for x in range(_a , w - offset ): _SCREAMING_SNAKE_CASE =ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() _SCREAMING_SNAKE_CASE =iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() _SCREAMING_SNAKE_CASE =ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() _SCREAMING_SNAKE_CASE =(wxx * wyy) - (wxy**2) _SCREAMING_SNAKE_CASE =wxx + wyy _SCREAMING_SNAKE_CASE =det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": lowerCamelCase : str = HarrisCorner(0.0_4, 3) lowerCamelCase , lowerCamelCase : Union[str, Any] = edge_detect.detect("path_to_image") cva.imwrite("detect.png", color_img)
47
'''simple docstring''' import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : Any=False ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =OmegaConf.load(_UpperCamelCase ) if display: print(yaml.dump(OmegaConf.to_container(_UpperCamelCase ) ) ) return config def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[Any]=None , _UpperCamelCase : Union[str, Any]=None ) -> Optional[Any]: """simple docstring""" if conf_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.yaml' _SCREAMING_SNAKE_CASE =load_config(_UpperCamelCase , display=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =VQModel(**config.model.params ) if ckpt_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.pt' _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location=_UpperCamelCase ) if ".ckpt" in ckpt_path: _SCREAMING_SNAKE_CASE =sd['state_dict'] model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) model.to(_UpperCamelCase ) del sd return model def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : int ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =model.encode(_UpperCamelCase ) print(f"VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}" ) _SCREAMING_SNAKE_CASE =model.decode(_UpperCamelCase ) return xrec def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : List[str]=False ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =string.rsplit('.' , 1 ) if reload: _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) importlib.reload(_UpperCamelCase ) return getattr(importlib.import_module(_UpperCamelCase , package=_UpperCamelCase ) , cls ) def _lowerCAmelCase ( _UpperCamelCase : str ) -> List[str]: """simple docstring""" if "target" not in config: raise KeyError('Expected key `target` to instantiate.' ) return get_obj_from_str(config['target'] )(**config.get('params' , {} ) ) def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : List[Any] , _UpperCamelCase : List[str]=True , _UpperCamelCase : int=True ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =instantiate_from_config(_UpperCamelCase ) if sd is not None: model.load_state_dict(_UpperCamelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[int] ) -> List[Any]: """simple docstring""" if ckpt: _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location='cpu' ) _SCREAMING_SNAKE_CASE =pl_sd['global_step'] print(f"loaded model from global step {global_step}." ) else: _SCREAMING_SNAKE_CASE ={'state_dict': None} _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =load_model_from_config(config.model , pl_sd['state_dict'] , gpu=_UpperCamelCase , eval_mode=_UpperCamelCase )['model'] return model, global_step
47
1
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class UpperCamelCase ( unittest.TestCase ): def _UpperCAmelCase ( self ,__UpperCamelCase ) -> List[str]: '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] ,model_result['ss'] ): lowercase_ : Dict = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(__UpperCamelCase ) def _UpperCAmelCase ( self ) -> int: '''simple docstring''' lowercase_ : int = 'sshleifer/tiny-gpt2' lowercase_ : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] ,training=__UpperCamelCase ,inference=__UpperCamelCase ,sequence_lengths=[8] ,batch_sizes=[1] ,eager_mode=__UpperCamelCase ,multi_process=__UpperCamelCase ,) lowercase_ : Union[str, Any] = TensorFlowBenchmark(__UpperCamelCase ) lowercase_ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> Any: '''simple docstring''' lowercase_ : List[str] = 'sgugger/tiny-distilbert-classification' lowercase_ : Dict = TensorFlowBenchmarkArguments( models=[MODEL_ID] ,training=__UpperCamelCase ,inference=__UpperCamelCase ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=__UpperCamelCase ,only_pretrain_model=__UpperCamelCase ,) lowercase_ : int = TensorFlowBenchmark(__UpperCamelCase ) lowercase_ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> List[Any]: '''simple docstring''' lowercase_ : Any = 'sshleifer/tiny-gpt2' lowercase_ : Any = TensorFlowBenchmarkArguments( models=[MODEL_ID] ,training=__UpperCamelCase ,inference=__UpperCamelCase ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=__UpperCamelCase ,) lowercase_ : Optional[Any] = TensorFlowBenchmark(__UpperCamelCase ) lowercase_ : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> List[Any]: '''simple docstring''' lowercase_ : Dict = 'sshleifer/tiny-gpt2' lowercase_ : Tuple = AutoConfig.from_pretrained(__UpperCamelCase ) lowercase_ : str = TensorFlowBenchmarkArguments( models=[MODEL_ID] ,training=__UpperCamelCase ,inference=__UpperCamelCase ,sequence_lengths=[8] ,batch_sizes=[1] ,eager_mode=__UpperCamelCase ,multi_process=__UpperCamelCase ,) lowercase_ : str = TensorFlowBenchmark(__UpperCamelCase ,[config] ) lowercase_ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> Any: '''simple docstring''' lowercase_ : Any = 'sshleifer/tiny-gpt2' lowercase_ : Any = AutoConfig.from_pretrained(__UpperCamelCase ) lowercase_ : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] ,training=__UpperCamelCase ,inference=__UpperCamelCase ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=__UpperCamelCase ,) lowercase_ : int = TensorFlowBenchmark(__UpperCamelCase ,[config] ) lowercase_ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> Union[str, Any]: '''simple docstring''' lowercase_ : int = 'sshleifer/tiny-gpt2' lowercase_ : List[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] ,training=__UpperCamelCase ,inference=__UpperCamelCase ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=__UpperCamelCase ,) lowercase_ : List[str] = TensorFlowBenchmark(__UpperCamelCase ) lowercase_ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _UpperCAmelCase ( self ) -> Tuple: '''simple docstring''' lowercase_ : List[str] = 'sshleifer/tiny-gpt2' lowercase_ : Optional[int] = AutoConfig.from_pretrained(__UpperCamelCase ) lowercase_ : int = TensorFlowBenchmarkArguments( models=[MODEL_ID] ,training=__UpperCamelCase ,inference=__UpperCamelCase ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=__UpperCamelCase ,) lowercase_ : str = TensorFlowBenchmark(__UpperCamelCase ,[config] ) lowercase_ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _UpperCAmelCase ( self ) -> Dict: '''simple docstring''' lowercase_ : str = 'patrickvonplaten/t5-tiny-random' lowercase_ : int = AutoConfig.from_pretrained(__UpperCamelCase ) lowercase_ : Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] ,training=__UpperCamelCase ,inference=__UpperCamelCase ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=__UpperCamelCase ,) lowercase_ : List[str] = TensorFlowBenchmark(__UpperCamelCase ,configs=[config] ) lowercase_ : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices('GPU' ) ) == 0 ,'Cannot do xla on CPU.' ) def _UpperCAmelCase ( self ) -> Optional[int]: '''simple docstring''' lowercase_ : Optional[int] = 'sshleifer/tiny-gpt2' lowercase_ : Union[str, Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] ,training=__UpperCamelCase ,inference=__UpperCamelCase ,sequence_lengths=[8] ,batch_sizes=[1] ,use_xla=__UpperCamelCase ,multi_process=__UpperCamelCase ,) lowercase_ : Union[str, Any] = TensorFlowBenchmark(__UpperCamelCase ) lowercase_ : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> Tuple: '''simple docstring''' lowercase_ : List[str] = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Any = TensorFlowBenchmarkArguments( models=[MODEL_ID] ,inference=__UpperCamelCase ,save_to_csv=__UpperCamelCase ,sequence_lengths=[8] ,batch_sizes=[1] ,inference_time_csv_file=os.path.join(__UpperCamelCase ,'inf_time.csv' ) ,inference_memory_csv_file=os.path.join(__UpperCamelCase ,'inf_mem.csv' ) ,env_info_csv_file=os.path.join(__UpperCamelCase ,'env.csv' ) ,multi_process=__UpperCamelCase ,) lowercase_ : List[str] = TensorFlowBenchmark(__UpperCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(__UpperCamelCase ,'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCamelCase ,'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__UpperCamelCase ,'env.csv' ) ).exists() ) def _UpperCAmelCase ( self ) -> int: '''simple docstring''' lowercase_ : int = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(__UpperCamelCase ): self.assertTrue(hasattr(__UpperCamelCase ,'sequential' ) ) self.assertTrue(hasattr(__UpperCamelCase ,'cumulative' ) ) self.assertTrue(hasattr(__UpperCamelCase ,'current' ) ) self.assertTrue(hasattr(__UpperCamelCase ,'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: lowercase_ : Dict = TensorFlowBenchmarkArguments( models=[MODEL_ID] ,inference=__UpperCamelCase ,sequence_lengths=[8] ,batch_sizes=[1] ,log_filename=os.path.join(__UpperCamelCase ,'log.txt' ) ,log_print=__UpperCamelCase ,trace_memory_line_by_line=__UpperCamelCase ,eager_mode=__UpperCamelCase ,multi_process=__UpperCamelCase ,) lowercase_ : Dict = TensorFlowBenchmark(__UpperCamelCase ) lowercase_ : Any = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(__UpperCamelCase ,'log.txt' ) ).exists() )
321
"""simple docstring""" 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 CLIPSegProcessor, ViTImageProcessor @require_vision class UpperCamelCase ( unittest.TestCase ): def _UpperCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' lowercase_ : List[Any] = tempfile.mkdtemp() # fmt: off lowercase_ : Any = ['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 lowercase_ : int = dict(zip(__UpperCamelCase ,range(len(__UpperCamelCase ) ) ) ) lowercase_ : Union[str, Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] lowercase_ : Tuple = {'unk_token': '<unk>'} lowercase_ : str = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) lowercase_ : int = 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(__UpperCamelCase ) + '\n' ) with open(self.merges_file ,'w' ,encoding='utf-8' ) as fp: fp.write('\n'.join(__UpperCamelCase ) ) lowercase_ : Any = { '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], } lowercase_ : List[str] = os.path.join(self.tmpdirname ,__UpperCamelCase ) with open(self.image_processor_file ,'w' ,encoding='utf-8' ) as fp: json.dump(__UpperCamelCase ,__UpperCamelCase ) def _UpperCAmelCase ( self ,**__UpperCamelCase ) -> Optional[int]: '''simple docstring''' return CLIPTokenizer.from_pretrained(self.tmpdirname ,**__UpperCamelCase ) def _UpperCAmelCase ( self ,**__UpperCamelCase ) -> Union[str, Any]: '''simple docstring''' return CLIPTokenizerFast.from_pretrained(self.tmpdirname ,**__UpperCamelCase ) def _UpperCAmelCase ( self ,**__UpperCamelCase ) -> str: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname ,**__UpperCamelCase ) def _UpperCAmelCase ( self ) -> Tuple: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _UpperCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' lowercase_ : Dict = [np.random.randint(255 ,size=(3, 30, 400) ,dtype=np.uinta )] lowercase_ : List[str] = [Image.fromarray(np.moveaxis(__UpperCamelCase ,0 ,-1 ) ) for x in image_inputs] return image_inputs def _UpperCAmelCase ( self ) -> str: '''simple docstring''' lowercase_ : Optional[int] = self.get_tokenizer() lowercase_ : List[Any] = self.get_rust_tokenizer() lowercase_ : Tuple = self.get_image_processor() lowercase_ : Optional[int] = CLIPSegProcessor(tokenizer=__UpperCamelCase ,image_processor=__UpperCamelCase ) processor_slow.save_pretrained(self.tmpdirname ) lowercase_ : Union[str, Any] = CLIPSegProcessor.from_pretrained(self.tmpdirname ,use_fast=__UpperCamelCase ) lowercase_ : List[Any] = CLIPSegProcessor(tokenizer=__UpperCamelCase ,image_processor=__UpperCamelCase ) processor_fast.save_pretrained(self.tmpdirname ) lowercase_ : str = CLIPSegProcessor.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 ,__UpperCamelCase ) self.assertIsInstance(processor_fast.tokenizer ,__UpperCamelCase ) 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 ,__UpperCamelCase ) self.assertIsInstance(processor_fast.image_processor ,__UpperCamelCase ) def _UpperCAmelCase ( self ) -> List[str]: '''simple docstring''' lowercase_ : Optional[int] = CLIPSegProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowercase_ : List[Any] = self.get_tokenizer(bos_token='(BOS)' ,eos_token='(EOS)' ) lowercase_ : Any = self.get_image_processor(do_normalize=__UpperCamelCase ,padding_value=1.0 ) lowercase_ : Any = CLIPSegProcessor.from_pretrained( self.tmpdirname ,bos_token='(BOS)' ,eos_token='(EOS)' ,do_normalize=__UpperCamelCase ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,__UpperCamelCase ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,__UpperCamelCase ) def _UpperCAmelCase ( self ) -> Dict: '''simple docstring''' lowercase_ : Dict = self.get_image_processor() lowercase_ : List[str] = self.get_tokenizer() lowercase_ : List[str] = CLIPSegProcessor(tokenizer=__UpperCamelCase ,image_processor=__UpperCamelCase ) lowercase_ : List[Any] = self.prepare_image_inputs() lowercase_ : str = image_processor(__UpperCamelCase ,return_tensors='np' ) lowercase_ : Union[str, Any] = processor(images=__UpperCamelCase ,return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1e-2 ) def _UpperCAmelCase ( self ) -> List[str]: '''simple docstring''' lowercase_ : Dict = self.get_image_processor() lowercase_ : List[Any] = self.get_tokenizer() lowercase_ : List[Any] = CLIPSegProcessor(tokenizer=__UpperCamelCase ,image_processor=__UpperCamelCase ) lowercase_ : Dict = 'lower newer' lowercase_ : Any = processor(text=__UpperCamelCase ) lowercase_ : int = tokenizer(__UpperCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def _UpperCAmelCase ( self ) -> Union[str, Any]: '''simple docstring''' lowercase_ : str = self.get_image_processor() lowercase_ : str = self.get_tokenizer() lowercase_ : int = CLIPSegProcessor(tokenizer=__UpperCamelCase ,image_processor=__UpperCamelCase ) lowercase_ : List[Any] = 'lower newer' lowercase_ : str = self.prepare_image_inputs() lowercase_ : Optional[int] = processor(text=__UpperCamelCase ,images=__UpperCamelCase ) self.assertListEqual(list(inputs.keys() ) ,['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(__UpperCamelCase ): processor() def _UpperCAmelCase ( self ) -> Tuple: '''simple docstring''' lowercase_ : Tuple = self.get_image_processor() lowercase_ : Optional[Any] = self.get_tokenizer() lowercase_ : List[str] = CLIPSegProcessor(tokenizer=__UpperCamelCase ,image_processor=__UpperCamelCase ) lowercase_ : Optional[int] = self.prepare_image_inputs() lowercase_ : Optional[Any] = self.prepare_image_inputs() lowercase_ : int = processor(images=__UpperCamelCase ,visual_prompt=__UpperCamelCase ) self.assertListEqual(list(inputs.keys() ) ,['pixel_values', 'conditional_pixel_values'] ) # test if it raises when no input is passed with pytest.raises(__UpperCamelCase ): processor() def _UpperCAmelCase ( self ) -> Dict: '''simple docstring''' lowercase_ : List[str] = self.get_image_processor() lowercase_ : Optional[Any] = self.get_tokenizer() lowercase_ : int = CLIPSegProcessor(tokenizer=__UpperCamelCase ,image_processor=__UpperCamelCase ) lowercase_ : Optional[int] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowercase_ : List[str] = processor.batch_decode(__UpperCamelCase ) lowercase_ : Optional[Any] = tokenizer.batch_decode(__UpperCamelCase ) self.assertListEqual(__UpperCamelCase ,__UpperCamelCase )
321
1
def UpperCamelCase( __UpperCamelCase : int ): return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
103
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A__ : List[Any] = logging.get_logger(__name__) def UpperCamelCase( __UpperCamelCase : List[str] ): lowerCAmelCase_ : Any = DPTConfig(embedding_type='''hybrid''' ) if "large" in checkpoint_url: lowerCAmelCase_ : Any = 1024 lowerCAmelCase_ : Tuple = 4096 lowerCAmelCase_ : List[Any] = 24 lowerCAmelCase_ : int = 16 lowerCAmelCase_ : Tuple = [5, 11, 17, 23] lowerCAmelCase_ : Optional[Any] = [256, 512, 1024, 1024] lowerCAmelCase_ : str = (1, 384, 384) if "nyu" or "midas" in checkpoint_url: lowerCAmelCase_ : Union[str, Any] = 768 lowerCAmelCase_ : int = [1, 1, 1, 0.5] lowerCAmelCase_ : List[str] = [256, 512, 768, 768] lowerCAmelCase_ : int = 150 lowerCAmelCase_ : Any = 16 lowerCAmelCase_ : Any = (1, 384, 384) lowerCAmelCase_ : List[str] = False lowerCAmelCase_ : Union[str, Any] = '''project''' if "ade" in checkpoint_url: lowerCAmelCase_ : Any = True lowerCAmelCase_ : Any = 768 lowerCAmelCase_ : Optional[int] = [1, 1, 1, 0.5] lowerCAmelCase_ : Union[str, Any] = 150 lowerCAmelCase_ : Any = 16 lowerCAmelCase_ : Any = '''huggingface/label-files''' lowerCAmelCase_ : Any = '''ade20k-id2label.json''' lowerCAmelCase_ : str = json.load(open(cached_download(hf_hub_url(__UpperCamelCase ,__UpperCamelCase ,repo_type='''dataset''' ) ) ,'''r''' ) ) lowerCAmelCase_ : Optional[Any] = {int(__UpperCamelCase ): v for k, v in idalabel.items()} lowerCAmelCase_ : Optional[Any] = idalabel lowerCAmelCase_ : Optional[int] = {v: k for k, v in idalabel.items()} lowerCAmelCase_ : List[Any] = [1, 150, 480, 480] return config, expected_shape def UpperCamelCase( __UpperCamelCase : Optional[int] ): lowerCAmelCase_ : int = ['''pretrained.model.head.weight''', '''pretrained.model.head.bias'''] for k in ignore_keys: state_dict.pop(__UpperCamelCase ,__UpperCamelCase ) def UpperCamelCase( __UpperCamelCase : int ): if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): lowerCAmelCase_ : Dict = name.replace('''pretrained.model''' ,'''dpt.encoder''' ) if "pretrained.model" in name: lowerCAmelCase_ : List[Any] = name.replace('''pretrained.model''' ,'''dpt.embeddings''' ) if "patch_embed" in name: lowerCAmelCase_ : Optional[Any] = name.replace('''patch_embed''' ,'''''' ) if "pos_embed" in name: lowerCAmelCase_ : Dict = name.replace('''pos_embed''' ,'''position_embeddings''' ) if "attn.proj" in name: lowerCAmelCase_ : Any = name.replace('''attn.proj''' ,'''attention.output.dense''' ) if "proj" in name and "project" not in name: lowerCAmelCase_ : Tuple = name.replace('''proj''' ,'''projection''' ) if "blocks" in name: lowerCAmelCase_ : Optional[Any] = name.replace('''blocks''' ,'''layer''' ) if "mlp.fc1" in name: lowerCAmelCase_ : Optional[int] = name.replace('''mlp.fc1''' ,'''intermediate.dense''' ) if "mlp.fc2" in name: lowerCAmelCase_ : Union[str, Any] = name.replace('''mlp.fc2''' ,'''output.dense''' ) if "norm1" in name and "backbone" not in name: lowerCAmelCase_ : List[str] = name.replace('''norm1''' ,'''layernorm_before''' ) if "norm2" in name and "backbone" not in name: lowerCAmelCase_ : Optional[Any] = name.replace('''norm2''' ,'''layernorm_after''' ) if "scratch.output_conv" in name: lowerCAmelCase_ : Optional[int] = name.replace('''scratch.output_conv''' ,'''head''' ) if "scratch" in name: lowerCAmelCase_ : Dict = name.replace('''scratch''' ,'''neck''' ) if "layer1_rn" in name: lowerCAmelCase_ : Optional[int] = name.replace('''layer1_rn''' ,'''convs.0''' ) if "layer2_rn" in name: lowerCAmelCase_ : Union[str, Any] = name.replace('''layer2_rn''' ,'''convs.1''' ) if "layer3_rn" in name: lowerCAmelCase_ : List[Any] = name.replace('''layer3_rn''' ,'''convs.2''' ) if "layer4_rn" in name: lowerCAmelCase_ : Optional[int] = name.replace('''layer4_rn''' ,'''convs.3''' ) if "refinenet" in name: lowerCAmelCase_ : List[str] = int(name[len('''neck.refinenet''' ) : len('''neck.refinenet''' ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 lowerCAmelCase_ : Dict = name.replace(f"""refinenet{layer_idx}""" ,f"""fusion_stage.layers.{abs(layer_idx-4 )}""" ) if "out_conv" in name: lowerCAmelCase_ : int = name.replace('''out_conv''' ,'''projection''' ) if "resConfUnit1" in name: lowerCAmelCase_ : Dict = name.replace('''resConfUnit1''' ,'''residual_layer1''' ) if "resConfUnit2" in name: lowerCAmelCase_ : str = name.replace('''resConfUnit2''' ,'''residual_layer2''' ) if "conv1" in name: lowerCAmelCase_ : str = name.replace('''conv1''' ,'''convolution1''' ) if "conv2" in name: lowerCAmelCase_ : Optional[Any] = name.replace('''conv2''' ,'''convolution2''' ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: lowerCAmelCase_ : Dict = name.replace('''pretrained.act_postprocess1.0.project.0''' ,'''neck.reassemble_stage.readout_projects.0.0''' ) if "pretrained.act_postprocess2.0.project.0" in name: lowerCAmelCase_ : Optional[int] = name.replace('''pretrained.act_postprocess2.0.project.0''' ,'''neck.reassemble_stage.readout_projects.1.0''' ) if "pretrained.act_postprocess3.0.project.0" in name: lowerCAmelCase_ : Tuple = name.replace('''pretrained.act_postprocess3.0.project.0''' ,'''neck.reassemble_stage.readout_projects.2.0''' ) if "pretrained.act_postprocess4.0.project.0" in name: lowerCAmelCase_ : Dict = name.replace('''pretrained.act_postprocess4.0.project.0''' ,'''neck.reassemble_stage.readout_projects.3.0''' ) # resize blocks if "pretrained.act_postprocess1.3" in name: lowerCAmelCase_ : List[Any] = name.replace('''pretrained.act_postprocess1.3''' ,'''neck.reassemble_stage.layers.0.projection''' ) if "pretrained.act_postprocess1.4" in name: lowerCAmelCase_ : Dict = name.replace('''pretrained.act_postprocess1.4''' ,'''neck.reassemble_stage.layers.0.resize''' ) if "pretrained.act_postprocess2.3" in name: lowerCAmelCase_ : List[Any] = name.replace('''pretrained.act_postprocess2.3''' ,'''neck.reassemble_stage.layers.1.projection''' ) if "pretrained.act_postprocess2.4" in name: lowerCAmelCase_ : List[str] = name.replace('''pretrained.act_postprocess2.4''' ,'''neck.reassemble_stage.layers.1.resize''' ) if "pretrained.act_postprocess3.3" in name: lowerCAmelCase_ : Optional[Any] = name.replace('''pretrained.act_postprocess3.3''' ,'''neck.reassemble_stage.layers.2.projection''' ) if "pretrained.act_postprocess4.3" in name: lowerCAmelCase_ : List[str] = name.replace('''pretrained.act_postprocess4.3''' ,'''neck.reassemble_stage.layers.3.projection''' ) if "pretrained.act_postprocess4.4" in name: lowerCAmelCase_ : Optional[Any] = name.replace('''pretrained.act_postprocess4.4''' ,'''neck.reassemble_stage.layers.3.resize''' ) if "pretrained" in name: lowerCAmelCase_ : Tuple = name.replace('''pretrained''' ,'''dpt''' ) if "bn" in name: lowerCAmelCase_ : Dict = name.replace('''bn''' ,'''batch_norm''' ) if "head" in name: lowerCAmelCase_ : Any = name.replace('''head''' ,'''head.head''' ) if "encoder.norm" in name: lowerCAmelCase_ : Tuple = name.replace('''encoder.norm''' ,'''layernorm''' ) if "auxlayer" in name: lowerCAmelCase_ : Optional[int] = name.replace('''auxlayer''' ,'''auxiliary_head.head''' ) if "backbone" in name: lowerCAmelCase_ : List[Any] = name.replace('''backbone''' ,'''backbone.bit.encoder''' ) if ".." in name: lowerCAmelCase_ : List[Any] = name.replace('''..''' ,'''.''' ) if "stem.conv" in name: lowerCAmelCase_ : str = name.replace('''stem.conv''' ,'''bit.embedder.convolution''' ) if "blocks" in name: lowerCAmelCase_ : List[str] = name.replace('''blocks''' ,'''layers''' ) if "convolution" in name and "backbone" in name: lowerCAmelCase_ : Optional[int] = name.replace('''convolution''' ,'''conv''' ) if "layer" in name and "backbone" in name: lowerCAmelCase_ : Optional[int] = name.replace('''layer''' ,'''layers''' ) if "backbone.bit.encoder.bit" in name: lowerCAmelCase_ : Union[str, Any] = name.replace('''backbone.bit.encoder.bit''' ,'''backbone.bit''' ) if "embedder.conv" in name: lowerCAmelCase_ : str = name.replace('''embedder.conv''' ,'''embedder.convolution''' ) if "backbone.bit.encoder.stem.norm" in name: lowerCAmelCase_ : Dict = name.replace('''backbone.bit.encoder.stem.norm''' ,'''backbone.bit.embedder.norm''' ) return name def UpperCamelCase( __UpperCamelCase : Union[str, Any] ,__UpperCamelCase : List[str] ): for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowerCAmelCase_ : Dict = state_dict.pop(f"""dpt.encoder.layer.{i}.attn.qkv.weight""" ) lowerCAmelCase_ : Tuple = state_dict.pop(f"""dpt.encoder.layer.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict lowerCAmelCase_ : str = in_proj_weight[: config.hidden_size, :] lowerCAmelCase_ : str = in_proj_bias[: config.hidden_size] lowerCAmelCase_ : Optional[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCAmelCase_ : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowerCAmelCase_ : Any = in_proj_weight[ -config.hidden_size :, : ] lowerCAmelCase_ : Dict = in_proj_bias[-config.hidden_size :] def UpperCamelCase( ): lowerCAmelCase_ : str = '''http://images.cocodataset.org/val2017/000000039769.jpg''' lowerCAmelCase_ : Dict = Image.open(requests.get(__UpperCamelCase ,stream=__UpperCamelCase ).raw ) return im @torch.no_grad() def UpperCamelCase( __UpperCamelCase : Optional[int] ,__UpperCamelCase : Dict ,__UpperCamelCase : Optional[int] ,__UpperCamelCase : Optional[int] ,__UpperCamelCase : str ): lowerCAmelCase_ , lowerCAmelCase_ : Any = get_dpt_config(__UpperCamelCase ) # load original state_dict from URL # state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu") lowerCAmelCase_ : List[str] = torch.load(__UpperCamelCase ,map_location='''cpu''' ) # remove certain keys remove_ignore_keys_(__UpperCamelCase ) # rename keys for key in state_dict.copy().keys(): lowerCAmelCase_ : Any = state_dict.pop(__UpperCamelCase ) lowerCAmelCase_ : Optional[Any] = val # read in qkv matrices read_in_q_k_v(__UpperCamelCase ,__UpperCamelCase ) # load HuggingFace model lowerCAmelCase_ : List[Any] = DPTForSemanticSegmentation(__UpperCamelCase ) if '''ade''' in checkpoint_url else DPTForDepthEstimation(__UpperCamelCase ) model.load_state_dict(__UpperCamelCase ) model.eval() # Check outputs on an image lowerCAmelCase_ : Tuple = 480 if '''ade''' in checkpoint_url else 384 lowerCAmelCase_ : Optional[int] = DPTImageProcessor(size=__UpperCamelCase ) lowerCAmelCase_ : Union[str, Any] = prepare_img() lowerCAmelCase_ : str = image_processor(__UpperCamelCase ,return_tensors='''pt''' ) # forward pass lowerCAmelCase_ : Tuple = model(**__UpperCamelCase ).logits if '''ade''' in checkpoint_url else model(**__UpperCamelCase ).predicted_depth if show_prediction: lowerCAmelCase_ : Optional[Any] = ( torch.nn.functional.interpolate( outputs.unsqueeze(1 ) ,size=(image.size[1], image.size[0]) ,mode='''bicubic''' ,align_corners=__UpperCamelCase ,) .squeeze() .cpu() .numpy() ) Image.fromarray((prediction / prediction.max()) * 255 ).show() if pytorch_dump_folder_path is not None: Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(__UpperCamelCase ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__UpperCamelCase ) if push_to_hub: model.push_to_hub('''ybelkada/dpt-hybrid-midas''' ) image_processor.push_to_hub('''ybelkada/dpt-hybrid-midas''' ) if __name__ == "__main__": A__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt''', type=str, help='''URL of the original DPT checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=False, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', ) parser.add_argument( '''--model_name''', default='''dpt-large''', type=str, help='''Name of the model, in case you\'re pushing to the hub.''', ) parser.add_argument( '''--show_prediction''', action='''store_true''', ) A__ : Union[str, Any] = parser.parse_args() convert_dpt_checkpoint( args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name, args.show_prediction )
103
1
def lowerCAmelCase__ ( a__ , a__ , a__ ) ->list: '''simple docstring''' _UpperCamelCase = len(a__ ) _UpperCamelCase = [[0] * n for i in range(a__ )] for i in range(a__ ): _UpperCamelCase = y_points[i] for i in range(2 , a__ ): for j in range(a__ , a__ ): _UpperCamelCase = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
63
import re def lowerCAmelCase__ ( a__ ) ->str: '''simple docstring''' if len(re.findall("[ATCG]" , a__ ) ) != len(a__ ): raise ValueError("Invalid Strand" ) return dna.translate(dna.maketrans("ATCG" , "TAGC" ) ) if __name__ == "__main__": import doctest doctest.testmod()
63
1
"""simple docstring""" from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging lowerCAmelCase_ = logging.get_logger(__name__) class __A ( A_ ): '''simple docstring''' lowerCAmelCase : Any = ["pixel_values"] def __init__( self : int ,_snake_case : bool = True ,_snake_case : Dict[str, int] = None ,_snake_case : PILImageResampling = PILImageResampling.BICUBIC ,_snake_case : bool = True ,_snake_case : Dict[str, int] = None ,_snake_case : bool = True ,_snake_case : Union[int, float] = 1 / 255 ,_snake_case : bool = True ,_snake_case : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN ,_snake_case : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD ,**_snake_case : Optional[int] ,) -> None: """simple docstring""" super().__init__(**_snake_case ) lowercase__ : List[str] = size if size is not None else {'''shortest_edge''': 224} lowercase__ : Union[str, Any] = get_size_dict(_snake_case ,default_to_square=_snake_case ) lowercase__ : Dict = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} lowercase__ : int = get_size_dict(_snake_case ,param_name='''crop_size''' ) lowercase__ : List[str] = do_resize lowercase__ : List[str] = size lowercase__ : List[Any] = resample lowercase__ : Any = do_center_crop lowercase__ : List[str] = crop_size lowercase__ : Union[str, Any] = do_rescale lowercase__ : List[Any] = rescale_factor lowercase__ : Optional[int] = do_normalize lowercase__ : Tuple = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowercase__ : List[str] = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCAmelCase ( self : List[str] ,_snake_case : np.ndarray ,_snake_case : Dict[str, int] ,_snake_case : PILImageResampling = PILImageResampling.BICUBIC ,_snake_case : Optional[Union[str, ChannelDimension]] = None ,**_snake_case : List[Any] ,) -> np.ndarray: """simple docstring""" lowercase__ : List[str] = get_size_dict(_snake_case ,default_to_square=_snake_case ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: lowercase__ : Optional[Any] = int((256 / 224) * size['''shortest_edge'''] ) lowercase__ : List[str] = get_resize_output_image_size(_snake_case ,size=_snake_case ,default_to_square=_snake_case ) lowercase__ : List[str] = {'''height''': output_size[0], '''width''': output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f"""Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}""" ) return resize( _snake_case ,size=(size_dict['''height'''], size_dict['''width''']) ,resample=_snake_case ,data_format=_snake_case ,**_snake_case ) def UpperCAmelCase ( self : Dict ,_snake_case : np.ndarray ,_snake_case : Dict[str, int] ,_snake_case : Optional[Union[str, ChannelDimension]] = None ,**_snake_case : List[str] ,) -> np.ndarray: """simple docstring""" lowercase__ : List[str] = get_size_dict(_snake_case ) if "height" not in size or "width" not in size: raise ValueError(f"""Size dict must have keys 'height' and 'width'. Got {size.keys()}""" ) return center_crop(_snake_case ,size=(size['''height'''], size['''width''']) ,data_format=_snake_case ,**_snake_case ) def UpperCAmelCase ( self : Union[str, Any] ,_snake_case : np.ndarray ,_snake_case : Union[int, float] ,_snake_case : Optional[Union[str, ChannelDimension]] = None ,**_snake_case : Any ,) -> np.ndarray: """simple docstring""" return rescale(_snake_case ,scale=_snake_case ,data_format=_snake_case ,**_snake_case ) def UpperCAmelCase ( self : Optional[int] ,_snake_case : np.ndarray ,_snake_case : Union[float, List[float]] ,_snake_case : Union[float, List[float]] ,_snake_case : Optional[Union[str, ChannelDimension]] = None ,**_snake_case : Tuple ,) -> np.ndarray: """simple docstring""" return normalize(_snake_case ,mean=_snake_case ,std=_snake_case ,data_format=_snake_case ,**_snake_case ) def UpperCAmelCase ( self : Optional[Any] ,_snake_case : ImageInput ,_snake_case : Optional[bool] = None ,_snake_case : Optional[Dict[str, int]] = None ,_snake_case : PILImageResampling = None ,_snake_case : Optional[bool] = None ,_snake_case : Optional[Dict[str, int]] = None ,_snake_case : Optional[bool] = None ,_snake_case : Optional[float] = None ,_snake_case : Optional[bool] = None ,_snake_case : Optional[Union[float, Iterable[float]]] = None ,_snake_case : Optional[Union[float, Iterable[float]]] = None ,_snake_case : Optional[TensorType] = None ,_snake_case : ChannelDimension = ChannelDimension.FIRST ,**_snake_case : Dict ,) -> BatchFeature: """simple docstring""" lowercase__ : Tuple = do_resize if do_resize is not None else self.do_resize lowercase__ : str = resample if resample is not None else self.resample lowercase__ : List[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop lowercase__ : int = do_rescale if do_rescale is not None else self.do_rescale lowercase__ : Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase__ : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize lowercase__ : str = image_mean if image_mean is not None else self.image_mean lowercase__ : Optional[int] = image_std if image_std is not None else self.image_std lowercase__ : Optional[Any] = size if size is not None else self.size lowercase__ : Tuple = get_size_dict(_snake_case ,default_to_square=_snake_case ) lowercase__ : Optional[Any] = crop_size if crop_size is not None else self.crop_size lowercase__ : int = get_size_dict(_snake_case ,param_name='''crop_size''' ) lowercase__ : Union[str, Any] = make_list_of_images(_snake_case ) if not valid_images(_snake_case ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. lowercase__ : Tuple = [to_numpy_array(_snake_case ) for image in images] if do_resize: lowercase__ : Any = [self.resize(_snake_case ,_snake_case ,_snake_case ) for image in images] if do_center_crop: lowercase__ : Tuple = [self.center_crop(_snake_case ,_snake_case ) for image in images] if do_rescale: lowercase__ : Dict = [self.rescale(_snake_case ,_snake_case ) for image in images] if do_normalize: lowercase__ : List[str] = [self.normalize(_snake_case ,_snake_case ,_snake_case ) for image in images] lowercase__ : int = [to_channel_dimension_format(_snake_case ,_snake_case ) for image in images] lowercase__ : Union[str, Any] = {'''pixel_values''': images} return BatchFeature(data=_snake_case ,tensor_type=_snake_case )
16
from typing import TYPE_CHECKING from ...utils import _LazyModule lowercase = {"processing_wav2vec2_with_lm": ["Wav2Vec2ProcessorWithLM"]} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys lowercase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
178
0
'''simple docstring''' def __lowerCamelCase ( ) -> int: return 1 def __lowerCamelCase ( __lowerCAmelCase : int ) -> int: return 0 if x < 0 else two_pence(x - 2 ) + one_pence() def __lowerCamelCase ( __lowerCAmelCase : int ) -> int: return 0 if x < 0 else five_pence(x - 5 ) + two_pence(__lowerCAmelCase ) def __lowerCamelCase ( __lowerCAmelCase : int ) -> int: return 0 if x < 0 else ten_pence(x - 10 ) + five_pence(__lowerCAmelCase ) def __lowerCamelCase ( __lowerCAmelCase : int ) -> int: return 0 if x < 0 else twenty_pence(x - 20 ) + ten_pence(__lowerCAmelCase ) def __lowerCamelCase ( __lowerCAmelCase : int ) -> int: return 0 if x < 0 else fifty_pence(x - 50 ) + twenty_pence(__lowerCAmelCase ) def __lowerCamelCase ( __lowerCAmelCase : int ) -> int: return 0 if x < 0 else one_pound(x - 1_00 ) + fifty_pence(__lowerCAmelCase ) def __lowerCamelCase ( __lowerCAmelCase : int ) -> int: return 0 if x < 0 else two_pound(x - 2_00 ) + one_pound(__lowerCAmelCase ) def __lowerCamelCase ( __lowerCAmelCase : int = 2_00 ) -> int: return two_pound(__lowerCAmelCase ) if __name__ == "__main__": print(solution(int(input().strip())))
3
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , __snake_case : Optional[Any] , __snake_case : List[Any]=7 , __snake_case : Optional[Any]=3 , __snake_case : str=18 , __snake_case : Union[str, Any]=30 , __snake_case : Union[str, Any]=4_00 , __snake_case : Optional[int]=True , __snake_case : Any=None , __snake_case : List[str]=True , )-> Optional[Any]: snake_case = size if size is not None else {"""height""": 18, """width""": 18} snake_case = parent snake_case = batch_size snake_case = num_channels snake_case = image_size snake_case = min_resolution snake_case = max_resolution snake_case = do_resize snake_case = size snake_case = apply_ocr def lowerCAmelCase ( self : List[Any] )-> List[str]: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _lowerCAmelCase ( A__ , unittest.TestCase ): """simple docstring""" snake_case_ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def lowerCAmelCase ( self : int )-> Tuple: snake_case = LayoutLMvaImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple )-> Tuple: return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Union[str, Any] )-> Any: snake_case = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__snake_case , """do_resize""" ) ) self.assertTrue(hasattr(__snake_case , """size""" ) ) self.assertTrue(hasattr(__snake_case , """apply_ocr""" ) ) def lowerCAmelCase ( self : List[str] )-> List[Any]: snake_case = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Dict )-> Union[str, Any]: pass def lowerCAmelCase ( self : Tuple )-> Dict: # Initialize image_processing snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , Image.Image ) # Test not batched input snake_case = image_processing(image_inputs[0] , return_tensors="""pt""" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) self.assertIsInstance(encoding.words , __snake_case ) self.assertIsInstance(encoding.boxes , __snake_case ) # Test batched snake_case = image_processing(__snake_case , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def lowerCAmelCase ( self : int )-> str: # Initialize image_processing snake_case = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , numpify=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , np.ndarray ) # Test not batched input snake_case = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched snake_case = image_processing(__snake_case , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def lowerCAmelCase ( self : List[Any] )-> Optional[Any]: # Initialize image_processing snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , torchify=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , torch.Tensor ) # Test not batched input snake_case = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched snake_case = image_processing(__snake_case , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) def lowerCAmelCase ( self : int )-> List[Any]: # with apply_OCR = True snake_case = LayoutLMvaImageProcessor() from datasets import load_dataset snake_case = load_dataset("""hf-internal-testing/fixtures_docvqa""" , split="""test""" ) snake_case = Image.open(ds[0]["""file"""] ).convert("""RGB""" ) snake_case = image_processing(__snake_case , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 snake_case = [["""11:14""", """to""", """11:39""", """a.m""", """11:39""", """to""", """11:44""", """a.m.""", """11:44""", """a.m.""", """to""", """12:25""", """p.m.""", """12:25""", """to""", """12:58""", """p.m.""", """12:58""", """to""", """4:00""", """p.m.""", """2:00""", """to""", """5:00""", """p.m.""", """Coffee""", """Break""", """Coffee""", """will""", """be""", """served""", """for""", """men""", """and""", """women""", """in""", """the""", """lobby""", """adjacent""", """to""", """exhibit""", """area.""", """Please""", """move""", """into""", """exhibit""", """area.""", """(Exhibits""", """Open)""", """TRRF""", """GENERAL""", """SESSION""", """(PART""", """|)""", """Presiding:""", """Lee""", """A.""", """Waller""", """TRRF""", """Vice""", """President""", """“Introductory""", """Remarks”""", """Lee""", """A.""", """Waller,""", """TRRF""", """Vice""", """Presi-""", """dent""", """Individual""", """Interviews""", """with""", """TRRF""", """Public""", """Board""", """Members""", """and""", """Sci-""", """entific""", """Advisory""", """Council""", """Mem-""", """bers""", """Conducted""", """by""", """TRRF""", """Treasurer""", """Philip""", """G.""", """Kuehn""", """to""", """get""", """answers""", """which""", """the""", """public""", """refrigerated""", """warehousing""", """industry""", """is""", """looking""", """for.""", """Plus""", """questions""", """from""", """the""", """floor.""", """Dr.""", """Emil""", """M.""", """Mrak,""", """University""", """of""", """Cal-""", """ifornia,""", """Chairman,""", """TRRF""", """Board;""", """Sam""", """R.""", """Cecil,""", """University""", """of""", """Georgia""", """College""", """of""", """Agriculture;""", """Dr.""", """Stanley""", """Charm,""", """Tufts""", """University""", """School""", """of""", """Medicine;""", """Dr.""", """Robert""", """H.""", """Cotton,""", """ITT""", """Continental""", """Baking""", """Company;""", """Dr.""", """Owen""", """Fennema,""", """University""", """of""", """Wis-""", """consin;""", """Dr.""", """Robert""", """E.""", """Hardenburg,""", """USDA.""", """Questions""", """and""", """Answers""", """Exhibits""", """Open""", """Capt.""", """Jack""", """Stoney""", """Room""", """TRRF""", """Scientific""", """Advisory""", """Council""", """Meeting""", """Ballroom""", """Foyer"""]] # noqa: E231 snake_case = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __snake_case ) self.assertListEqual(encoding.boxes , __snake_case ) # with apply_OCR = False snake_case = LayoutLMvaImageProcessor(apply_ocr=__snake_case ) snake_case = image_processing(__snake_case , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) )
3
1
"""simple docstring""" import pytest import datasets # Import fixture modules as plugins lowerCAmelCase__ = ['''tests.fixtures.files''', '''tests.fixtures.hub''', '''tests.fixtures.fsspec'''] def snake_case_ ( A_ : Optional[Any], A_ : int ): '''simple docstring''' for item in items: if any(marker in item.keywords for marker in ['''integration''', '''unit'''] ): continue item.add_marker(pytest.mark.unit ) def snake_case_ ( A_ : Tuple ): '''simple docstring''' config.addinivalue_line('''markers''', '''torchaudio_latest: mark test to run with torchaudio>=0.12''' ) @pytest.fixture(autouse=A_ ) def snake_case_ ( A_ : List[str], A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : Any = tmp_path_factory.getbasetemp() / '''cache''' _lowerCamelCase : Tuple = test_hf_cache_home / '''datasets''' _lowerCamelCase : List[str] = test_hf_cache_home / '''metrics''' _lowerCamelCase : Optional[int] = test_hf_cache_home / '''modules''' monkeypatch.setattr('''datasets.config.HF_DATASETS_CACHE''', str(A_ ) ) monkeypatch.setattr('''datasets.config.HF_METRICS_CACHE''', str(A_ ) ) monkeypatch.setattr('''datasets.config.HF_MODULES_CACHE''', str(A_ ) ) _lowerCamelCase : Any = test_hf_datasets_cache / '''downloads''' monkeypatch.setattr('''datasets.config.DOWNLOADED_DATASETS_PATH''', str(A_ ) ) _lowerCamelCase : Optional[Any] = test_hf_datasets_cache / '''downloads''' / '''extracted''' monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''', str(A_ ) ) @pytest.fixture(autouse=A_, scope='''session''' ) def snake_case_ ( ): '''simple docstring''' datasets.disable_progress_bar() @pytest.fixture(autouse=A_ ) def snake_case_ ( A_ : Tuple ): '''simple docstring''' monkeypatch.setattr('''datasets.config.HF_UPDATE_DOWNLOAD_COUNTS''', A_ ) @pytest.fixture def snake_case_ ( A_ : str ): '''simple docstring''' monkeypatch.setattr('''sqlalchemy.util.deprecations.SILENCE_UBER_WARNING''', A_ )
72
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Union[str, Any] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : List[Any] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : int = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : int = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] _lowerCamelCase : Optional[int] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] _lowerCamelCase : Union[str, Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : str = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] _lowerCamelCase : Optional[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : Tuple = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] _lowerCamelCase : Any = '''fp16''' self.assertFalse(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] _lowerCamelCase : str = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] _lowerCamelCase : Union[str, Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : int = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] _lowerCamelCase : int = '''fp16''' self.assertFalse(is_safetensors_compatible(__lowerCAmelCase , variant=__lowerCAmelCase ) )
72
1
"""simple docstring""" import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch __A : str = logging.get_logger(__name__) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None ): if not conversation_id: UpperCamelCase : Optional[int] = uuid.uuida() if past_user_inputs is None: UpperCamelCase : Any = [] if generated_responses is None: UpperCamelCase : List[str] = [] UpperCamelCase : uuid.UUID = conversation_id UpperCamelCase : List[str] = past_user_inputs UpperCamelCase : List[str] = generated_responses UpperCamelCase : Optional[str] = text def __eq__( self , SCREAMING_SNAKE_CASE_ ): if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): return False if self.uuid == other.uuid: return True return ( self.new_user_input == other.new_user_input and self.past_user_inputs == other.past_user_inputs and self.generated_responses == other.generated_responses ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False ): if self.new_user_input: if overwrite: logger.warning( f'User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten ' f'with: "{text}".' ) UpperCamelCase : Union[str, Any] = text else: logger.warning( f'User input added while unprocessed input was existing: "{self.new_user_input}" new input ' f'ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input' ) else: UpperCamelCase : str = text def a_ ( self ): if self.new_user_input: self.past_user_inputs.append(self.new_user_input ) UpperCamelCase : Optional[int] = None def a_ ( self , SCREAMING_SNAKE_CASE_ ): self.generated_responses.append(SCREAMING_SNAKE_CASE_ ) def a_ ( self ): for user_input, generated_response in zip(self.past_user_inputs , self.generated_responses ): yield True, user_input yield False, generated_response if self.new_user_input: yield True, self.new_user_input def __repr__( self ): UpperCamelCase : List[Any] = f'Conversation id: {self.uuid} \n' for is_user, text in self.iter_texts(): UpperCamelCase : Dict = """user""" if is_user else """bot""" output += f'{name} >> {text} \n' return output @add_end_docstrings( _UpperCAmelCase , R'\n min_length_for_response (`int`, *optional*, defaults to 32):\n The minimum length (in number of tokens) for a response.\n minimum_tokens (`int`, *optional*, defaults to 10):\n The minimum length of tokens to leave for a response.\n ' , ) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if self.tokenizer.pad_token_id is None: UpperCamelCase : str = self.tokenizer.eos_token def a_ ( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = {} UpperCamelCase : Optional[Any] = {} UpperCamelCase : Tuple = {} if min_length_for_response is not None: UpperCamelCase : Union[str, Any] = min_length_for_response if minimum_tokens is not None: UpperCamelCase : Tuple = minimum_tokens if "max_length" in generate_kwargs: UpperCamelCase : Optional[int] = generate_kwargs["""max_length"""] # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length) if clean_up_tokenization_spaces is not None: UpperCamelCase : Optional[Any] = clean_up_tokenization_spaces if generate_kwargs: forward_params.update(SCREAMING_SNAKE_CASE_ ) return preprocess_params, forward_params, postprocess_params def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = super().__call__(SCREAMING_SNAKE_CASE_ , num_workers=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) == 1: return outputs[0] return outputs def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=32 ): if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): raise ValueError("""ConversationalPipeline, expects Conversation as inputs""" ) if conversation.new_user_input is None: raise ValueError( f'Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. ' """Add user inputs with the conversation's `add_user_input` method""" ) if hasattr(self.tokenizer , """_build_conversation_input_ids""" ): UpperCamelCase : int = self.tokenizer._build_conversation_input_ids(SCREAMING_SNAKE_CASE_ ) else: # If the tokenizer cannot handle conversations, we default to only the old version UpperCamelCase : Dict = self._legacy_parse_and_tokenize(SCREAMING_SNAKE_CASE_ ) if self.framework == "pt": UpperCamelCase : List[str] = torch.LongTensor([input_ids] ) elif self.framework == "tf": UpperCamelCase : Any = tf.constant([input_ids] ) return {"input_ids": input_ids, "conversation": conversation} def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=10 , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = generate_kwargs.get("""max_length""" , self.model.config.max_length ) UpperCamelCase : Optional[Any] = model_inputs["""input_ids"""].shape[1] if max_length - minimum_tokens < n: logger.warning(f'Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})' ) UpperCamelCase : Any = max_length - minimum_tokens UpperCamelCase : Union[str, Any] = model_inputs["""input_ids"""][:, -trim:] if "attention_mask" in model_inputs: UpperCamelCase : str = model_inputs["""attention_mask"""][:, -trim:] UpperCamelCase : Union[str, Any] = model_inputs.pop("""conversation""" ) UpperCamelCase : int = max_length UpperCamelCase : int = self.model.generate(**SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if self.model.config.is_encoder_decoder: UpperCamelCase : List[str] = 1 else: UpperCamelCase : Optional[int] = n return {"output_ids": output_ids[:, start_position:], "conversation": conversation} def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=True ): UpperCamelCase : Dict = model_outputs["""output_ids"""] UpperCamelCase : Union[str, Any] = self.tokenizer.decode( output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase : Dict = model_outputs["""conversation"""] conversation.mark_processed() conversation.append_response(SCREAMING_SNAKE_CASE_ ) return conversation def a_ ( self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = self.tokenizer.eos_token_id UpperCamelCase : Union[str, Any] = [] for is_user, text in conversation.iter_texts(): if eos_token_id is not None: input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) + [eos_token_id] ) else: input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) ) if len(SCREAMING_SNAKE_CASE_ ) > self.tokenizer.model_max_length: UpperCamelCase : Optional[int] = input_ids[-self.tokenizer.model_max_length :] return input_ids
27
"""simple docstring""" def A_ ( snake_case_ : int ): '''simple docstring''' if number < 0: raise ValueError("""number must not be negative""" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
27
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) A : Dict = { "configuration_speech_to_text": ["SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Speech2TextConfig"], "processing_speech_to_text": ["Speech2TextProcessor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[int] = ["Speech2TextTokenizer"] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[int] = ["Speech2TextFeatureExtractor"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : str = [ "TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFSpeech2TextForConditionalGeneration", "TFSpeech2TextModel", "TFSpeech2TextPreTrainedModel", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[str] = [ "SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "Speech2TextForConditionalGeneration", "Speech2TextModel", "Speech2TextPreTrainedModel", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys A : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a__: Union[str, Any] = logging.get_logger(__name__) a__: Union[str, Any] = {'vocab_file': 'spiece.model'} a__: Tuple = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } a__: Any = { 'google/bigbird-roberta-base': 4_096, 'google/bigbird-roberta-large': 4_096, 'google/bigbird-base-trivia-itc': 4_096, } class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): __SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE = ['''input_ids''', '''attention_mask'''] __SCREAMING_SNAKE_CASE = [] def __init__( self,__lowerCamelCase,__lowerCamelCase="<unk>",__lowerCamelCase="<s>",__lowerCamelCase="</s>",__lowerCamelCase="<pad>",__lowerCamelCase="[SEP]",__lowerCamelCase="[MASK]",__lowerCamelCase="[CLS]",__lowerCamelCase = None,**__lowerCamelCase,): A__ = AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else bos_token A__ = AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else eos_token A__ = AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else unk_token A__ = AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else pad_token A__ = AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else cls_token A__ = AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else sep_token # Mask token behave like a normal word, i.e. include the space before it A__ = AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else mask_token A__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__lowerCamelCase,eos_token=__lowerCamelCase,unk_token=__lowerCamelCase,pad_token=__lowerCamelCase,sep_token=__lowerCamelCase,mask_token=__lowerCamelCase,cls_token=__lowerCamelCase,sp_model_kwargs=self.sp_model_kwargs,**__lowerCamelCase,) A__ = vocab_file A__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__lowerCamelCase ) @property def UpperCamelCase ( self ): return self.sp_model.get_piece_size() def UpperCamelCase ( self ): A__ = {self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): A__ = self.__dict__.copy() A__ = None return state def __setstate__( self,__lowerCamelCase ): A__ = d # for backward compatibility if not hasattr(self,'''sp_model_kwargs''' ): A__ = {} A__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase ( self,__lowerCamelCase ): return self.sp_model.encode(__lowerCamelCase,out_type=__lowerCamelCase ) def UpperCamelCase ( self,__lowerCamelCase ): return self.sp_model.piece_to_id(__lowerCamelCase ) def UpperCamelCase ( self,__lowerCamelCase ): A__ = self.sp_model.IdToPiece(__lowerCamelCase ) return token def UpperCamelCase ( self,__lowerCamelCase ): A__ = [] A__ = '''''' A__ = 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(__lowerCamelCase ) + token A__ = True A__ = [] else: current_sub_tokens.append(__lowerCamelCase ) A__ = False out_string += self.sp_model.decode(__lowerCamelCase ) return out_string.strip() def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = False,__lowerCamelCase = None,__lowerCamelCase = True,**__lowerCamelCase,): A__ = kwargs.pop('''use_source_tokenizer''',__lowerCamelCase ) A__ = self.convert_ids_to_tokens(__lowerCamelCase,skip_special_tokens=__lowerCamelCase ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 A__ = [] A__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(__lowerCamelCase ) ) A__ = [] sub_texts.append(__lowerCamelCase ) else: current_sub_text.append(__lowerCamelCase ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(__lowerCamelCase ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: A__ = re.sub(r''' (\[(MASK|SEP)\])''',r'''\1''',''' '''.join(__lowerCamelCase ) ) else: A__ = ''''''.join(__lowerCamelCase ) A__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: A__ = self.clean_up_tokenization(__lowerCamelCase ) return clean_text else: return text def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = None ): if not os.path.isdir(__lowerCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return A__ = 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: A__ = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase ) return (out_vocab_file,) def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A__ = [self.cls_token_id] A__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = None,__lowerCamelCase = 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] + ([0] * len(__lowerCamelCase )) + [1] def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = None ): A__ = [self.sep_token_id] A__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
193
0
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
353
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class __UpperCAmelCase : '''simple docstring''' def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=[0, 1, 2, 3] , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=[1, 384, 24, 24] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , ) -> Tuple: A_ = parent A_ = batch_size A_ = image_size A_ = patch_size A_ = num_channels A_ = is_training A_ = use_labels A_ = hidden_size A_ = num_hidden_layers A_ = backbone_out_indices A_ = num_attention_heads A_ = intermediate_size A_ = hidden_act A_ = hidden_dropout_prob A_ = attention_probs_dropout_prob A_ = initializer_range A_ = num_labels A_ = backbone_featmap_shape A_ = scope A_ = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) A_ = (image_size // patch_size) ** 2 A_ = num_patches + 1 def __A ( self ) -> Optional[Any]: A_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A_ = None if self.use_labels: A_ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) A_ = self.get_config() return config, pixel_values, labels def __A ( self ) -> Optional[Any]: A_ = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [96, 192, 384, 768], '''num_groups''': 2, } return DPTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=_SCREAMING_SNAKE_CASE , backbone_featmap_shape=self.backbone_featmap_shape , ) def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: A_ = DPTModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() A_ = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: A_ = self.num_labels A_ = DPTForDepthEstimation(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() A_ = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: A_ = self.num_labels A_ = DPTForSemanticSegmentation(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() A_ = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __A ( self ) -> Optional[int]: A_ = self.prepare_config_and_inputs() A_ ,A_ ,A_ = config_and_inputs A_ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __UpperCAmelCase ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' __lowercase : Optional[int] = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () __lowercase : Optional[int] = ( { 'depth-estimation': DPTForDepthEstimation, 'feature-extraction': DPTModel, 'image-segmentation': DPTForSemanticSegmentation, } if is_torch_available() else {} ) __lowercase : Any = False __lowercase : Tuple = False __lowercase : List[Any] = False def __A ( self ) -> Tuple: A_ = DPTModelTester(self ) A_ = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __A ( self ) -> Dict: self.config_tester.run_common_tests() @unittest.skip(reason='''DPT does not use inputs_embeds''' ) def __A ( self ) -> Union[str, Any]: pass def __A ( self ) -> Dict: A_ ,A_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ = model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) A_ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def __A ( self ) -> Optional[int]: A_ ,A_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ = model_class(_SCREAMING_SNAKE_CASE ) A_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A_ = [*signature.parameters.keys()] A_ = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def __A ( self ) -> str: A_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def __A ( self ) -> str: A_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*_SCREAMING_SNAKE_CASE ) def __A ( self ) -> Optional[Any]: A_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_SNAKE_CASE ) def __A ( self ) -> Any: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue A_ ,A_ = self.model_tester.prepare_config_and_inputs_for_common() A_ = True if model_class in get_values(_SCREAMING_SNAKE_CASE ): continue A_ = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.train() A_ = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) A_ = model(**_SCREAMING_SNAKE_CASE ).loss loss.backward() def __A ( self ) -> Any: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue A_ ,A_ = self.model_tester.prepare_config_and_inputs_for_common() A_ = False A_ = True if model_class in get_values(_SCREAMING_SNAKE_CASE ) or not model_class.supports_gradient_checkpointing: continue A_ = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.gradient_checkpointing_enable() model.train() A_ = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) A_ = model(**_SCREAMING_SNAKE_CASE ).loss loss.backward() def __A ( self ) -> Tuple: A_ ,A_ = self.model_tester.prepare_config_and_inputs_for_common() A_ = _config_zero_init(_SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: A_ = model_class(config=_SCREAMING_SNAKE_CASE ) # Skip the check for the backbone A_ = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": A_ = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __A ( self ) -> int: pass @slow def __A ( self ) -> Dict: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: A_ = DPTModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def __A ( self ) -> Optional[int]: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type A_ ,A_ = self.model_tester.prepare_config_and_inputs_for_common() A_ = '''add''' with self.assertRaises(_SCREAMING_SNAKE_CASE ): A_ = DPTForDepthEstimation(_SCREAMING_SNAKE_CASE ) def _UpperCAmelCase ( ) -> Optional[int]: A_ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision @slow class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __A ( self ) -> Any: A_ = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' ) A_ = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(_SCREAMING_SNAKE_CASE ) A_ = prepare_img() A_ = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).to(_SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): A_ = model(**_SCREAMING_SNAKE_CASE ) A_ = outputs.predicted_depth # verify the predicted depth A_ = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , _SCREAMING_SNAKE_CASE ) A_ = torch.tensor( [[[5.6_437, 5.6_146, 5.6_511], [5.4_371, 5.5_649, 5.5_958], [5.5_215, 5.5_184, 5.5_293]]] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , _SCREAMING_SNAKE_CASE , atol=1E-4 ) )
18
0
import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): a_ = yaml.safe_load( '\\nname: ""\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: "Dataset Card for X" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: "Table of Contents"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Dataset Description"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: "Dataset Summary"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Supported Tasks and Leaderboards"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n' ) a_ = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Extra Ignored Subsection', 'text': '', 'is_empty_text': True, 'subsections': [], } ], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } a_ = '\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = ( 'The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.' ) a_ = '\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = ( 'The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.' ) a_ = '\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.' a_ = '' a_ = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = 'The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.' @pytest.mark.parametrize( "readme_md, expected_dict" , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def lowerCamelCase__ ( _a , _a): assert ReadMe.from_string(_a , _a).to_dict() == expected_dict @pytest.mark.parametrize( "readme_md, expected_error" , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def lowerCamelCase__ ( _a , _a): with pytest.raises(_a , match=re.escape(expected_error.format(path="root"))): SCREAMING_SNAKE_CASE : str = ReadMe.from_string(_a , _a) readme.validate() @pytest.mark.parametrize( "readme_md, expected_error" , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase__ ( _a , _a): with pytest.raises(_a , match=re.escape(expected_error.format(path="root"))): ReadMe.from_string(_a , _a) @pytest.mark.parametrize( "readme_md," , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase__ ( _a): ReadMe.from_string(_a , _a , suppress_parsing_errors=_a) @pytest.mark.parametrize( "readme_md, expected_dict" , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def lowerCamelCase__ ( _a , _a): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : Optional[int] = Path(_a) / "README.md" with open(_a , "w+") as readme_file: readme_file.write(_a) SCREAMING_SNAKE_CASE : Optional[Any] = ReadMe.from_readme(_a , _a).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( "readme_md, expected_error" , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def lowerCamelCase__ ( _a , _a): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : List[str] = Path(_a) / "README.md" with open(_a , "w+") as readme_file: readme_file.write(_a) SCREAMING_SNAKE_CASE : Optional[Any] = expected_error.format(path=_a) with pytest.raises(_a , match=re.escape(_a)): SCREAMING_SNAKE_CASE : Optional[int] = ReadMe.from_readme(_a , _a) readme.validate() @pytest.mark.parametrize( "readme_md, expected_error" , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase__ ( _a , _a): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : Any = Path(_a) / "README.md" with open(_a , "w+") as readme_file: readme_file.write(_a) SCREAMING_SNAKE_CASE : Dict = expected_error.format(path=_a) with pytest.raises(_a , match=re.escape(_a)): ReadMe.from_readme(_a , _a) @pytest.mark.parametrize( "readme_md," , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase__ ( _a): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : int = Path(_a) / "README.md" with open(_a , "w+") as readme_file: readme_file.write(_a) ReadMe.from_readme(_a , _a , suppress_parsing_errors=_a)
76
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __snake_case = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece class lowercase__ ( _UpperCAmelCase , unittest.TestCase ): A__ : List[str] =XLMProphetNetTokenizer A__ : List[Any] =False A__ : Tuple =True def A_ ( self : str ): super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ = XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_ ) tokenizer.save_pretrained(self.tmpdirname ) def A_ ( self : Tuple ): SCREAMING_SNAKE_CASE__ = '[PAD]' SCREAMING_SNAKE_CASE__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_ ) , UpperCAmelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_ ) , UpperCAmelCase_ ) def A_ ( self : Tuple ): SCREAMING_SNAKE_CASE__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '[PAD]' ) self.assertEqual(vocab_keys[1] , '[CLS]' ) self.assertEqual(vocab_keys[-1] , 'j' ) self.assertEqual(len(UpperCAmelCase_ ) , 1012 ) def A_ ( self : List[Any] ): self.assertEqual(self.get_tokenizer().vocab_size , 1012 ) def A_ ( self : Optional[int] ): SCREAMING_SNAKE_CASE__ = XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize('This is a test' ) self.assertListEqual(UpperCAmelCase_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( UpperCAmelCase_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) self.assertListEqual( UpperCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(UpperCAmelCase_ ) self.assertListEqual( UpperCAmelCase_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '[UNK]', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '[UNK]', '.', ] , ) @cached_property def A_ ( self : Optional[Any] ): return XLMProphetNetTokenizer.from_pretrained('microsoft/xprophetnet-large-wiki100-cased' ) @slow def A_ ( self : Any ): SCREAMING_SNAKE_CASE__ = 'Hello World!' SCREAMING_SNAKE_CASE__ = [35389, 6672, 49, 2] self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_ ) ) @slow def A_ ( self : Tuple ): # fmt: off SCREAMING_SNAKE_CASE__ = {'input_ids': [[11073, 82783, 18, 26, 82783, 549, 51540, 248, 17209, 1301, 217, 20, 215186, 1325, 147, 17209, 1301, 217, 20, 56370, 53, 122020, 20, 16477, 27, 87355, 4548, 20, 4728, 78392, 17, 159969, 18, 26, 24491, 629, 15, 538, 22704, 5439, 15, 2788, 24491, 9885, 15, 43534, 605, 15, 814, 18403, 33200, 29, 15, 43534, 24458, 12410, 111, 24966, 83669, 9637, 144068, 26, 850, 22346, 27, 147, 24966, 83669, 83490, 26, 39113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 122020, 115785, 34, 816, 1339, 46887, 18, 147, 53905, 1951, 42238, 41170, 17732, 834, 436, 15, 27523, 98733, 217, 147, 5542, 4981, 930, 17347, 16, 2], [20091, 629, 94, 82786, 58, 490, 20, 1528, 84, 53905, 344, 80592, 110128, 18822, 5267, 1306, 62, 152537, 308, 7997, 401, 124427, 549, 35442, 225, 109, 15055, 25748, 147, 7119, 43712, 34, 767, 135366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63784, 119466, 17, 147808, 88214, 18, 656, 81, 32, 3296, 10280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ , model_name='microsoft/xprophetnet-large-wiki100-cased' , revision='1acad1643ddd54a44df6a1b797ada8373685d90e' , )
176
0
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 AutoFeatureExtractor, WavaVecaFeatureExtractor 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_feature_extraction import CustomFeatureExtractor # noqa E402 __A = get_tests_dir('''fixtures''') class lowercase ( unittest.TestCase): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: UpperCAmelCase_= mock.Mock() UpperCAmelCase_= 500 UpperCAmelCase_= {} UpperCAmelCase_= HTTPError UpperCAmelCase_= {} # Download this model to make sure it's in the cache. UpperCAmelCase_= WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2""" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("""requests.Session.request""" , return_value=lowerCamelCase_ ) as mock_head: UpperCAmelCase_= WavaVecaFeatureExtractor.from_pretrained("""hf-internal-testing/tiny-random-wav2vec2""" ) # This check we did call the fake head request mock_head.assert_called() def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: UpperCAmelCase_= WavaVecaFeatureExtractor.from_pretrained( """https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json""" ) @is_staging_test class lowercase ( unittest.TestCase): """simple docstring""" @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ) -> str: UpperCAmelCase_= TOKEN HfFolder.save_token(lowerCamelCase_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int ) -> List[str]: try: delete_repo(token=cls._token , repo_id="""test-feature-extractor""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-feature-extractor-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-feature-extractor""" ) except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: UpperCAmelCase_= WavaVecaFeatureExtractor.from_pretrained(lowerCamelCase_ ) feature_extractor.push_to_hub("""test-feature-extractor""" , use_auth_token=self._token ) UpperCAmelCase_= WavaVecaFeatureExtractor.from_pretrained(F"""{USER}/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_ ) ) # Reset repo delete_repo(token=self._token , repo_id="""test-feature-extractor""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( lowerCamelCase_ , repo_id="""test-feature-extractor""" , push_to_hub=lowerCamelCase_ , use_auth_token=self._token ) UpperCAmelCase_= WavaVecaFeatureExtractor.from_pretrained(F"""{USER}/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_ ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: UpperCAmelCase_= WavaVecaFeatureExtractor.from_pretrained(lowerCamelCase_ ) feature_extractor.push_to_hub("""valid_org/test-feature-extractor""" , use_auth_token=self._token ) UpperCAmelCase_= WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_ ) ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-feature-extractor""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( lowerCamelCase_ , repo_id="""valid_org/test-feature-extractor-org""" , push_to_hub=lowerCamelCase_ , use_auth_token=self._token ) UpperCAmelCase_= WavaVecaFeatureExtractor.from_pretrained("""valid_org/test-feature-extractor-org""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(lowerCamelCase_ , getattr(lowerCamelCase_ , lowerCamelCase_ ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: CustomFeatureExtractor.register_for_auto_class() UpperCAmelCase_= CustomFeatureExtractor.from_pretrained(lowerCamelCase_ ) feature_extractor.push_to_hub("""test-dynamic-feature-extractor""" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {"""AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor"""} , ) UpperCAmelCase_= AutoFeatureExtractor.from_pretrained( F"""{USER}/test-dynamic-feature-extractor""" , trust_remote_code=lowerCamelCase_ ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , """CustomFeatureExtractor""" )
355
from __future__ import annotations def __a ( lowerCAmelCase_ : list[int] ,lowerCAmelCase_ : int ) -> list[list[int]]: '''simple docstring''' UpperCAmelCase_= [] UpperCAmelCase_= [] UpperCAmelCase_= 0 UpperCAmelCase_= sum(lowerCAmelCase_ ) create_state_space_tree(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ) return result def __a ( lowerCAmelCase_ : list[int] ,lowerCAmelCase_ : int ,lowerCAmelCase_ : int ,lowerCAmelCase_ : list[int] ,lowerCAmelCase_ : list[list[int]] ,lowerCAmelCase_ : int ,) -> None: '''simple docstring''' if sum(lowerCAmelCase_ ) > max_sum or (remaining_nums_sum + sum(lowerCAmelCase_ )) < max_sum: return if sum(lowerCAmelCase_ ) == max_sum: result.append(lowerCAmelCase_ ) return for index in range(lowerCAmelCase_ ,len(lowerCAmelCase_ ) ): create_state_space_tree( lowerCAmelCase_ ,lowerCAmelCase_ ,index + 1 ,[*path, nums[index]] ,lowerCAmelCase_ ,remaining_nums_sum - nums[index] ,) __A = [3, 34, 4, 12, 5, 2] __A = 9 __A = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
277
0
'''simple docstring''' import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class snake_case__ ( UpperCamelCase): def __get__( self : int , _A : int , _A : Dict=None ) -> Optional[int]: # See docs.python.org/3/howto/descriptor.html#properties if obj is None: return self if self.fget is None: raise AttributeError('''unreadable attribute''' ) UpperCAmelCase_ : Optional[Any] = '''__cached_''' + self.fget.__name__ UpperCAmelCase_ : Dict = getattr(_A , _A , _A ) if cached is None: UpperCAmelCase_ : Optional[Any] = self.fget(_A ) setattr(_A , _A , _A ) return cached def __UpperCAmelCase ( A : str ) -> Tuple: UpperCAmelCase_ : Any = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(F"invalid truth value {val!r}" ) def __UpperCAmelCase ( A : List[Any] ) -> Union[str, Any]: if is_torch_fx_proxy(A ): return True if is_torch_available(): import torch if isinstance(A , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(A , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(A , (jnp.ndarray, Tracer) ): return True return isinstance(A , np.ndarray ) def __UpperCAmelCase ( A : Union[str, Any] ) -> str: return isinstance(A , np.ndarray ) def __UpperCAmelCase ( A : Dict ) -> int: return _is_numpy(A ) def __UpperCAmelCase ( A : str ) -> Optional[Any]: import torch return isinstance(A , torch.Tensor ) def __UpperCAmelCase ( A : Tuple ) -> Tuple: return False if not is_torch_available() else _is_torch(A ) def __UpperCAmelCase ( A : List[Any] ) -> Union[str, Any]: import torch return isinstance(A , torch.device ) def __UpperCAmelCase ( A : Any ) -> Dict: return False if not is_torch_available() else _is_torch_device(A ) def __UpperCAmelCase ( A : Union[str, Any] ) -> List[Any]: import torch if isinstance(A , A ): if hasattr(A , A ): UpperCAmelCase_ : Optional[Any] = getattr(A , A ) else: return False return isinstance(A , torch.dtype ) def __UpperCAmelCase ( A : List[Any] ) -> Optional[int]: return False if not is_torch_available() else _is_torch_dtype(A ) def __UpperCAmelCase ( A : int ) -> Tuple: import tensorflow as tf return isinstance(A , tf.Tensor ) def __UpperCAmelCase ( A : Dict ) -> Optional[Any]: return False if not is_tf_available() else _is_tensorflow(A ) def __UpperCAmelCase ( A : int ) -> Optional[Any]: import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(A , '''is_symbolic_tensor''' ): return tf.is_symbolic_tensor(A ) return type(A ) == tf.Tensor def __UpperCAmelCase ( A : Optional[int] ) -> Dict: return False if not is_tf_available() else _is_tf_symbolic_tensor(A ) def __UpperCAmelCase ( A : Dict ) -> Optional[Any]: import jax.numpy as jnp # noqa: F811 return isinstance(A , jnp.ndarray ) def __UpperCAmelCase ( A : Dict ) -> Optional[int]: return False if not is_flax_available() else _is_jax(A ) def __UpperCAmelCase ( A : Optional[int] ) -> List[str]: if isinstance(A , (dict, UserDict) ): return {k: to_py_obj(A ) for k, v in obj.items()} elif isinstance(A , (list, tuple) ): return [to_py_obj(A ) for o in obj] elif is_tf_tensor(A ): return obj.numpy().tolist() elif is_torch_tensor(A ): return obj.detach().cpu().tolist() elif is_jax_tensor(A ): return np.asarray(A ).tolist() elif isinstance(A , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def __UpperCAmelCase ( A : Optional[int] ) -> Dict: if isinstance(A , (dict, UserDict) ): return {k: to_numpy(A ) for k, v in obj.items()} elif isinstance(A , (list, tuple) ): return np.array(A ) elif is_tf_tensor(A ): return obj.numpy() elif is_torch_tensor(A ): return obj.detach().cpu().numpy() elif is_jax_tensor(A ): return np.asarray(A ) else: return obj class snake_case__ ( UpperCamelCase): def A ( self : Dict ) -> Optional[int]: UpperCAmelCase_ : Union[str, Any] = fields(self ) # Safety and consistency checks if not len(_A ): raise ValueError(F"{self.__class__.__name__} has no fields." ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(F"{self.__class__.__name__} should not have more than one required field." ) UpperCAmelCase_ : Tuple = getattr(self , class_fields[0].name ) UpperCAmelCase_ : int = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(_A ): if isinstance(_A , _A ): UpperCAmelCase_ : Optional[Any] = first_field.items() UpperCAmelCase_ : Union[str, Any] = True else: try: UpperCAmelCase_ : Optional[Any] = iter(_A ) UpperCAmelCase_ : Dict = True except TypeError: UpperCAmelCase_ : Optional[int] = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(_A ): if ( not isinstance(_A , (list, tuple) ) or not len(_A ) == 2 or not isinstance(element[0] , _A ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute UpperCAmelCase_ : List[Any] = first_field else: # If we have a mixed iterator, raise an error raise ValueError( F"Cannot set key/value for {element}. It needs to be a tuple (key, value)." ) break setattr(self , element[0] , element[1] ) if element[1] is not None: UpperCAmelCase_ : Union[str, Any] = element[1] elif first_field is not None: UpperCAmelCase_ : Any = first_field else: for field in class_fields: UpperCAmelCase_ : Dict = getattr(self , field.name ) if v is not None: UpperCAmelCase_ : Any = v def __delitem__( self : List[Any] , *_A : Tuple , **_A : int ) -> Union[str, Any]: raise Exception(F"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance." ) def A ( self : str , *_A : Dict , **_A : Dict ) -> str: raise Exception(F"You cannot use ``setdefault`` on a {self.__class__.__name__} instance." ) def A ( self : List[Any] , *_A : Any , **_A : List[str] ) -> List[str]: raise Exception(F"You cannot use ``pop`` on a {self.__class__.__name__} instance." ) def A ( self : Dict , *_A : List[Any] , **_A : List[str] ) -> Optional[int]: raise Exception(F"You cannot use ``update`` on a {self.__class__.__name__} instance." ) def __getitem__( self : Optional[Any] , _A : str ) -> Optional[Any]: if isinstance(_A , _A ): UpperCAmelCase_ : List[str] = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self : Tuple , _A : List[str] , _A : str ) -> Optional[Any]: if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(_A , _A ) super().__setattr__(_A , _A ) def __setitem__( self : Tuple , _A : Tuple , _A : Optional[int] ) -> List[str]: # Will raise a KeyException if needed super().__setitem__(_A , _A ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(_A , _A ) def A ( self : Dict ) -> Tuple[Any]: return tuple(self[k] for k in self.keys() ) class snake_case__ ( UpperCamelCase , UpperCamelCase): @classmethod def A ( cls : List[str] , _A : int ) -> str: raise ValueError( F"{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}" ) class snake_case__ ( UpperCamelCase): a_ = "longest" a_ = "max_length" a_ = "do_not_pad" class snake_case__ ( UpperCamelCase): a_ = "pt" a_ = "tf" a_ = "np" a_ = "jax" class snake_case__ : def __init__( self : List[Any] , _A : List[ContextManager] ) -> Any: UpperCAmelCase_ : Tuple = context_managers UpperCAmelCase_ : str = ExitStack() def __enter__( self : str ) -> Union[str, Any]: for context_manager in self.context_managers: self.stack.enter_context(_A ) def __exit__( self : Optional[int] , *_A : Tuple , **_A : Optional[Any] ) -> Optional[Any]: self.stack.__exit__(*_A , **_A ) def __UpperCAmelCase ( A : int ) -> Optional[int]: UpperCAmelCase_ : List[str] = infer_framework(A ) if framework == "tf": UpperCAmelCase_ : List[Any] = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": UpperCAmelCase_ : List[str] = inspect.signature(model_class.forward ) # PyTorch models else: UpperCAmelCase_ : Optional[Any] = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def __UpperCAmelCase ( A : List[str] ) -> Optional[Any]: UpperCAmelCase_ : Optional[Any] = model_class.__name__ UpperCAmelCase_ : Tuple = infer_framework(A ) if framework == "tf": UpperCAmelCase_ : Tuple = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": UpperCAmelCase_ : str = inspect.signature(model_class.forward ) # PyTorch models else: UpperCAmelCase_ : List[str] = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def __UpperCAmelCase ( A : MutableMapping , A : str = "" , A : str = "." ) -> List[Any]: def _flatten_dict(A : Optional[int] , A : Optional[Any]="" , A : str="." ): for k, v in d.items(): UpperCAmelCase_ : List[str] = str(A ) + delimiter + str(A ) if parent_key else k if v and isinstance(A , A ): yield from flatten_dict(A , A , delimiter=A ).items() else: yield key, v return dict(_flatten_dict(A , A , A ) ) @contextmanager def __UpperCAmelCase ( A : Optional[int] , A : bool = False ) -> List[Any]: if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def __UpperCAmelCase ( A : Tuple , A : Optional[int]=None ) -> Optional[Any]: if is_numpy_array(A ): return np.transpose(A , axes=A ) elif is_torch_tensor(A ): return array.T if axes is None else array.permute(*A ) elif is_tf_tensor(A ): import tensorflow as tf return tf.transpose(A , perm=A ) elif is_jax_tensor(A ): return jnp.transpose(A , axes=A ) else: raise ValueError(F"Type not supported for transpose: {type(A )}." ) def __UpperCAmelCase ( A : Tuple , A : Optional[int] ) -> Any: if is_numpy_array(A ): return np.reshape(A , A ) elif is_torch_tensor(A ): return array.reshape(*A ) elif is_tf_tensor(A ): import tensorflow as tf return tf.reshape(A , A ) elif is_jax_tensor(A ): return jnp.reshape(A , A ) else: raise ValueError(F"Type not supported for reshape: {type(A )}." ) def __UpperCAmelCase ( A : Any , A : Tuple=None ) -> Any: if is_numpy_array(A ): return np.squeeze(A , axis=A ) elif is_torch_tensor(A ): return array.squeeze() if axis is None else array.squeeze(dim=A ) elif is_tf_tensor(A ): import tensorflow as tf return tf.squeeze(A , axis=A ) elif is_jax_tensor(A ): return jnp.squeeze(A , axis=A ) else: raise ValueError(F"Type not supported for squeeze: {type(A )}." ) def __UpperCAmelCase ( A : str , A : Tuple ) -> List[str]: if is_numpy_array(A ): return np.expand_dims(A , A ) elif is_torch_tensor(A ): return array.unsqueeze(dim=A ) elif is_tf_tensor(A ): import tensorflow as tf return tf.expand_dims(A , axis=A ) elif is_jax_tensor(A ): return jnp.expand_dims(A , axis=A ) else: raise ValueError(F"Type not supported for expand_dims: {type(A )}." ) def __UpperCAmelCase ( A : Optional[int] ) -> List[str]: if is_numpy_array(A ): return np.size(A ) elif is_torch_tensor(A ): return array.numel() elif is_tf_tensor(A ): import tensorflow as tf return tf.size(A ) elif is_jax_tensor(A ): return array.size else: raise ValueError(F"Type not supported for expand_dims: {type(A )}." ) def __UpperCAmelCase ( A : Union[str, Any] , A : Union[str, Any] ) -> Optional[int]: for key, value in auto_map.items(): if isinstance(A , (tuple, list) ): UpperCAmelCase_ : Dict = [F"{repo_id}--{v}" if (v is not None and '''--''' not in v) else v for v in value] elif value is not None and "--" not in value: UpperCAmelCase_ : Dict = F"{repo_id}--{value}" return auto_map def __UpperCAmelCase ( A : Any ) -> Optional[Any]: for base_class in inspect.getmro(A ): UpperCAmelCase_ : int = base_class.__module__ UpperCAmelCase_ : Optional[int] = base_class.__name__ if module.startswith('''tensorflow''' ) or module.startswith('''keras''' ) or name == "TFPreTrainedModel": return "tf" elif module.startswith('''torch''' ) or name == "PreTrainedModel": return "pt" elif module.startswith('''flax''' ) or module.startswith('''jax''' ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(F"Could not infer framework from class {model_class}." )
304
'''simple docstring''' from __future__ import annotations import math def __UpperCAmelCase ( A : int , A : int , A : bool , A : list[int] , A : float ) -> int: if depth < 0: raise ValueError('''Depth cannot be less than 0''' ) if not scores: raise ValueError('''Scores cannot be empty''' ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , A , A , A ) , minimax(depth + 1 , node_index * 2 + 1 , A , A , A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , A , A , A ) , minimax(depth + 1 , node_index * 2 + 1 , A , A , A ) , ) ) def __UpperCAmelCase ( ) -> None: UpperCAmelCase_ : List[str] = [9_0, 2_3, 6, 3_3, 2_1, 6_5, 1_2_3, 3_4_4_2_3] UpperCAmelCase_ : List[Any] = math.log(len(A ) , 2 ) print(F"Optimal value : {minimax(0 , 0 , A , A , A )}" ) if __name__ == "__main__": import doctest doctest.testmod() main()
304
1
'''simple docstring''' import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort _lowerCamelCase : str = logging.get_logger(__name__) _lowerCamelCase : int = { 'tensor(bool)': np.bool_, 'tensor(int8)': np.inta, 'tensor(uint8)': np.uinta, 'tensor(int16)': np.intaa, 'tensor(uint16)': np.uintaa, 'tensor(int32)': np.intaa, 'tensor(uint32)': np.uintaa, 'tensor(int64)': np.intaa, 'tensor(uint64)': np.uintaa, 'tensor(float16)': np.floataa, 'tensor(float)': np.floataa, 'tensor(double)': np.floataa, } class __UpperCAmelCase : '''simple docstring''' def __init__(self : str , _lowerCAmelCase : List[str]=None , **_lowerCAmelCase : Optional[Any] ) -> List[str]: logger.info("""`diffusers.OnnxRuntimeModel` is experimental and might change in the future.""" ) A = model A = kwargs.get("""model_save_dir""" , _lowerCAmelCase ) A = kwargs.get("""latest_model_name""" , _lowerCAmelCase ) def __call__(self : List[Any] , **_lowerCAmelCase : str ) -> str: A = {k: np.array(_lowerCAmelCase ) for k, v in kwargs.items()} return self.model.run(_lowerCAmelCase , _lowerCAmelCase ) @staticmethod def A (_lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : int=None , _lowerCAmelCase : int=None ) -> Union[str, Any]: if provider is None: logger.info("""No onnxruntime provider specified, using CPUExecutionProvider""" ) A = """CPUExecutionProvider""" return ort.InferenceSession(_lowerCAmelCase , providers=[provider] , sess_options=_lowerCAmelCase ) def A (self : str , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : Optional[str] = None , **_lowerCAmelCase : Dict ) -> Dict: A = file_name if file_name is not None else ONNX_WEIGHTS_NAME A = self.model_save_dir.joinpath(self.latest_model_name ) A = Path(_lowerCAmelCase ).joinpath(_lowerCAmelCase ) try: shutil.copyfile(_lowerCAmelCase , _lowerCAmelCase ) except shutil.SameFileError: pass # copy external weights (for models >2GB) A = self.model_save_dir.joinpath(_lowerCAmelCase ) if src_path.exists(): A = Path(_lowerCAmelCase ).joinpath(_lowerCAmelCase ) try: shutil.copyfile(_lowerCAmelCase , _lowerCAmelCase ) except shutil.SameFileError: pass def A (self : Optional[int] , _lowerCAmelCase : Union[str, os.PathLike] , **_lowerCAmelCase : Any , ) -> Optional[int]: if os.path.isfile(_lowerCAmelCase ): logger.error(F"""Provided path ({save_directory}) should be a directory, not a file""" ) return os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase ) # saving model weights/files self._save_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) @classmethod def A (cls : str , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : Optional[Union[bool, str, None]] = None , _lowerCAmelCase : Optional[Union[str, None]] = None , _lowerCAmelCase : bool = False , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional["ort.SessionOptions"] = None , **_lowerCAmelCase : Optional[Any] , ) -> Optional[Any]: A = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(_lowerCAmelCase ): A = OnnxRuntimeModel.load_model( os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , provider=_lowerCAmelCase , sess_options=_lowerCAmelCase ) A = Path(_lowerCAmelCase ) # load model from hub else: # download model A = hf_hub_download( repo_id=_lowerCAmelCase , filename=_lowerCAmelCase , use_auth_token=_lowerCAmelCase , revision=_lowerCAmelCase , cache_dir=_lowerCAmelCase , force_download=_lowerCAmelCase , ) A = Path(_lowerCAmelCase ).parent A = Path(_lowerCAmelCase ).name A = OnnxRuntimeModel.load_model(_lowerCAmelCase , provider=_lowerCAmelCase , sess_options=_lowerCAmelCase ) return cls(model=_lowerCAmelCase , **_lowerCAmelCase ) @classmethod def A (cls : Tuple , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : bool = True , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , **_lowerCAmelCase : Optional[int] , ) -> str: A = None if len(str(_lowerCAmelCase ).split("""@""" ) ) == 2: A , A = model_id.split("""@""" ) return cls._from_pretrained( model_id=_lowerCAmelCase , revision=_lowerCAmelCase , cache_dir=_lowerCAmelCase , force_download=_lowerCAmelCase , use_auth_token=_lowerCAmelCase , **_lowerCAmelCase , )
361
'''simple docstring''' from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES _lowerCamelCase : List[str] = logging.get_logger(__name__) _lowerCamelCase : Any = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) _lowerCamelCase : Optional[Any] = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) _lowerCamelCase : int = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) _lowerCamelCase : List[str] = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) _lowerCamelCase : int = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) _lowerCamelCase : int = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) _lowerCamelCase : Optional[int] = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) _lowerCamelCase : Optional[Any] = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) _lowerCamelCase : Any = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) _lowerCamelCase : Union[str, Any] = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) _lowerCamelCase : Dict = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) _lowerCamelCase : int = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) _lowerCamelCase : Union[str, Any] = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) _lowerCamelCase : Any = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) _lowerCamelCase : List[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) _lowerCamelCase : Dict = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) _lowerCamelCase : Tuple = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) _lowerCamelCase : Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) _lowerCamelCase : Union[str, Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) _lowerCamelCase : Optional[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) _lowerCamelCase : Optional[int] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) _lowerCamelCase : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) _lowerCamelCase : List[str] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) _lowerCamelCase : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) _lowerCamelCase : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) _lowerCamelCase : str = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) _lowerCamelCase : Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) _lowerCamelCase : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_MAPPING _lowerCamelCase : Optional[Any] = auto_class_update(FlaxAutoModel) class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING _lowerCamelCase : List[str] = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING _lowerCamelCase : List[Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING _lowerCamelCase : List[str] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowerCamelCase : Tuple = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _lowerCamelCase : Tuple = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING _lowerCamelCase : Any = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING _lowerCamelCase : str = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING _lowerCamelCase : Tuple = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING _lowerCamelCase : List[Any] = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING _lowerCamelCase : Union[str, Any] = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING _lowerCamelCase : Optional[int] = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class __UpperCAmelCase ( _BaseAutoModelClass ): '''simple docstring''' __lowerCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING _lowerCamelCase : Optional[int] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
337
0
"""simple docstring""" def lowercase ( a__ : Union[str, Any] ) -> Optional[Any]: _UpperCamelCase = len(a__ ) while cur > 1: # Find the maximum number in arr _UpperCamelCase = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi _UpperCamelCase = arr[mi::-1] + arr[mi + 1 : len(a__ )] # Reverse whole list _UpperCamelCase = arr[cur - 1 :: -1] + arr[cur : len(a__ )] cur -= 1 return arr if __name__ == "__main__": UpperCAmelCase = input("""Enter numbers separated by a comma:\n""").strip() UpperCAmelCase = [int(item) for item in user_input.split(""",""")] print(pancake_sort(unsorted))
256
"""simple docstring""" def lowercase ( a__ : Union[str, Any] ) -> Optional[Any]: _UpperCamelCase = len(a__ ) while cur > 1: # Find the maximum number in arr _UpperCamelCase = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi _UpperCamelCase = arr[mi::-1] + arr[mi + 1 : len(a__ )] # Reverse whole list _UpperCamelCase = arr[cur - 1 :: -1] + arr[cur : len(a__ )] cur -= 1 return arr if __name__ == "__main__": UpperCAmelCase = input("""Enter numbers separated by a comma:\n""").strip() UpperCAmelCase = [int(item) for item in user_input.split(""",""")] print(pancake_sort(unsorted))
256
1
"""simple docstring""" import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _UpperCamelCase ( lowerCAmelCase__ ,unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Any =KandinskyVaaPriorPipeline __UpperCAmelCase : Any =["""prompt"""] __UpperCAmelCase : Optional[Any] =["""prompt""", """negative_prompt"""] __UpperCAmelCase : List[str] =[ """num_images_per_prompt""", """generator""", """num_inference_steps""", """latents""", """negative_prompt""", """guidance_scale""", """output_type""", """return_dict""", ] __UpperCAmelCase : Optional[Any] =False @property def snake_case ( self ): return 32 @property def snake_case ( self ): return 32 @property def snake_case ( self ): return self.time_input_dim @property def snake_case ( self ): return self.time_input_dim * 4 @property def snake_case ( self ): return 1_00 @property def snake_case ( self ): __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def snake_case ( self ): torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModelWithProjection(__a ) @property def snake_case ( self ): torch.manual_seed(0 ) __lowerCAmelCase = { "num_attention_heads": 2, "attention_head_dim": 12, "embedding_dim": self.text_embedder_hidden_size, "num_layers": 1, } __lowerCAmelCase = PriorTransformer(**__a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __lowerCAmelCase = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def snake_case ( self ): torch.manual_seed(0 ) __lowerCAmelCase = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=2_24 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __lowerCAmelCase = CLIPVisionModelWithProjection(__a ) return model @property def snake_case ( self ): __lowerCAmelCase = CLIPImageProcessor( crop_size=2_24 , do_center_crop=__a , do_normalize=__a , do_resize=__a , image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , resample=3 , size=2_24 , ) return image_processor def snake_case ( self ): __lowerCAmelCase = self.dummy_prior __lowerCAmelCase = self.dummy_image_encoder __lowerCAmelCase = self.dummy_text_encoder __lowerCAmelCase = self.dummy_tokenizer __lowerCAmelCase = self.dummy_image_processor __lowerCAmelCase = UnCLIPScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=10_00 , clip_sample=__a , clip_sample_range=1_0.0 , ) __lowerCAmelCase = { "prior": prior, "image_encoder": image_encoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "scheduler": scheduler, "image_processor": image_processor, } return components def snake_case ( self , __a , __a=0 ): if str(__a ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(__a ) else: __lowerCAmelCase = torch.Generator(device=__a ).manual_seed(__a ) __lowerCAmelCase = { "prompt": "horse", "generator": generator, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def snake_case ( self ): __lowerCAmelCase = "cpu" __lowerCAmelCase = self.get_dummy_components() __lowerCAmelCase = self.pipeline_class(**__a ) __lowerCAmelCase = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __lowerCAmelCase = pipe(**self.get_dummy_inputs(__a ) ) __lowerCAmelCase = output.image_embeds __lowerCAmelCase = pipe( **self.get_dummy_inputs(__a ) , return_dict=__a , )[0] __lowerCAmelCase = image[0, -10:] __lowerCAmelCase = image_from_tuple[0, -10:] assert image.shape == (1, 32) __lowerCAmelCase = np.array( [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def snake_case ( self ): __lowerCAmelCase = torch_device == "cpu" __lowerCAmelCase = True __lowerCAmelCase = False self._test_inference_batch_single_identical( test_max_difference=__a , relax_max_difference=__a , test_mean_pixel_difference=__a , ) @skip_mps def snake_case ( self ): __lowerCAmelCase = torch_device == "cpu" __lowerCAmelCase = False self._test_attention_slicing_forward_pass( test_max_difference=__a , test_mean_pixel_difference=__a , )
259
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [[] for _ in range(_UpperCamelCase )] __lowerCAmelCase = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative" ) if key == 1 or len(_UpperCamelCase ) <= key: return input_string for position, character in enumerate(_UpperCamelCase ): __lowerCAmelCase = position % (lowest * 2) # puts it in bounds __lowerCAmelCase = min(_UpperCamelCase , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(_UpperCamelCase ) __lowerCAmelCase = ["".join(_UpperCamelCase ) for row in temp_grid] __lowerCAmelCase = "".join(_UpperCamelCase ) return output_string def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [] __lowerCAmelCase = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative" ) if key == 1: return input_string __lowerCAmelCase = [[] for _ in range(_UpperCamelCase )] # generates template for position in range(len(_UpperCamelCase ) ): __lowerCAmelCase = position % (lowest * 2) # puts it in bounds __lowerCAmelCase = min(_UpperCamelCase , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append("*" ) __lowerCAmelCase = 0 for row in temp_grid: # fills in the characters __lowerCAmelCase = input_string[counter : counter + len(_UpperCamelCase )] grid.append(list(_UpperCamelCase ) ) counter += len(_UpperCamelCase ) __lowerCAmelCase = "" # reads as zigzag for position in range(len(_UpperCamelCase ) ): __lowerCAmelCase = position % (lowest * 2) # puts it in bounds __lowerCAmelCase = min(_UpperCamelCase , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def _lowerCamelCase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = {} for key_guess in range(1 , len(_UpperCamelCase ) ): # tries every key __lowerCAmelCase = decrypt(_UpperCamelCase , _UpperCamelCase ) return results if __name__ == "__main__": import doctest doctest.testmod()
259
1
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowercase ( unittest.TestCase ): def a__ ( self ) -> Union[str, Any]: _A : List[str] = 0 def a__ ( self ) -> str: _A : Union[str, Any] = AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32""" ) self.assertIsInstance(_a , _a ) def a__ ( self ) -> str: with tempfile.TemporaryDirectory() as tmpdirname: _A : Dict = Path(_a ) / """preprocessor_config.json""" _A : Union[str, Any] = Path(_a ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) _A : Optional[Any] = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def a__ ( self ) -> Optional[Any]: # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: _A : List[str] = Path(_a ) / """preprocessor_config.json""" _A : str = Path(_a ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) _A : int = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def a__ ( self ) -> Dict: with tempfile.TemporaryDirectory() as tmpdirname: _A : List[Any] = CLIPConfig() # Create a dummy config file with image_proceesor_type _A : Tuple = Path(_a ) / """preprocessor_config.json""" _A : Any = Path(_a ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally _A : Optional[Any] = AutoImageProcessor.from_pretrained(_a ).to_dict() config_dict.pop("""image_processor_type""" ) _A : Any = CLIPImageProcessor(**_a ) # save in new folder model_config.save_pretrained(_a ) config.save_pretrained(_a ) _A : int = AutoImageProcessor.from_pretrained(_a ) # make sure private variable is not incorrectly saved _A : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(_a , _a ) def a__ ( self ) -> Optional[Any]: with tempfile.TemporaryDirectory() as tmpdirname: _A : Tuple = Path(_a ) / """preprocessor_config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) _A : List[str] = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def a__ ( self ) -> Tuple: with self.assertRaisesRegex( _a , """clip-base is not a local folder and is not a valid model identifier""" ): _A : Tuple = AutoImageProcessor.from_pretrained("""clip-base""" ) def a__ ( self ) -> Optional[Any]: with self.assertRaisesRegex( _a , R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): _A : List[Any] = AutoImageProcessor.from_pretrained(_a , revision="""aaaaaa""" ) def a__ ( self ) -> Optional[int]: with self.assertRaisesRegex( _a , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): _A : Optional[int] = AutoImageProcessor.from_pretrained("""hf-internal-testing/config-no-model""" ) def a__ ( self ) -> Optional[Any]: # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_a ): _A : str = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(_a ): _A : int = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) _A : Tuple = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_a ) _A : List[Any] = AutoImageProcessor.from_pretrained(_a , trust_remote_code=_a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , """NewImageProcessor""" ) def a__ ( self ) -> List[str]: try: AutoConfig.register("""custom""" , _a ) AutoImageProcessor.register(_a , _a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_a ): AutoImageProcessor.register(_a , _a ) with tempfile.TemporaryDirectory() as tmpdirname: _A : Dict = Path(_a ) / """preprocessor_config.json""" _A : Optional[Any] = Path(_a ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(_a , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(_a , """w""" ) ) _A : str = CustomImageProcessor.from_pretrained(_a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_a ) _A : List[Any] = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def a__ ( self ) -> Optional[int]: class lowercase ( UpperCamelCase__ ): _a = True try: AutoConfig.register("""custom""" , _a ) AutoImageProcessor.register(_a , _a ) # If remote code is not set, the default is to use local _A : List[str] = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. _A : Dict = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub _A : str = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(not hasattr(_a , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
26
import argparse import shutil import time from json import JSONDecodeError from logging import getLogger from pathlib import Path from typing import Dict, List import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import ( SeqaSeqDataset, calculate_bleu, calculate_rouge, chunks, lmap, load_json, parse_numeric_n_bool_cl_kwargs, save_json, use_task_specific_params, write_txt_file, ) _snake_case = getLogger(__name__) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_ = 8,snake_case_ = 1024,snake_case_="val",snake_case_=None,snake_case_=False,snake_case_="summarization",snake_case_=None,snake_case_=1,snake_case_ = None,snake_case_="",**snake_case_,): _A : Dict = str(snake_case_ ) assert local_rank is not None torch.distributed.init_process_group(backend="""nccl""",rank=snake_case_ ) _A : Tuple = Path(snake_case_ ) _A : List[Any] = save_dir.joinpath(f'''rank_{local_rank}_output.json''' ) torch.cuda.set_device(snake_case_ ) _A : Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(snake_case_ ).cuda() if fpaa: _A : Any = model.half() # determine if we need to increase num_beams use_task_specific_params(snake_case_,snake_case_ ) # update config with task specific params _A : str = generate_kwargs.pop("""num_beams""",model.config.num_beams ) # AttributeError risk? if num_return_sequences > num_beams: _A : int = num_return_sequences _A : Optional[Any] = AutoTokenizer.from_pretrained(snake_case_ ) logger.info(f'''Inferred tokenizer type: {tokenizer.__class__}''' ) # if this is wrong, check config.model_type. if max_source_length is None: _A : Optional[int] = tokenizer.model_max_length if prefix is None: _A : Tuple = prefix or getattr(model.config,"""prefix""","""""" ) or """""" _A : Optional[int] = SeqaSeqDataset( snake_case_,snake_case_,snake_case_,max_target_length=1024,type_path=snake_case_,n_obs=snake_case_,prefix=snake_case_,**snake_case_,) # I set shuffle=True for a more accurate progress bar. # If all the longest samples are first, the prog bar estimate is too high at the beginning. _A : Optional[int] = ds.make_sortish_sampler(snake_case_,distributed=snake_case_,add_extra_examples=snake_case_,shuffle=snake_case_ ) _A : Dict = DataLoader(snake_case_,sampler=snake_case_,batch_size=snake_case_,collate_fn=ds.collate_fn ) _A : Optional[Any] = [] for batch in tqdm(snake_case_ ): _A : Tuple = model.generate( input_ids=batch["""input_ids"""].to(model.device ),attention_mask=batch["""attention_mask"""].to(model.device ),num_return_sequences=snake_case_,num_beams=snake_case_,**snake_case_,) _A : Any = tokenizer.batch_decode(snake_case_,skip_special_tokens=snake_case_,clean_up_tokenization_spaces=snake_case_ ) _A : Dict = batch["""ids"""] if num_return_sequences > 1: _A : Any = chunks(snake_case_,snake_case_ ) # batch size chunks, each of size num_return_seq for i, pred in enumerate(snake_case_ ): results.append({"""pred""": pred, """id""": ids[i].item()} ) save_json(snake_case_,snake_case_ ) return results, sampler.num_replicas def lowerCAmelCase_ ( ): _A : Tuple = argparse.ArgumentParser( epilog="""Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate""" ) parser.add_argument("""--data_dir""",type=snake_case_,help="""like cnn_dm/test.source""" ) parser.add_argument( """--model_name""",type=snake_case_,help="""like facebook/bart-large-cnn,t5-base, etc.""",default="""sshleifer/distilbart-xsum-12-3""",) parser.add_argument("""--save_dir""",type=snake_case_,help="""where to save""",default="""tmp_gen""" ) parser.add_argument("""--max_source_length""",type=snake_case_,default=snake_case_ ) parser.add_argument( """--type_path""",type=snake_case_,default="""test""",help="""which subset to evaluate typically train/val/test""" ) parser.add_argument("""--task""",type=snake_case_,default="""summarization""",help="""used for task_specific_params + metrics""" ) parser.add_argument("""--bs""",type=snake_case_,default=8,required=snake_case_,help="""batch size""" ) parser.add_argument( """--local_rank""",type=snake_case_,default=-1,required=snake_case_,help="""should be passed by distributed.launch""" ) parser.add_argument( """--n_obs""",type=snake_case_,default=snake_case_,required=snake_case_,help="""How many observations. Defaults to all.""" ) parser.add_argument( """--num_return_sequences""",type=snake_case_,default=1,required=snake_case_,help="""How many sequences to return""" ) parser.add_argument( """--sync_timeout""",type=snake_case_,default=600,required=snake_case_,help="""How long should master process wait for other processes to finish.""",) parser.add_argument("""--src_lang""",type=snake_case_,default=snake_case_,required=snake_case_ ) parser.add_argument("""--tgt_lang""",type=snake_case_,default=snake_case_,required=snake_case_ ) parser.add_argument( """--prefix""",type=snake_case_,required=snake_case_,default=snake_case_,help="""will be added to the begininng of src examples""" ) parser.add_argument("""--fp16""",action="""store_true""" ) parser.add_argument("""--debug""",action="""store_true""" ) _A : Union[str, Any] = time.time() _A , _A : List[str] = parser.parse_known_args() _A : List[str] = parse_numeric_n_bool_cl_kwargs(snake_case_ ) if generate_kwargs and args.local_rank <= 0: print(f'''parsed the following generate kwargs: {generate_kwargs}''' ) _A : Dict = Path(args.save_dir + """_tmp""" ) Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) # this handles locking. _A : int = list(json_save_dir.glob("""rank_*.json""" ) ) if intermediate_files: raise ValueError(f'''Found files at {json_save_dir} please move or remove them.''' ) # In theory, a node could finish and save before another node hits this. If this happens, we can address later. _A : Any = {} if args.src_lang is not None: _A : int = args.src_lang if args.tgt_lang is not None: _A : Dict = args.tgt_lang Path(args.save_dir ).mkdir(exist_ok=snake_case_ ) _A , _A : str = eval_data_dir( args.data_dir,snake_case_,args.model_name,type_path=args.type_path,bs=args.bs,fpaa=args.fpaa,task=args.task,local_rank=args.local_rank,n_obs=args.n_obs,max_source_length=args.max_source_length,num_return_sequences=args.num_return_sequences,prefix=args.prefix,dataset_kwargs=snake_case_,**snake_case_,) if args.local_rank <= 0: _A : List[Any] = Path(args.save_dir ) save_dir.mkdir(exist_ok=snake_case_ ) _A : Tuple = gather_results_from_each_node(snake_case_,snake_case_,args.sync_timeout ) _A : Optional[int] = combine_partial_results(snake_case_ ) if args.num_return_sequences > 1: _A : Optional[Any] = save_dir.joinpath("""pseudolabel_results.json""" ) print(f'''Saving aggregated results at {save_path}, intermediate in {json_save_dir}/''' ) save_json(snake_case_,snake_case_ ) return _A : List[str] = Path(args.data_dir ).joinpath(args.type_path + """.target""" ) with open(snake_case_ ) as f: _A : int = [x.rstrip() for x in f.readlines()][: len(snake_case_ )] # Calculate metrics, save metrics, and save _generations.txt _A : Dict = """translation""" in args.task _A : Optional[Any] = calculate_bleu if calc_bleu else calculate_rouge _A : Tuple = """bleu""" if calc_bleu else """rouge""" _A : Dict = score_fn(snake_case_,snake_case_ ) _A : List[Any] = len(snake_case_ ) _A : Optional[int] = time.time() - start_time _A : Dict = round(runtime / metrics["""n_obs"""],4 ) _A : Dict = num_replicas # TODO(@stas00): add whatever metadata to metrics _A : Any = save_dir.joinpath(f'''{args.type_path}_{metric_name}.json''' ) save_json(snake_case_,snake_case_,indent=snake_case_ ) print(snake_case_ ) write_txt_file(snake_case_,save_dir.joinpath(f'''{args.type_path}_generations.txt''' ) ) if args.debug: write_txt_file(snake_case_,save_dir.joinpath(f'''{args.type_path}.target''' ) ) else: shutil.rmtree(snake_case_ ) def lowerCAmelCase_ ( snake_case_ ): _A : Dict = [] for partial_result in partial_results: records.extend(snake_case_ ) _A : Optional[Any] = sorted(snake_case_,key=lambda snake_case_ : x["id"] ) _A : List[str] = [x["""pred"""] for x in records] return preds def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): # WAIT FOR lots of .json files _A : Optional[Any] = time.time() logger.info("""waiting for all nodes to finish""" ) _A : List[str] = None while (time.time() - start_wait) < timeout: _A : str = list(save_dir.glob("""rank_*.json""" ) ) if len(snake_case_ ) < num_replicas: continue try: # make sure all json files are fully saved _A : List[str] = lmap(snake_case_,snake_case_ ) return json_data except JSONDecodeError: continue else: raise TimeoutError("""Rank 0 gave up on waiting for other processes""" ) # Unreachable if __name__ == "__main__": # Usage for MT: run_generate()
26
1
'''simple docstring''' import argparse import json import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( VideoMAEConfig, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEImageProcessor, ) def __lowerCamelCase ( __snake_case : Union[str, Any] ) -> Tuple: """simple docstring""" A__ : Optional[int] =VideoMAEConfig() set_architecture_configs(__snake_case, __snake_case ) if "finetuned" not in model_name: A__ : List[Any] =False if "finetuned" in model_name: A__ : int ="""huggingface/label-files""" if "kinetics" in model_name: A__ : List[Any] =400 A__ : str ="""kinetics400-id2label.json""" elif "ssv2" in model_name: A__ : Any =174 A__ : str ="""something-something-v2-id2label.json""" else: raise ValueError("""Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned.""" ) A__ : List[Any] =json.load(open(hf_hub_download(__snake_case, __snake_case, repo_type="""dataset""" ), """r""" ) ) A__ : Dict ={int(__snake_case ): v for k, v in idalabel.items()} A__ : str =idalabel A__ : Tuple ={v: k for k, v in idalabel.items()} return config def __lowerCamelCase ( __snake_case : int, __snake_case : int ) -> Optional[int]: """simple docstring""" if "small" in model_name: A__ : Union[str, Any] =384 A__ : str =1_536 A__ : Optional[Any] =12 A__ : List[Any] =16 A__ : Dict =12 A__ : int =3 A__ : Tuple =192 A__ : Union[str, Any] =768 elif "large" in model_name: A__ : Union[str, Any] =1_024 A__ : Tuple =4_096 A__ : Optional[Any] =24 A__ : Any =16 A__ : Optional[Any] =12 A__ : Union[str, Any] =8 A__ : Any =512 A__ : str =2_048 elif "huge" in model_name: A__ : Union[str, Any] =1_280 A__ : int =5_120 A__ : List[str] =32 A__ : str =16 A__ : Dict =12 A__ : Dict =8 A__ : str =640 A__ : Tuple =2_560 elif "base" not in model_name: raise ValueError("""Model name should include either \"small\", \"base\", \"large\", or \"huge\"""" ) def __lowerCamelCase ( __snake_case : str ) -> Optional[Any]: """simple docstring""" if "encoder." in name: A__ : Optional[Any] =name.replace("""encoder.""", """""" ) if "cls_token" in name: A__ : Optional[int] =name.replace("""cls_token""", """videomae.embeddings.cls_token""" ) if "decoder_pos_embed" in name: A__ : Optional[int] =name.replace("""decoder_pos_embed""", """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: A__ : Dict =name.replace("""pos_embed""", """videomae.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: A__ : List[Any] =name.replace("""patch_embed.proj""", """videomae.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: A__ : Tuple =name.replace("""patch_embed.norm""", """videomae.embeddings.norm""" ) if "decoder.blocks" in name: A__ : Optional[Any] =name.replace("""decoder.blocks""", """decoder.decoder_layers""" ) if "blocks" in name: A__ : int =name.replace("""blocks""", """videomae.encoder.layer""" ) if "attn.proj" in name: A__ : Dict =name.replace("""attn.proj""", """attention.output.dense""" ) if "attn" in name and "bias" not in name: A__ : Dict =name.replace("""attn""", """attention.self""" ) if "attn" in name: A__ : Tuple =name.replace("""attn""", """attention.attention""" ) if "norm1" in name: A__ : Tuple =name.replace("""norm1""", """layernorm_before""" ) if "norm2" in name: A__ : Optional[Any] =name.replace("""norm2""", """layernorm_after""" ) if "mlp.fc1" in name: A__ : Optional[int] =name.replace("""mlp.fc1""", """intermediate.dense""" ) if "mlp.fc2" in name: A__ : List[str] =name.replace("""mlp.fc2""", """output.dense""" ) if "decoder_embed" in name: A__ : Any =name.replace("""decoder_embed""", """decoder.decoder_embed""" ) if "decoder_norm" in name: A__ : Dict =name.replace("""decoder_norm""", """decoder.decoder_norm""" ) if "decoder_pred" in name: A__ : List[str] =name.replace("""decoder_pred""", """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name and "fc" not in name: A__ : List[Any] =name.replace("""norm.weight""", """videomae.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name and "fc" not in name: A__ : Dict =name.replace("""norm.bias""", """videomae.layernorm.bias""" ) if "head" in name and "decoder" not in name: A__ : str =name.replace("""head""", """classifier""" ) return name def __lowerCamelCase ( __snake_case : Tuple, __snake_case : Optional[int] ) -> Tuple: """simple docstring""" for key in orig_state_dict.copy().keys(): A__ : Optional[Any] =orig_state_dict.pop(__snake_case ) if key.startswith("""encoder.""" ): A__ : Dict =key.replace("""encoder.""", """""" ) if "qkv" in key: A__ : Any =key.split(""".""" ) if key.startswith("""decoder.blocks""" ): A__ : List[str] =config.decoder_hidden_size A__ : List[str] =int(key_split[2] ) A__ : Tuple ="""decoder.decoder_layers.""" if "weight" in key: A__ : Optional[int] =val[:dim, :] A__ : Optional[Any] =val[dim : dim * 2, :] A__ : Optional[Any] =val[-dim:, :] else: A__ : int =config.hidden_size A__ : Any =int(key_split[1] ) A__ : Optional[int] ="""videomae.encoder.layer.""" if "weight" in key: A__ : Dict =val[:dim, :] A__ : Optional[int] =val[dim : dim * 2, :] A__ : Union[str, Any] =val[-dim:, :] else: A__ : str =val return orig_state_dict def __lowerCamelCase ( ) -> Dict: """simple docstring""" A__ : str =hf_hub_download( repo_id="""hf-internal-testing/spaghetti-video""", filename="""eating_spaghetti.npy""", repo_type="""dataset""" ) A__ : Any =np.load(__snake_case ) return list(__snake_case ) def __lowerCamelCase ( __snake_case : Union[str, Any], __snake_case : List[Any], __snake_case : Optional[int], __snake_case : Optional[Any] ) -> List[str]: """simple docstring""" A__ : Tuple =get_videomae_config(__snake_case ) if "finetuned" in model_name: A__ : Optional[Any] =VideoMAEForVideoClassification(__snake_case ) else: A__ : Optional[Any] =VideoMAEForPreTraining(__snake_case ) # download original checkpoint, hosted on Google Drive A__ : Optional[Any] ="""pytorch_model.bin""" gdown.cached_download(__snake_case, __snake_case, quiet=__snake_case ) A__ : List[str] =torch.load(__snake_case, map_location="""cpu""" ) if "model" in files: A__ : List[Any] =files["""model"""] else: A__ : Tuple =files["""module"""] A__ : Union[str, Any] =convert_state_dict(__snake_case, __snake_case ) model.load_state_dict(__snake_case ) model.eval() # verify model on basic input A__ : List[str] =VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5] ) A__ : int =prepare_video() A__ : Optional[Any] =image_processor(__snake_case, return_tensors="""pt""" ) if "finetuned" not in model_name: A__ : Any =hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos""", filename="""bool_masked_pos.pt""" ) A__ : str =torch.load(__snake_case ) A__ : int =model(**__snake_case ) A__ : List[str] =outputs.logits A__ : Union[str, Any] =[ """videomae-small-finetuned-kinetics""", """videomae-small-finetuned-ssv2""", # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600) """videomae-base-short""", """videomae-base-short-finetuned-kinetics""", """videomae-base""", """videomae-base-finetuned-kinetics""", """videomae-large""", """videomae-large-finetuned-kinetics""", """videomae-huge-finetuned-kinetics""", # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400) """videomae-base-short-ssv2""", """videomae-base-short-finetuned-ssv2""", """videomae-base-ssv2""", """videomae-base-finetuned-ssv2""", ] # NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5] if model_name == "videomae-small-finetuned-kinetics": A__ : Any =torch.Size([1, 400] ) A__ : List[Any] =torch.tensor([-0.92_91, -0.40_61, -0.93_07] ) elif model_name == "videomae-small-finetuned-ssv2": A__ : str =torch.Size([1, 174] ) A__ : Optional[Any] =torch.tensor([0.26_71, -0.46_89, -0.82_35] ) elif model_name == "videomae-base": A__ : Optional[int] =torch.Size([1, 1_408, 1_536] ) A__ : Optional[int] =torch.tensor([[0.77_39, 0.79_68, 0.70_89], [0.67_01, 0.74_87, 0.62_09], [0.42_87, 0.51_58, 0.47_73]] ) elif model_name == "videomae-base-short": A__ : str =torch.Size([1, 1_408, 1_536] ) A__ : Tuple =torch.tensor([[0.79_94, 0.96_12, 0.85_08], [0.74_01, 0.89_58, 0.83_02], [0.58_62, 0.74_68, 0.73_25]] ) # we verified the loss both for normalized and unnormalized targets for this one A__ : List[Any] =torch.tensor([0.51_42] ) if config.norm_pix_loss else torch.tensor([0.64_69] ) elif model_name == "videomae-large": A__ : Optional[Any] =torch.Size([1, 1_408, 1_536] ) A__ : int =torch.tensor([[0.71_49, 0.79_97, 0.69_66], [0.67_68, 0.78_69, 0.69_48], [0.51_39, 0.62_21, 0.56_05]] ) elif model_name == "videomae-large-finetuned-kinetics": A__ : int =torch.Size([1, 400] ) A__ : str =torch.tensor([0.07_71, 0.00_11, -0.36_25] ) elif model_name == "videomae-huge-finetuned-kinetics": A__ : Any =torch.Size([1, 400] ) A__ : Tuple =torch.tensor([0.24_33, 0.16_32, -0.48_94] ) elif model_name == "videomae-base-short-finetuned-kinetics": A__ : Union[str, Any] =torch.Size([1, 400] ) A__ : List[Any] =torch.tensor([0.65_88, 0.09_90, -0.24_93] ) elif model_name == "videomae-base-finetuned-kinetics": A__ : List[str] =torch.Size([1, 400] ) A__ : List[str] =torch.tensor([0.36_69, -0.06_88, -0.24_21] ) elif model_name == "videomae-base-short-ssv2": A__ : Dict =torch.Size([1, 1_408, 1_536] ) A__ : Any =torch.tensor([[0.47_12, 0.52_96, 0.57_86], [0.22_78, 0.27_29, 0.40_26], [0.03_52, 0.07_30, 0.25_06]] ) elif model_name == "videomae-base-short-finetuned-ssv2": A__ : Dict =torch.Size([1, 174] ) A__ : Dict =torch.tensor([-0.05_37, -0.15_39, -0.32_66] ) elif model_name == "videomae-base-ssv2": A__ : str =torch.Size([1, 1_408, 1_536] ) A__ : List[str] =torch.tensor([[0.81_31, 0.87_27, 0.85_46], [0.73_66, 0.93_77, 0.88_70], [0.59_35, 0.88_74, 0.85_64]] ) elif model_name == "videomae-base-finetuned-ssv2": A__ : Any =torch.Size([1, 174] ) A__ : str =torch.tensor([0.19_61, -0.83_37, -0.63_89] ) else: raise ValueError(f"Model name not supported. Should be one of {model_names}" ) # verify logits assert logits.shape == expected_shape if "finetuned" in model_name: assert torch.allclose(logits[0, :3], __snake_case, atol=1E-4 ) else: print("""Logits:""", logits[0, :3, :3] ) assert torch.allclose(logits[0, :3, :3], __snake_case, atol=1E-4 ) print("""Logits ok!""" ) # verify loss, if applicable if model_name == "videomae-base-short": A__ : Optional[Any] =outputs.loss assert torch.allclose(__snake_case, __snake_case, atol=1E-4 ) print("""Loss ok!""" ) if pytorch_dump_folder_path is not None: print(f"Saving model and image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__snake_case ) model.save_pretrained(__snake_case ) if push_to_hub: print("""Pushing to the hub...""" ) model.push_to_hub(__snake_case, organization="""nielsr""" ) if __name__ == "__main__": __snake_case : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&amp;export=download&amp;confirm=t&amp;uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4', type=str, help=( 'URL of the original PyTorch checkpoint (on Google Drive) you\'d like to convert. Should be a direct' ' download link.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default='/Users/nielsrogge/Documents/VideoMAE/Test', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--model_name', default='videomae-base', type=str, help='Name of the model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __snake_case : Tuple = parser.parse_args() convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
136
'''simple docstring''' from __future__ import annotations from typing import Any class lowerCamelCase : '''simple docstring''' def __init__( self : List[str] , lowerCAmelCase_ : int ) -> None: '''simple docstring''' A__ : Any =num_of_nodes A__ : list[list[int]] =[] A__ : dict[int, int] ={} def lowercase__ ( self : Optional[Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ) -> None: '''simple docstring''' self.m_edges.append([u_node, v_node, weight] ) def lowercase__ ( self : int , lowerCAmelCase_ : int ) -> int: '''simple docstring''' if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def lowercase__ ( self : Optional[int] , lowerCAmelCase_ : int ) -> None: '''simple docstring''' if self.m_component[u_node] != u_node: for k in self.m_component: A__ : str =self.find_component(lowerCAmelCase_ ) def lowercase__ ( self : int , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : int ) -> None: '''simple docstring''' if component_size[u_node] <= component_size[v_node]: A__ : int =v_node component_size[v_node] += component_size[u_node] self.set_component(lowerCAmelCase_ ) elif component_size[u_node] >= component_size[v_node]: A__ : List[str] =self.find_component(lowerCAmelCase_ ) component_size[u_node] += component_size[v_node] self.set_component(lowerCAmelCase_ ) def lowercase__ ( self : str ) -> None: '''simple docstring''' A__ : Union[str, Any] =[] A__ : List[str] =0 A__ : list[Any] =[-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) A__ : List[str] =self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: A__ , A__ , A__ : Any =edge A__ : Tuple =self.m_component[u] A__ : Optional[Any] =self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): A__ : Optional[int] =[u, v, w] for edge in minimum_weight_edge: if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): A__ , A__ , A__ : Tuple =edge A__ : Any =self.m_component[u] A__ : Optional[Any] =self.m_component[v] if u_component != v_component: mst_weight += w self.union(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) print(f"Added edge [{u} - {v}]\nAdded weight: {w}\n" ) num_of_components -= 1 A__ : int =[-1] * self.m_num_of_nodes print(f"The total weight of the minimal spanning tree is: {mst_weight}" ) def __lowerCamelCase ( ) -> None: """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
136
1
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline lowerCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name class snake_case__(_UpperCamelCase ): """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Union[str, Any] ): super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self : Tuple , SCREAMING_SNAKE_CASE : int = 1 , SCREAMING_SNAKE_CASE : int = 100 , SCREAMING_SNAKE_CASE : Optional[Union[torch.Generator, List[torch.Generator]]] = None , SCREAMING_SNAKE_CASE : Optional[float] = None , SCREAMING_SNAKE_CASE : bool = True , ): if audio_length_in_s is None: lowercase__ : Tuple = self.unet.config.sample_size / self.unet.config.sample_rate lowercase__ : List[Any] = audio_length_in_s * self.unet.config.sample_rate lowercase__ : List[Any] = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( f"""{audio_length_in_s} is too small. Make sure it's bigger or equal to""" f""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" ) lowercase__ : str = int(SCREAMING_SNAKE_CASE ) if sample_size % down_scale_factor != 0: lowercase__ : str = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( f"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled""" f""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising""" " process." ) lowercase__ : int = int(SCREAMING_SNAKE_CASE ) lowercase__ : Dict = next(iter(self.unet.parameters() ) ).dtype lowercase__ : Dict = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f"""You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE )}, but requested an effective batch""" f""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) lowercase__ : Optional[int] = randn_tensor(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device=self.device , dtype=SCREAMING_SNAKE_CASE ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE , device=audio.device ) lowercase__ : Any = self.scheduler.timesteps.to(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output lowercase__ : List[str] = self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. compute previous image: x_t -> t_t-1 lowercase__ : int = self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample lowercase__ : Tuple = audio.clamp(-1 , 1 ).float().cpu().numpy() lowercase__ : str = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=SCREAMING_SNAKE_CASE )
130
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} lowerCAmelCase__ = { '''vocab_file''': { '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt''', '''distilbert-base-uncased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt''' ), '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt''', '''distilbert-base-cased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt''' ), '''distilbert-base-german-cased''': '''https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt''', '''distilbert-base-multilingual-cased''': ( '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json''', '''distilbert-base-uncased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json''' ), '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json''', '''distilbert-base-cased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json''' ), '''distilbert-base-german-cased''': ( '''https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json''' ), '''distilbert-base-multilingual-cased''': ( '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json''' ), }, } lowerCAmelCase__ = { '''distilbert-base-uncased''': 5_1_2, '''distilbert-base-uncased-distilled-squad''': 5_1_2, '''distilbert-base-cased''': 5_1_2, '''distilbert-base-cased-distilled-squad''': 5_1_2, '''distilbert-base-german-cased''': 5_1_2, '''distilbert-base-multilingual-cased''': 5_1_2, } lowerCAmelCase__ = { '''distilbert-base-uncased''': {'''do_lower_case''': True}, '''distilbert-base-uncased-distilled-squad''': {'''do_lower_case''': True}, '''distilbert-base-cased''': {'''do_lower_case''': False}, '''distilbert-base-cased-distilled-squad''': {'''do_lower_case''': False}, '''distilbert-base-german-cased''': {'''do_lower_case''': False}, '''distilbert-base-multilingual-cased''': {'''do_lower_case''': False}, } class snake_case__(_UpperCamelCase ): """simple docstring""" lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = PRETRAINED_INIT_CONFIGURATION lowercase_ = ["""input_ids""", """attention_mask"""] lowercase_ = DistilBertTokenizer def __init__( self : Tuple , SCREAMING_SNAKE_CASE : str=None , SCREAMING_SNAKE_CASE : Any=None , SCREAMING_SNAKE_CASE : Tuple=True , SCREAMING_SNAKE_CASE : Union[str, Any]="[UNK]" , SCREAMING_SNAKE_CASE : str="[SEP]" , SCREAMING_SNAKE_CASE : Dict="[PAD]" , SCREAMING_SNAKE_CASE : List[str]="[CLS]" , SCREAMING_SNAKE_CASE : List[str]="[MASK]" , SCREAMING_SNAKE_CASE : Tuple=True , SCREAMING_SNAKE_CASE : int=None , **SCREAMING_SNAKE_CASE : Dict , ): super().__init__( SCREAMING_SNAKE_CASE , tokenizer_file=SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE , unk_token=SCREAMING_SNAKE_CASE , sep_token=SCREAMING_SNAKE_CASE , pad_token=SCREAMING_SNAKE_CASE , cls_token=SCREAMING_SNAKE_CASE , mask_token=SCREAMING_SNAKE_CASE , tokenize_chinese_chars=SCREAMING_SNAKE_CASE , strip_accents=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) lowercase__ : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , SCREAMING_SNAKE_CASE ) != do_lower_case or normalizer_state.get("strip_accents" , SCREAMING_SNAKE_CASE ) != strip_accents or normalizer_state.get("handle_chinese_chars" , SCREAMING_SNAKE_CASE ) != tokenize_chinese_chars ): lowercase__ : Optional[Any] = getattr(SCREAMING_SNAKE_CASE , normalizer_state.pop("type" ) ) lowercase__ : Any = do_lower_case lowercase__ : Optional[int] = strip_accents lowercase__ : List[Any] = tokenize_chinese_chars lowercase__ : List[Any] = normalizer_class(**SCREAMING_SNAKE_CASE ) lowercase__ : Optional[int] = do_lower_case def snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Dict=None ): lowercase__ : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def snake_case ( self : List[str] , SCREAMING_SNAKE_CASE : List[int] , SCREAMING_SNAKE_CASE : Optional[List[int]] = None ): lowercase__ : Dict = [self.sep_token_id] lowercase__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def snake_case ( self : Any , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[str] = None ): lowercase__ : Union[str, Any] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE , name=SCREAMING_SNAKE_CASE ) return tuple(SCREAMING_SNAKE_CASE )
130
1
def snake_case_ ( lowerCAmelCase_ : Dict ): __lowercase : Optional[Any] = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def snake_case_ ( lowerCAmelCase_ : Any = 5000 ): __lowercase : Optional[int] = [(i * (3 * i - 1)) // 2 for i in range(1 , lowercase_ )] for i, pentagonal_i in enumerate(lowercase_ ): for j in range(lowercase_ , len(lowercase_ ) ): __lowercase : Union[str, Any] = pentagonal_nums[j] __lowercase : Dict = pentagonal_i + pentagonal_j __lowercase : List[str] = pentagonal_j - pentagonal_i if is_pentagonal(lowercase_ ) and is_pentagonal(lowercase_ ): return b return -1 if __name__ == "__main__": print(f'''{solution() = }''')
362
def snake_case_ ( lowerCAmelCase_ : str , lowerCAmelCase_ : str ): if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError("""String lengths must match!""" ) __lowercase : str = 0 for chara, chara in zip(lowerCAmelCase_ , lowerCAmelCase_ ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
306
0
from __future__ import annotations import os import tempfile import unittest from transformers import ConvBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class A : """simple docstring""" def __init__( self : Union[str, Any],lowercase_ : int,lowercase_ : Union[str, Any]=1_3,lowercase_ : List[str]=7,lowercase_ : Tuple=True,lowercase_ : List[str]=True,lowercase_ : List[str]=True,lowercase_ : List[str]=True,lowercase_ : Tuple=9_9,lowercase_ : Union[str, Any]=3_2,lowercase_ : str=2,lowercase_ : Optional[Any]=4,lowercase_ : Optional[int]=3_7,lowercase_ : int="gelu",lowercase_ : Any=0.1,lowercase_ : Optional[int]=0.1,lowercase_ : List[str]=5_1_2,lowercase_ : int=1_6,lowercase_ : Dict=2,lowercase_ : Any=0.02,lowercase_ : Union[str, Any]=3,lowercase_ : Dict=4,lowercase_ : Dict=None,)-> Optional[int]: '''simple docstring''' A__ = parent A__ = 1_3 A__ = 7 A__ = True A__ = True A__ = True A__ = True A__ = 9_9 A__ = 3_8_4 A__ = 2 A__ = 4 A__ = 3_7 A__ = 'gelu' A__ = 0.1 A__ = 0.1 A__ = 5_1_2 A__ = 1_6 A__ = 2 A__ = 0.02 A__ = 3 A__ = 4 A__ = 1_2_8 A__ = 2 A__ = 9 A__ = 1 A__ = None def snake_case__ ( self : Any )-> Optional[int]: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length],self.vocab_size ) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length] ) A__ = None if self.use_token_type_ids: A__ = ids_tensor([self.batch_size, self.seq_length],self.type_vocab_size ) A__ = None A__ = None A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size],self.type_sequence_label_size ) A__ = ids_tensor([self.batch_size, self.seq_length],self.num_labels ) A__ = ids_tensor([self.batch_size],self.num_choices ) A__ = ConvBertConfig( vocab_size=self.vocab_size,hidden_size=self.hidden_size,num_hidden_layers=self.num_hidden_layers,num_attention_heads=self.num_attention_heads,intermediate_size=self.intermediate_size,hidden_act=self.hidden_act,hidden_dropout_prob=self.hidden_dropout_prob,attention_probs_dropout_prob=self.attention_probs_dropout_prob,max_position_embeddings=self.max_position_embeddings,type_vocab_size=self.type_vocab_size,initializer_range=self.initializer_range,return_dict=lowercase_,) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case__ ( self : List[Any],lowercase_ : Optional[Any],lowercase_ : List[str],lowercase_ : str,lowercase_ : Optional[Any],lowercase_ : int,lowercase_ : Union[str, Any],lowercase_ : Dict )-> List[Any]: '''simple docstring''' A__ = TFConvBertModel(config=lowercase_ ) A__ = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} A__ = [input_ids, input_mask] A__ = model(lowercase_ ) A__ = model(lowercase_ ) self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size) ) def snake_case__ ( self : Union[str, Any],lowercase_ : Optional[Any],lowercase_ : int,lowercase_ : Any,lowercase_ : Any,lowercase_ : Optional[Any],lowercase_ : Tuple,lowercase_ : Optional[Any] )-> Tuple: '''simple docstring''' A__ = TFConvBertForMaskedLM(config=lowercase_ ) A__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } A__ = model(lowercase_ ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.vocab_size) ) def snake_case__ ( self : List[Any],lowercase_ : List[str],lowercase_ : Tuple,lowercase_ : Optional[int],lowercase_ : Any,lowercase_ : Dict,lowercase_ : str,lowercase_ : str )-> Union[str, Any]: '''simple docstring''' A__ = self.num_labels A__ = TFConvBertForSequenceClassification(config=lowercase_ ) A__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } A__ = model(lowercase_ ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels) ) def snake_case__ ( self : List[str],lowercase_ : Tuple,lowercase_ : Optional[int],lowercase_ : List[str],lowercase_ : List[Any],lowercase_ : Dict,lowercase_ : List[str],lowercase_ : Dict )-> int: '''simple docstring''' A__ = self.num_choices A__ = TFConvBertForMultipleChoice(config=lowercase_ ) A__ = tf.tile(tf.expand_dims(lowercase_,1 ),(1, self.num_choices, 1) ) A__ = tf.tile(tf.expand_dims(lowercase_,1 ),(1, self.num_choices, 1) ) A__ = tf.tile(tf.expand_dims(lowercase_,1 ),(1, self.num_choices, 1) ) A__ = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } A__ = model(lowercase_ ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_choices) ) def snake_case__ ( self : int,lowercase_ : int,lowercase_ : Dict,lowercase_ : List[Any],lowercase_ : Dict,lowercase_ : List[Any],lowercase_ : Optional[Any],lowercase_ : Optional[Any] )-> Dict: '''simple docstring''' A__ = self.num_labels A__ = TFConvBertForTokenClassification(config=lowercase_ ) A__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } A__ = model(lowercase_ ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.seq_length, self.num_labels) ) def snake_case__ ( self : str,lowercase_ : Optional[Any],lowercase_ : Optional[Any],lowercase_ : Optional[Any],lowercase_ : List[Any],lowercase_ : Any,lowercase_ : Union[str, Any],lowercase_ : Dict )-> Tuple: '''simple docstring''' A__ = TFConvBertForQuestionAnswering(config=lowercase_ ) A__ = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } A__ = model(lowercase_ ) 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 snake_case__ ( self : int )-> Any: '''simple docstring''' A__ = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = config_and_inputs A__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class A ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) lowerCamelCase = ( { 'feature-extraction': TFConvBertModel, 'fill-mask': TFConvBertForMaskedLM, 'question-answering': TFConvBertForQuestionAnswering, 'text-classification': TFConvBertForSequenceClassification, 'token-classification': TFConvBertForTokenClassification, 'zero-shot': TFConvBertForSequenceClassification, } if is_tf_available() else {} ) lowerCamelCase = False lowerCamelCase = False lowerCamelCase = False def snake_case__ ( self : List[Any] )-> Optional[int]: '''simple docstring''' A__ = TFConvBertModelTester(self ) A__ = ConfigTester(self,config_class=lowercase_,hidden_size=3_7 ) def snake_case__ ( self : Union[str, Any] )-> List[str]: '''simple docstring''' self.config_tester.run_common_tests() def snake_case__ ( self : Optional[Any] )-> Any: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) def snake_case__ ( self : Any )-> int: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase_ ) def snake_case__ ( self : Dict )-> Optional[int]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowercase_ ) def snake_case__ ( self : Tuple )-> Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_ ) def snake_case__ ( self : str )-> List[str]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowercase_ ) def snake_case__ ( self : Union[str, Any] )-> Union[str, Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_ ) @slow def snake_case__ ( self : str )-> Dict: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = True A__ = True if hasattr(lowercase_,'use_cache' ): A__ = True A__ = getattr(self.model_tester,'encoder_seq_length',self.model_tester.seq_length ) A__ = getattr(self.model_tester,'key_length',lowercase_ ) for model_class in self.all_model_classes: A__ = self._prepare_for_class(lowercase_,lowercase_ ) A__ = model_class(lowercase_ ) A__ = len(model(lowercase_ ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowercase_,saved_model=lowercase_ ) A__ = os.path.join(lowercase_,'saved_model','1' ) A__ = tf.keras.models.load_model(lowercase_ ) A__ = model(lowercase_ ) if self.is_encoder_decoder: A__ = outputs['encoder_hidden_states'] A__ = outputs['encoder_attentions'] else: A__ = outputs['hidden_states'] A__ = outputs['attentions'] self.assertEqual(len(lowercase_ ),lowercase_ ) A__ = getattr( self.model_tester,'expected_num_hidden_layers',self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(lowercase_ ),lowercase_ ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ),[self.model_tester.seq_length, self.model_tester.hidden_size],) self.assertEqual(len(lowercase_ ),self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ),[self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length],) @slow def snake_case__ ( self : List[Any] )-> Union[str, Any]: '''simple docstring''' A__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) self.assertIsNotNone(lowercase_ ) def snake_case__ ( self : Any )-> str: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = True A__ = getattr(self.model_tester,'decoder_seq_length',self.model_tester.seq_length ) A__ = getattr(self.model_tester,'encoder_seq_length',self.model_tester.seq_length ) A__ = getattr(self.model_tester,'key_length',lowercase_ ) A__ = getattr(self.model_tester,'key_length',lowercase_ ) def check_decoder_attentions_output(lowercase_ : Union[str, Any] ): A__ = len(lowercase_ ) self.assertEqual(out_len % 2,0 ) A__ = outputs.decoder_attentions self.assertEqual(len(lowercase_ ),self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ),[self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length],) def check_encoder_attentions_output(lowercase_ : str ): A__ = [ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(lowercase_ ),self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ),[self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length],) for model_class in self.all_model_classes: A__ = True A__ = False A__ = model_class(lowercase_ ) A__ = model(self._prepare_for_class(lowercase_,lowercase_ ) ) A__ = len(lowercase_ ) self.assertEqual(config.output_hidden_states,lowercase_ ) check_encoder_attentions_output(lowercase_ ) if self.is_encoder_decoder: A__ = model_class(lowercase_ ) A__ = model(self._prepare_for_class(lowercase_,lowercase_ ) ) self.assertEqual(config.output_hidden_states,lowercase_ ) check_decoder_attentions_output(lowercase_ ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] A__ = True A__ = model_class(lowercase_ ) A__ = model(self._prepare_for_class(lowercase_,lowercase_ ) ) self.assertEqual(config.output_hidden_states,lowercase_ ) check_encoder_attentions_output(lowercase_ ) # Check attention is always last and order is fine A__ = True A__ = True A__ = model_class(lowercase_ ) A__ = model(self._prepare_for_class(lowercase_,lowercase_ ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1),len(lowercase_ ) ) self.assertEqual(model.config.output_hidden_states,lowercase_ ) check_encoder_attentions_output(lowercase_ ) @require_tf class A ( unittest.TestCase ): """simple docstring""" @slow def snake_case__ ( self : Optional[Any] )-> str: '''simple docstring''' A__ = TFConvBertModel.from_pretrained('YituTech/conv-bert-base' ) A__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) A__ = model(lowercase_ )[0] A__ = [1, 6, 7_6_8] self.assertEqual(output.shape,lowercase_ ) A__ = tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3],lowercase_,atol=1E-4 )
7
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class A ( _UpperCAmelCase ): """simple docstring""" lowerCamelCase = (DPMSolverSinglestepScheduler,) lowerCamelCase = (('num_inference_steps', 25),) def snake_case__ ( self : Tuple,**lowercase_ : Dict )-> Optional[int]: '''simple docstring''' A__ = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, 'prediction_type': 'epsilon', 'thresholding': False, 'sample_max_value': 1.0, 'algorithm_type': 'dpmsolver++', 'solver_type': 'midpoint', 'lambda_min_clipped': -float('inf' ), 'variance_type': None, } config.update(**lowercase_ ) return config def snake_case__ ( self : str,lowercase_ : Optional[Any]=0,**lowercase_ : Any )-> List[Any]: '''simple docstring''' A__ = dict(self.forward_default_kwargs ) A__ = kwargs.pop('num_inference_steps',lowercase_ ) A__ = self.dummy_sample A__ = 0.1 * sample A__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A__ = self.get_scheduler_config(**lowercase_ ) A__ = scheduler_class(**lowercase_ ) scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals A__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_ ) A__ = scheduler_class.from_pretrained(lowercase_ ) new_scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals A__ = dummy_past_residuals[: new_scheduler.config.solver_order] A__ , A__ = sample, sample for t in range(lowercase_,time_step + scheduler.config.solver_order + 1 ): A__ = scheduler.step(lowercase_,lowercase_,lowercase_,**lowercase_ ).prev_sample A__ = new_scheduler.step(lowercase_,lowercase_,lowercase_,**lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def snake_case__ ( self : List[str] )-> List[Any]: '''simple docstring''' pass def snake_case__ ( self : Tuple,lowercase_ : Union[str, Any]=0,**lowercase_ : Union[str, Any] )-> Union[str, Any]: '''simple docstring''' A__ = dict(self.forward_default_kwargs ) A__ = kwargs.pop('num_inference_steps',lowercase_ ) A__ = self.dummy_sample A__ = 0.1 * sample A__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A__ = self.get_scheduler_config() A__ = scheduler_class(**lowercase_ ) scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals (must be after setting timesteps) A__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_ ) A__ = scheduler_class.from_pretrained(lowercase_ ) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_ ) # copy over dummy past residual (must be after setting timesteps) A__ = dummy_past_residuals[: new_scheduler.config.solver_order] A__ = scheduler.step(lowercase_,lowercase_,lowercase_,**lowercase_ ).prev_sample A__ = new_scheduler.step(lowercase_,lowercase_,lowercase_,**lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def snake_case__ ( self : Optional[Any],lowercase_ : Optional[int]=None,**lowercase_ : int )-> int: '''simple docstring''' if scheduler is None: A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config(**lowercase_ ) A__ = scheduler_class(**lowercase_ ) A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config(**lowercase_ ) A__ = scheduler_class(**lowercase_ ) A__ = 1_0 A__ = self.dummy_model() A__ = self.dummy_sample_deter scheduler.set_timesteps(lowercase_ ) for i, t in enumerate(scheduler.timesteps ): A__ = model(lowercase_,lowercase_ ) A__ = scheduler.step(lowercase_,lowercase_,lowercase_ ).prev_sample return sample def snake_case__ ( self : Any )-> str: '''simple docstring''' A__ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) A__ = 5_0 A__ = self.dummy_model() A__ = self.dummy_sample_deter scheduler.set_timesteps(lowercase_ ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): A__ = model(lowercase_,lowercase_ ) A__ = scheduler.step(lowercase_,lowercase_,lowercase_ ).prev_sample A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.2_574 ) < 1E-3 def snake_case__ ( self : Optional[Any] )-> List[Any]: '''simple docstring''' for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_configs(num_train_timesteps=lowercase_ ) def snake_case__ ( self : int )-> Optional[Any]: '''simple docstring''' A__ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) A__ = self.full_loop(scheduler=lowercase_ ) A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.2_791 ) < 1E-3 A__ = DEISMultistepScheduler.from_config(scheduler.config ) A__ = DPMSolverMultistepScheduler.from_config(scheduler.config ) A__ = UniPCMultistepScheduler.from_config(scheduler.config ) A__ = DPMSolverSinglestepScheduler.from_config(scheduler.config ) A__ = self.full_loop(scheduler=lowercase_ ) A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.2_791 ) < 1E-3 def snake_case__ ( self : Tuple )-> Any: '''simple docstring''' self.check_over_configs(thresholding=lowercase_ ) for order in [1, 2, 3]: for solver_type in ["midpoint", "heun"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=lowercase_,prediction_type=lowercase_,sample_max_value=lowercase_,algorithm_type='dpmsolver++',solver_order=lowercase_,solver_type=lowercase_,) def snake_case__ ( self : List[Any] )-> int: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_ ) def snake_case__ ( self : Dict )-> List[Any]: '''simple docstring''' for algorithm_type in ["dpmsolver", "dpmsolver++"]: for solver_type in ["midpoint", "heun"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=lowercase_,solver_type=lowercase_,prediction_type=lowercase_,algorithm_type=lowercase_,) A__ = self.full_loop( solver_order=lowercase_,solver_type=lowercase_,prediction_type=lowercase_,algorithm_type=lowercase_,) assert not torch.isnan(lowercase_ ).any(), "Samples have nan numbers" def snake_case__ ( self : Optional[int] )-> Tuple: '''simple docstring''' self.check_over_configs(lower_order_final=lowercase_ ) self.check_over_configs(lower_order_final=lowercase_ ) def snake_case__ ( self : Tuple )-> Optional[int]: '''simple docstring''' self.check_over_configs(lambda_min_clipped=-float('inf' ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def snake_case__ ( self : Optional[Any] )-> Tuple: '''simple docstring''' self.check_over_configs(variance_type=lowercase_ ) self.check_over_configs(variance_type='learned_range' ) def snake_case__ ( self : str )-> Any: '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_forward(num_inference_steps=lowercase_,time_step=0 ) def snake_case__ ( self : Tuple )-> Tuple: '''simple docstring''' A__ = self.full_loop() A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.2_791 ) < 1E-3 def snake_case__ ( self : Any )-> Union[str, Any]: '''simple docstring''' A__ = self.full_loop(use_karras_sigmas=lowercase_ ) A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.2_248 ) < 1E-3 def snake_case__ ( self : Union[str, Any] )-> Tuple: '''simple docstring''' A__ = self.full_loop(prediction_type='v_prediction' ) A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.1_453 ) < 1E-3 def snake_case__ ( self : Tuple )-> int: '''simple docstring''' A__ = self.full_loop(prediction_type='v_prediction',use_karras_sigmas=lowercase_ ) A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.0_649 ) < 1E-3 def snake_case__ ( self : List[Any] )-> int: '''simple docstring''' A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config(thresholding=lowercase_,dynamic_thresholding_ratio=0 ) A__ = scheduler_class(**lowercase_ ) A__ = 1_0 A__ = self.dummy_model() A__ = self.dummy_sample_deter.half() scheduler.set_timesteps(lowercase_ ) for i, t in enumerate(scheduler.timesteps ): A__ = model(lowercase_,lowercase_ ) A__ = scheduler.step(lowercase_,lowercase_,lowercase_ ).prev_sample assert sample.dtype == torch.floataa
7
1
import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" torch.manual_seed(0) _lowercase : List[Any] = UNetaDModel( sample_size=(32, 64), in_channels=1, out_channels=1, layers_per_block=2, block_out_channels=(1_28, 1_28), down_block_types=('AttnDownBlock2D', 'DownBlock2D'), up_block_types=('UpBlock2D', 'AttnUpBlock2D'), ) return model @property def UpperCamelCase ( self) -> Dict: """simple docstring""" torch.manual_seed(0) _lowercase : Tuple = UNetaDConditionModel( sample_size=(64, 32), in_channels=1, out_channels=1, layers_per_block=2, block_out_channels=(1_28, 1_28), down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D'), up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D'), cross_attention_dim=10, ) return model @property def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" torch.manual_seed(0) _lowercase : int = AutoencoderKL( sample_size=(1_28, 64), in_channels=1, out_channels=1, latent_channels=1, layers_per_block=2, block_out_channels=(1_28, 1_28), down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D'), up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D'), ) _lowercase : Tuple = UNetaDModel( sample_size=(64, 32), in_channels=1, out_channels=1, layers_per_block=2, block_out_channels=(1_28, 1_28), down_block_types=('AttnDownBlock2D', 'DownBlock2D'), up_block_types=('UpBlock2D', 'AttnUpBlock2D'), ) return vqvae, unet @slow def UpperCamelCase ( self) -> List[Any]: """simple docstring""" _lowercase : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator _lowercase : Optional[Any] = Mel( x_res=self.dummy_unet.config.sample_size[1], y_res=self.dummy_unet.config.sample_size[0], ) _lowercase : str = DDPMScheduler() _lowercase : Tuple = AudioDiffusionPipeline(vqvae=lowerCamelCase, unet=self.dummy_unet, mel=lowerCamelCase, scheduler=lowerCamelCase) _lowercase : Any = pipe.to(lowerCamelCase) pipe.set_progress_bar_config(disable=lowerCamelCase) _lowercase : Optional[Any] = torch.Generator(device=lowerCamelCase).manual_seed(42) _lowercase : Tuple = pipe(generator=lowerCamelCase, steps=4) _lowercase : Any = output.audios[0] _lowercase : Tuple = output.images[0] _lowercase : Tuple = torch.Generator(device=lowerCamelCase).manual_seed(42) _lowercase : Tuple = pipe(generator=lowerCamelCase, steps=4, return_dict=lowerCamelCase) _lowercase : List[str] = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) _lowercase : List[Any] = np.frombuffer(image.tobytes(), dtype='uint8')[:10] _lowercase : Dict = np.frombuffer(image_from_tuple.tobytes(), dtype='uint8')[:10] _lowercase : Any = np.array([69, 2_55, 2_55, 2_55, 0, 0, 77, 1_81, 12, 1_27]) assert np.abs(image_slice.flatten() - expected_slice).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() == 0 _lowercase : List[str] = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1], y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0], ) _lowercase : Tuple = DDIMScheduler() _lowercase : str = self.dummy_vqvae_and_unet _lowercase : int = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0], unet=dummy_vqvae_and_unet[1], mel=lowerCamelCase, scheduler=lowerCamelCase) _lowercase : Optional[int] = pipe.to(lowerCamelCase) pipe.set_progress_bar_config(disable=lowerCamelCase) np.random.seed(0) _lowercase : Any = np.random.uniform(-1, 1, ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,)) _lowercase : Dict = torch.Generator(device=lowerCamelCase).manual_seed(42) _lowercase : Dict = pipe(raw_audio=lowerCamelCase, generator=lowerCamelCase, start_step=5, steps=10) _lowercase : Any = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) _lowercase : Optional[Any] = np.frombuffer(image.tobytes(), dtype='uint8')[:10] _lowercase : Tuple = np.array([1_20, 1_17, 1_10, 1_09, 1_38, 1_67, 1_38, 1_48, 1_32, 1_21]) assert np.abs(image_slice.flatten() - expected_slice).max() == 0 _lowercase : Union[str, Any] = self.dummy_unet_condition _lowercase : Optional[Any] = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0], unet=lowerCamelCase, mel=lowerCamelCase, scheduler=lowerCamelCase) _lowercase : Any = pipe.to(lowerCamelCase) pipe.set_progress_bar_config(disable=lowerCamelCase) np.random.seed(0) _lowercase : Optional[int] = torch.rand((1, 1, 10)) _lowercase : Tuple = pipe(generator=lowerCamelCase, encoding=lowerCamelCase) _lowercase : Optional[Any] = output.images[0] _lowercase : List[str] = np.frombuffer(image.tobytes(), dtype='uint8')[:10] _lowercase : Dict = np.array([1_07, 1_03, 1_20, 1_27, 1_42, 1_22, 1_13, 1_22, 97, 1_11]) assert np.abs(image_slice.flatten() - expected_slice).max() == 0 @slow @require_torch_gpu class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : List[str] = torch_device _lowercase : List[Any] = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256') _lowercase : Tuple = pipe.to(lowerCamelCase) pipe.set_progress_bar_config(disable=lowerCamelCase) _lowercase : Any = torch.Generator(device=lowerCamelCase).manual_seed(42) _lowercase : str = pipe(generator=lowerCamelCase) _lowercase : Union[str, Any] = output.audios[0] _lowercase : Union[str, Any] = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] _lowercase : int = np.frombuffer(image.tobytes(), dtype='uint8')[:10] _lowercase : str = np.array([1_51, 1_67, 1_54, 1_44, 1_22, 1_34, 1_21, 1_05, 70, 26]) assert np.abs(image_slice.flatten() - expected_slice).max() == 0
84
import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Optional[Any] = { "b0": efficientnet.EfficientNetBa, "b1": efficientnet.EfficientNetBa, "b2": efficientnet.EfficientNetBa, "b3": efficientnet.EfficientNetBa, "b4": efficientnet.EfficientNetBa, "b5": efficientnet.EfficientNetBa, "b6": efficientnet.EfficientNetBa, "b7": efficientnet.EfficientNetBa, } SCREAMING_SNAKE_CASE : Tuple = { "b0": { "hidden_dim": 1280, "width_coef": 1.0, "depth_coef": 1.0, "image_size": 224, "dropout_rate": 0.2, "dw_padding": [], }, "b1": { "hidden_dim": 1280, "width_coef": 1.0, "depth_coef": 1.1, "image_size": 240, "dropout_rate": 0.2, "dw_padding": [16], }, "b2": { "hidden_dim": 1408, "width_coef": 1.1, "depth_coef": 1.2, "image_size": 260, "dropout_rate": 0.3, "dw_padding": [5, 8, 16], }, "b3": { "hidden_dim": 1536, "width_coef": 1.2, "depth_coef": 1.4, "image_size": 300, "dropout_rate": 0.3, "dw_padding": [5, 18], }, "b4": { "hidden_dim": 1792, "width_coef": 1.4, "depth_coef": 1.8, "image_size": 380, "dropout_rate": 0.4, "dw_padding": [6], }, "b5": { "hidden_dim": 2048, "width_coef": 1.6, "depth_coef": 2.2, "image_size": 456, "dropout_rate": 0.4, "dw_padding": [13, 27], }, "b6": { "hidden_dim": 2304, "width_coef": 1.8, "depth_coef": 2.6, "image_size": 528, "dropout_rate": 0.5, "dw_padding": [31], }, "b7": { "hidden_dim": 2560, "width_coef": 2.0, "depth_coef": 3.1, "image_size": 600, "dropout_rate": 0.5, "dw_padding": [18], }, } def UpperCamelCase_( lowerCamelCase_ ) -> List[str]: _lowercase : Union[str, Any] = EfficientNetConfig() _lowercase : Any = CONFIG_MAP[model_name]['hidden_dim'] _lowercase : Any = CONFIG_MAP[model_name]['width_coef'] _lowercase : Optional[int] = CONFIG_MAP[model_name]['depth_coef'] _lowercase : List[Any] = CONFIG_MAP[model_name]['image_size'] _lowercase : Tuple = CONFIG_MAP[model_name]['dropout_rate'] _lowercase : Dict = CONFIG_MAP[model_name]['dw_padding'] _lowercase : str = 'huggingface/label-files' _lowercase : Optional[Any] = 'imagenet-1k-id2label.json' _lowercase : List[Any] = 1000 _lowercase : str = json.load(open(hf_hub_download(lowerCamelCase_ , lowerCamelCase_ , repo_type='dataset' ) , 'r' ) ) _lowercase : Optional[int] = {int(lowerCamelCase_ ): v for k, v in idalabel.items()} _lowercase : int = idalabel _lowercase : Optional[Any] = {v: k for k, v in idalabel.items()} return config def UpperCamelCase_( ) -> List[Any]: _lowercase : Union[str, Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' _lowercase : Tuple = Image.open(requests.get(lowerCamelCase_ , stream=lowerCamelCase_ ).raw ) return im def UpperCamelCase_( lowerCamelCase_ ) -> Dict: _lowercase : Tuple = CONFIG_MAP[model_name]['image_size'] _lowercase : List[str] = EfficientNetImageProcessor( size={'height': size, 'width': size} , image_mean=[0.4_85, 0.4_56, 0.4_06] , image_std=[0.47_85_39_44, 0.4_73_28_64, 0.47_43_41_63] , do_center_crop=lowerCamelCase_ , ) return preprocessor def UpperCamelCase_( lowerCamelCase_ ) -> Union[str, Any]: _lowercase : Tuple = [v.split('_' )[0].split('block' )[1] for v in original_param_names if v.startswith('block' )] _lowercase : Tuple = sorted(set(lowerCamelCase_ ) ) _lowercase : List[Any] = len(lowerCamelCase_ ) _lowercase : List[str] = {b: str(lowerCamelCase_ ) for b, i in zip(lowerCamelCase_ , range(lowerCamelCase_ ) )} _lowercase : Optional[int] = [] rename_keys.append(('stem_conv/kernel:0', 'embeddings.convolution.weight') ) rename_keys.append(('stem_bn/gamma:0', 'embeddings.batchnorm.weight') ) rename_keys.append(('stem_bn/beta:0', 'embeddings.batchnorm.bias') ) rename_keys.append(('stem_bn/moving_mean:0', 'embeddings.batchnorm.running_mean') ) rename_keys.append(('stem_bn/moving_variance:0', 'embeddings.batchnorm.running_var') ) for b in block_names: _lowercase : Union[str, Any] = block_name_mapping[b] rename_keys.append((F'''block{b}_expand_conv/kernel:0''', F'''encoder.blocks.{hf_b}.expansion.expand_conv.weight''') ) rename_keys.append((F'''block{b}_expand_bn/gamma:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.weight''') ) rename_keys.append((F'''block{b}_expand_bn/beta:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.bias''') ) rename_keys.append( (F'''block{b}_expand_bn/moving_mean:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.running_mean''') ) rename_keys.append( (F'''block{b}_expand_bn/moving_variance:0''', F'''encoder.blocks.{hf_b}.expansion.expand_bn.running_var''') ) rename_keys.append( (F'''block{b}_dwconv/depthwise_kernel:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight''') ) rename_keys.append((F'''block{b}_bn/gamma:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight''') ) rename_keys.append((F'''block{b}_bn/beta:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias''') ) rename_keys.append( (F'''block{b}_bn/moving_mean:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean''') ) rename_keys.append( (F'''block{b}_bn/moving_variance:0''', F'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var''') ) rename_keys.append((F'''block{b}_se_reduce/kernel:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.reduce.weight''') ) rename_keys.append((F'''block{b}_se_reduce/bias:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.reduce.bias''') ) rename_keys.append((F'''block{b}_se_expand/kernel:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.expand.weight''') ) rename_keys.append((F'''block{b}_se_expand/bias:0''', F'''encoder.blocks.{hf_b}.squeeze_excite.expand.bias''') ) rename_keys.append( (F'''block{b}_project_conv/kernel:0''', F'''encoder.blocks.{hf_b}.projection.project_conv.weight''') ) rename_keys.append((F'''block{b}_project_bn/gamma:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.weight''') ) rename_keys.append((F'''block{b}_project_bn/beta:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.bias''') ) rename_keys.append( (F'''block{b}_project_bn/moving_mean:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.running_mean''') ) rename_keys.append( (F'''block{b}_project_bn/moving_variance:0''', F'''encoder.blocks.{hf_b}.projection.project_bn.running_var''') ) rename_keys.append(('top_conv/kernel:0', 'encoder.top_conv.weight') ) rename_keys.append(('top_bn/gamma:0', 'encoder.top_bn.weight') ) rename_keys.append(('top_bn/beta:0', 'encoder.top_bn.bias') ) rename_keys.append(('top_bn/moving_mean:0', 'encoder.top_bn.running_mean') ) rename_keys.append(('top_bn/moving_variance:0', 'encoder.top_bn.running_var') ) _lowercase : Optional[Any] = {} for item in rename_keys: if item[0] in original_param_names: _lowercase : str = 'efficientnet.' + item[1] _lowercase : Optional[Any] = 'classifier.weight' _lowercase : List[str] = 'classifier.bias' return key_mapping def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Optional[Any]: for key, value in tf_params.items(): if "normalization" in key: continue _lowercase : Any = key_mapping[key] if "_conv" in key and "kernel" in key: _lowercase : Optional[Any] = torch.from_numpy(lowerCamelCase_ ).permute(3 , 2 , 0 , 1 ) elif "depthwise_kernel" in key: _lowercase : Dict = torch.from_numpy(lowerCamelCase_ ).permute(2 , 3 , 0 , 1 ) elif "kernel" in key: _lowercase : Tuple = torch.from_numpy(np.transpose(lowerCamelCase_ ) ) else: _lowercase : List[str] = torch.from_numpy(lowerCamelCase_ ) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(lowerCamelCase_ ) @torch.no_grad() def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> int: _lowercase : Any = model_classes[model_name]( include_top=lowerCamelCase_ , weights='imagenet' , input_tensor=lowerCamelCase_ , input_shape=lowerCamelCase_ , pooling=lowerCamelCase_ , classes=1000 , classifier_activation='softmax' , ) _lowercase : int = original_model.trainable_variables _lowercase : Dict = original_model.non_trainable_variables _lowercase : Optional[Any] = {param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: _lowercase : int = param.numpy() _lowercase : int = list(tf_params.keys() ) # Load HuggingFace model _lowercase : int = get_efficientnet_config(lowerCamelCase_ ) _lowercase : List[str] = EfficientNetForImageClassification(lowerCamelCase_ ).eval() _lowercase : str = hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print('Converting parameters...' ) _lowercase : Optional[int] = rename_keys(lowerCamelCase_ ) replace_params(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # Initialize preprocessor and preprocess input image _lowercase : Optional[Any] = convert_image_processor(lowerCamelCase_ ) _lowercase : Optional[Any] = preprocessor(images=prepare_img() , return_tensors='pt' ) # HF model inference hf_model.eval() with torch.no_grad(): _lowercase : Any = hf_model(**lowerCamelCase_ ) _lowercase : Optional[int] = outputs.logits.detach().numpy() # Original model inference _lowercase : List[Any] = False _lowercase : List[Any] = CONFIG_MAP[model_name]['image_size'] _lowercase : int = prepare_img().resize((image_size, image_size) , resample=PIL.Image.NEAREST ) _lowercase : Optional[Any] = image.img_to_array(lowerCamelCase_ ) _lowercase : Any = np.expand_dims(lowerCamelCase_ , axis=0 ) _lowercase : Optional[int] = original_model.predict(lowerCamelCase_ ) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ), "The predicted logits are not the same." print('Model outputs match!' ) if save_model: # Create folder to save model if not os.path.isdir(lowerCamelCase_ ): os.mkdir(lowerCamelCase_ ) # Save converted model and image processor hf_model.save_pretrained(lowerCamelCase_ ) preprocessor.save_pretrained(lowerCamelCase_ ) if push_to_hub: # Push model and image processor to hub print(F'''Pushing converted {model_name} to the hub...''' ) _lowercase : str = F'''efficientnet-{model_name}''' preprocessor.push_to_hub(lowerCamelCase_ ) hf_model.push_to_hub(lowerCamelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="b0", type=str, help="Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].", ) parser.add_argument( "--pytorch_dump_folder_path", default="hf_model", type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument("--save_model", action="store_true", help="Save model to local") parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub") SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
84
1
"""simple docstring""" import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def _snake_case ( lowercase__ , lowercase__ , lowercase__ ): _lowerCamelCase : Any = AlbertConfig.from_json_file(snake_case_ ) print(f'''Building PyTorch model from configuration: {config}''' ) _lowerCamelCase : str = AlbertForPreTraining(snake_case_ ) # Load weights from tf checkpoint load_tf_weights_in_albert(snake_case_ , snake_case_ , snake_case_ ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , snake_case_ ) if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--albert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained ALBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) lowercase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
96
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case_ : list , snake_case_ : int | None = None , snake_case_ : int | None = None ) -> None: '''simple docstring''' if start is None: UpperCAmelCase_ = 0 if end is None: UpperCAmelCase_ = len(snake_case_ ) - 1 if start >= end: return UpperCAmelCase_ = (start + end) // 2 slowsort(snake_case_ , snake_case_ , snake_case_ ) slowsort(snake_case_ , mid + 1 , snake_case_ ) if sequence[end] < sequence[mid]: UpperCAmelCase_ , UpperCAmelCase_ = sequence[mid], sequence[end] slowsort(snake_case_ , snake_case_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
1
0
def _snake_case ( UpperCamelCase : list , UpperCamelCase : list ): _validate_point(UpperCamelCase ) _validate_point(UpperCamelCase ) if len(UpperCamelCase ) != len(UpperCamelCase ): raise ValueError("""Both points must be in the same n-dimensional space""" ) return float(sum(abs(a - b ) for a, b in zip(UpperCamelCase , UpperCamelCase ) ) ) def _snake_case ( UpperCamelCase : list[float] ): if point: if isinstance(UpperCamelCase , UpperCamelCase ): for item in point: if not isinstance(UpperCamelCase , (int, float) ): UpperCAmelCase : Any = ( """Expected a list of numbers as input, found """ F"{type(UpperCamelCase ).__name__}" ) raise TypeError(UpperCamelCase ) else: UpperCAmelCase : int = F"Expected a list of numbers as input, found {type(UpperCamelCase ).__name__}" raise TypeError(UpperCamelCase ) else: raise ValueError("""Missing an input""" ) def _snake_case ( UpperCamelCase : list , UpperCamelCase : list ): _validate_point(UpperCamelCase ) _validate_point(UpperCamelCase ) if len(UpperCamelCase ) != len(UpperCamelCase ): raise ValueError("""Both points must be in the same n-dimensional space""" ) return float(sum(abs(x - y ) for x, y in zip(UpperCamelCase , UpperCamelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
354
"""simple docstring""" from typing import List from .keymap import KEYMAP, get_character def _snake_case ( UpperCamelCase : str ): def decorator(UpperCamelCase : Optional[int] ): UpperCAmelCase : List[Any] = getattr(UpperCamelCase , """handle_key""" , [] ) handle += [key] setattr(UpperCamelCase , """handle_key""" , UpperCamelCase ) return func return decorator def _snake_case ( *UpperCamelCase : List[str] ): def decorator(UpperCamelCase : Union[str, Any] ): UpperCAmelCase : Optional[Any] = getattr(UpperCamelCase , """handle_key""" , [] ) handle += keys setattr(UpperCamelCase , """handle_key""" , UpperCamelCase ) return func return decorator class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): def __new__( cls , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' UpperCAmelCase : List[Any] = super().__new__(cls , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not hasattr(_SCREAMING_SNAKE_CASE , """key_handler""" ): setattr(_SCREAMING_SNAKE_CASE , """key_handler""" , {} ) setattr(_SCREAMING_SNAKE_CASE , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): UpperCAmelCase : List[str] = getattr(_SCREAMING_SNAKE_CASE , """handle_key""" , [] ) for key in handled_keys: UpperCAmelCase : Optional[int] = value return new_cls @staticmethod def SCREAMING_SNAKE_CASE ( cls ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase : str = get_character() if char != KEYMAP["undefined"]: UpperCAmelCase : List[Any] = ord(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : int = cls.key_handler.get(_SCREAMING_SNAKE_CASE ) if handler: UpperCAmelCase : int = char return handler(cls ) else: return None def _snake_case ( cls : Union[str, Any] ): return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
76
0
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class a__ ( unittest.TestCase ): """simple docstring""" def _snake_case (self ): __lowerCAmelCase = get_activation('''swish''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def _snake_case (self ): __lowerCAmelCase = get_activation('''silu''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def _snake_case (self ): __lowerCAmelCase = get_activation('''mish''' ) self.assertIsInstance(_a , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def _snake_case (self ): __lowerCAmelCase = get_activation('''gelu''' ) self.assertIsInstance(_a , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
174
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class lowerCamelCase__ : '''simple docstring''' def __init__(self ,__lowerCamelCase ,__lowerCamelCase=13 ,__lowerCamelCase=2 ,__lowerCamelCase=24 ,__lowerCamelCase=16 ,__lowerCamelCase=True ,__lowerCamelCase=True ,__lowerCamelCase=32 ,__lowerCamelCase=5 ,__lowerCamelCase=4 ,__lowerCamelCase=37 ,__lowerCamelCase="gelu" ,__lowerCamelCase=0.1 ,__lowerCamelCase=0.1 ,__lowerCamelCase=10 ,__lowerCamelCase=0.02 ,__lowerCamelCase=None ,__lowerCamelCase=2 ,__lowerCamelCase=2 ,) -> Dict: """simple docstring""" lowerCAmelCase__ : Tuple = parent lowerCAmelCase__ : Union[str, Any] = batch_size lowerCAmelCase__ : Tuple = patch_size lowerCAmelCase__ : str = max_length lowerCAmelCase__ : Union[str, Any] = num_mel_bins lowerCAmelCase__ : Union[str, Any] = is_training lowerCAmelCase__ : Union[str, Any] = use_labels lowerCAmelCase__ : List[str] = hidden_size lowerCAmelCase__ : List[Any] = num_hidden_layers lowerCAmelCase__ : Dict = num_attention_heads lowerCAmelCase__ : int = intermediate_size lowerCAmelCase__ : Optional[int] = hidden_act lowerCAmelCase__ : Optional[int] = hidden_dropout_prob lowerCAmelCase__ : Tuple = attention_probs_dropout_prob lowerCAmelCase__ : Optional[int] = type_sequence_label_size lowerCAmelCase__ : Any = initializer_range lowerCAmelCase__ : Optional[int] = scope lowerCAmelCase__ : Union[str, Any] = frequency_stride lowerCAmelCase__ : Union[str, Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) lowerCAmelCase__ : Dict = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 lowerCAmelCase__ : Tuple = (self.max_length - self.patch_size) // self.time_stride + 1 lowerCAmelCase__ : List[Any] = frequency_out_dimension * time_out_dimension lowerCAmelCase__ : Dict = num_patches + 2 def lowerCAmelCase__ (self ) -> int: """simple docstring""" lowerCAmelCase__ : int = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) lowerCAmelCase__ : Tuple = None if self.use_labels: lowerCAmelCase__ : Union[str, Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) lowerCAmelCase__ : str = self.get_config() return config, input_values, labels def lowerCAmelCase__ (self ) -> List[str]: """simple docstring""" return ASTConfig( patch_size=self.patch_size ,max_length=self.max_length ,num_mel_bins=self.num_mel_bins ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=__lowerCamelCase ,initializer_range=self.initializer_range ,frequency_stride=self.frequency_stride ,time_stride=self.time_stride ,) def lowerCAmelCase__ (self ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) -> Optional[int]: """simple docstring""" lowerCAmelCase__ : Union[str, Any] = ASTModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() lowerCAmelCase__ : Any = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__ (self ) -> int: """simple docstring""" lowerCAmelCase__ : List[str] = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) : Dict = config_and_inputs lowerCAmelCase__ : List[Any] = {'''input_values''': input_values} return config, inputs_dict @require_torch class lowerCamelCase__ ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase): '''simple docstring''' snake_case_ =( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) snake_case_ =( {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel} if is_torch_available() else {} ) snake_case_ =False snake_case_ =False snake_case_ =False snake_case_ =False def lowerCAmelCase__ (self ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) -> Optional[Any]: """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def lowerCAmelCase__ (self ) -> int: """simple docstring""" lowerCAmelCase__ : str = ASTModelTester(self ) lowerCAmelCase__ : Tuple = ConfigTester(self ,config_class=__lowerCamelCase ,has_text_modality=__lowerCamelCase ,hidden_size=37 ) def lowerCAmelCase__ (self ) -> int: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def lowerCAmelCase__ (self ) -> List[str]: """simple docstring""" pass def lowerCAmelCase__ (self ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ : Optional[Any] = model_class(__lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) lowerCAmelCase__ : Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCamelCase ,nn.Linear ) ) def lowerCAmelCase__ (self ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ : Optional[Any] = model_class(__lowerCamelCase ) lowerCAmelCase__ : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ : Optional[Any] = [*signature.parameters.keys()] lowerCAmelCase__ : Optional[int] = ['''input_values'''] self.assertListEqual(arg_names[:1] ,__lowerCamelCase ) def lowerCAmelCase__ (self ) -> Dict: """simple docstring""" lowerCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) @slow def lowerCAmelCase__ (self ) -> Union[str, Any]: """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ : Optional[int] = ASTModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : int = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' ,filename='''sample_audio.flac''' ,repo_type='''dataset''') lowerCAmelCase__ , lowerCAmelCase__ : int = torchaudio.load(lowerCamelCase_) return audio, sampling_rate @require_torch @require_torchaudio class lowerCamelCase__ ( unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase__ (self ) -> Union[str, Any]: """simple docstring""" return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def lowerCAmelCase__ (self ) -> Optional[int]: """simple docstring""" lowerCAmelCase__ : int = self.default_feature_extractor lowerCAmelCase__ : List[str] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(__lowerCamelCase ) lowerCAmelCase__ : List[str] = self.default_feature_extractor lowerCAmelCase__ , lowerCAmelCase__ : int = prepare_audio() lowerCAmelCase__ : Optional[int] = audio.squeeze().numpy() lowerCAmelCase__ : List[Any] = feature_extractor(__lowerCamelCase ,sampling_rate=__lowerCamelCase ,return_tensors='''pt''' ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): lowerCAmelCase__ : str = model(**__lowerCamelCase ) # verify the logits lowerCAmelCase__ : Union[str, Any] = torch.Size((1, 5_27) ) self.assertEqual(outputs.logits.shape ,__lowerCamelCase ) lowerCAmelCase__ : List[str] = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,__lowerCamelCase ,atol=1e-4 ) )
94
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase__ ( lowerCamelCase_ : int ,lowerCamelCase_ : Optional[Any] ,lowerCamelCase_ : Optional[int] ,lowerCamelCase_ : Optional[int] ,lowerCamelCase_ : Any=True ,lowerCamelCase_ : Tuple="pt"): '''simple docstring''' lowerCAmelCase__ : Tuple = {'''add_prefix_space''': True} if isinstance(lowerCamelCase_ ,lowerCamelCase_) and not line.startswith(''' ''') else {} lowerCAmelCase__ : Union[str, Any] = padding_side return tokenizer( [line] ,max_length=lowerCamelCase_ ,padding='''max_length''' if pad_to_max_length else None ,truncation=lowerCamelCase_ ,return_tensors=lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ,**lowerCamelCase_ ,) def lowerCAmelCase__ ( lowerCamelCase_ : Optional[int] ,lowerCamelCase_ : Dict ,lowerCamelCase_ : Any=None ,): '''simple docstring''' lowerCAmelCase__ : List[Any] = input_ids.ne(lowerCamelCase_).any(dim=0) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class lowerCamelCase__ ( lowerCamelCase__): '''simple docstring''' def __init__(self ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase="train" ,__lowerCamelCase=None ,__lowerCamelCase=None ,__lowerCamelCase=None ,__lowerCamelCase="" ,) -> List[str]: """simple docstring""" super().__init__() lowerCAmelCase__ : str = Path(__lowerCamelCase ).joinpath(type_path + '''.source''' ) lowerCAmelCase__ : int = Path(__lowerCamelCase ).joinpath(type_path + '''.target''' ) lowerCAmelCase__ : Tuple = self.get_char_lens(self.src_file ) lowerCAmelCase__ : Dict = max_source_length lowerCAmelCase__ : Optional[int] = max_target_length assert min(self.src_lens ) > 0, f"""found empty line in {self.src_file}""" lowerCAmelCase__ : Tuple = tokenizer lowerCAmelCase__ : List[Any] = prefix if n_obs is not None: lowerCAmelCase__ : Optional[Any] = self.src_lens[:n_obs] lowerCAmelCase__ : Any = src_lang lowerCAmelCase__ : Optional[Any] = tgt_lang def __len__(self ) -> str: """simple docstring""" return len(self.src_lens ) def __getitem__(self ,__lowerCamelCase ) -> Dict[str, torch.Tensor]: """simple docstring""" lowerCAmelCase__ : List[Any] = index + 1 # linecache starts at 1 lowerCAmelCase__ : Any = self.prefix + linecache.getline(str(self.src_file ) ,__lowerCamelCase ).rstrip('''\n''' ) lowerCAmelCase__ : Any = linecache.getline(str(self.tgt_file ) ,__lowerCamelCase ).rstrip('''\n''' ) assert source_line, f"""empty source line for index {index}""" assert tgt_line, f"""empty tgt line for index {index}""" # Need to add eos token manually for T5 if isinstance(self.tokenizer ,__lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right lowerCAmelCase__ : List[str] = ( self.tokenizer.question_encoder if isinstance(self.tokenizer ,__lowerCamelCase ) else self.tokenizer ) lowerCAmelCase__ : Dict = self.tokenizer.generator if isinstance(self.tokenizer ,__lowerCamelCase ) else self.tokenizer lowerCAmelCase__ : Union[str, Any] = encode_line(__lowerCamelCase ,__lowerCamelCase ,self.max_source_length ,'''right''' ) lowerCAmelCase__ : Any = encode_line(__lowerCamelCase ,__lowerCamelCase ,self.max_target_length ,'''right''' ) lowerCAmelCase__ : List[str] = source_inputs['''input_ids'''].squeeze() lowerCAmelCase__ : str = target_inputs['''input_ids'''].squeeze() lowerCAmelCase__ : Tuple = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowerCAmelCase__ (__lowerCamelCase ) -> List[str]: """simple docstring""" return [len(__lowerCamelCase ) for x in Path(__lowerCamelCase ).open().readlines()] def lowerCAmelCase__ (self ,__lowerCamelCase ) -> Dict[str, torch.Tensor]: """simple docstring""" lowerCAmelCase__ : Union[str, Any] = torch.stack([x['''input_ids'''] for x in batch] ) lowerCAmelCase__ : Union[str, Any] = torch.stack([x['''attention_mask'''] for x in batch] ) lowerCAmelCase__ : List[Any] = torch.stack([x['''decoder_input_ids'''] for x in batch] ) lowerCAmelCase__ : Any = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer ,__lowerCamelCase ) else self.tokenizer.pad_token_id ) lowerCAmelCase__ : Tuple = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer ,__lowerCamelCase ) else self.tokenizer.pad_token_id ) lowerCAmelCase__ : Dict = trim_batch(__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ , lowerCAmelCase__ : Union[str, Any] = trim_batch(__lowerCamelCase ,__lowerCamelCase ,attention_mask=__lowerCamelCase ) lowerCAmelCase__ : Union[str, Any] = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch __snake_case : Any =getLogger(__name__) def lowerCAmelCase__ ( lowerCamelCase_ : List[List]): '''simple docstring''' return list(itertools.chain.from_iterable(lowerCamelCase_)) def lowerCAmelCase__ ( lowerCamelCase_ : str): '''simple docstring''' lowerCAmelCase__ : int = get_git_info() save_json(lowerCamelCase_ ,os.path.join(lowerCamelCase_ ,'''git_log.json''')) def lowerCAmelCase__ ( lowerCamelCase_ : Tuple ,lowerCamelCase_ : Union[str, Any] ,lowerCamelCase_ : Tuple=4 ,**lowerCamelCase_ : List[str]): '''simple docstring''' with open(lowerCamelCase_ ,'''w''') as f: json.dump(lowerCamelCase_ ,lowerCamelCase_ ,indent=lowerCamelCase_ ,**lowerCamelCase_) def lowerCAmelCase__ ( lowerCamelCase_ : Tuple): '''simple docstring''' with open(lowerCamelCase_) as f: return json.load(lowerCamelCase_) def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : str = git.Repo(search_parent_directories=lowerCamelCase_) lowerCAmelCase__ : List[Any] = { '''repo_id''': str(lowerCamelCase_), '''repo_sha''': str(repo.head.object.hexsha), '''repo_branch''': str(repo.active_branch), '''hostname''': str(socket.gethostname()), } return repo_infos def lowerCAmelCase__ ( lowerCamelCase_ : Callable ,lowerCamelCase_ : Iterable): '''simple docstring''' return list(map(lowerCamelCase_ ,lowerCamelCase_)) def lowerCAmelCase__ ( lowerCamelCase_ : Any ,lowerCamelCase_ : Optional[Any]): '''simple docstring''' with open(lowerCamelCase_ ,'''wb''') as f: return pickle.dump(lowerCamelCase_ ,lowerCamelCase_) def lowerCAmelCase__ ( lowerCamelCase_ : int): '''simple docstring''' def remove_articles(lowerCamelCase_ : List[str]): return re.sub(r'''\b(a|an|the)\b''' ,''' ''' ,lowerCamelCase_) def white_space_fix(lowerCamelCase_ : Optional[int]): return " ".join(text.split()) def remove_punc(lowerCamelCase_ : List[str]): lowerCAmelCase__ : List[Any] = set(string.punctuation) return "".join(ch for ch in text if ch not in exclude) def lower(lowerCamelCase_ : Optional[int]): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase_)))) def lowerCAmelCase__ ( lowerCamelCase_ : List[Any] ,lowerCamelCase_ : Optional[int]): '''simple docstring''' lowerCAmelCase__ : Optional[Any] = normalize_answer(lowerCamelCase_).split() lowerCAmelCase__ : str = normalize_answer(lowerCamelCase_).split() lowerCAmelCase__ : str = Counter(lowerCamelCase_) & Counter(lowerCamelCase_) lowerCAmelCase__ : Dict = sum(common.values()) if num_same == 0: return 0 lowerCAmelCase__ : Optional[int] = 1.0 * num_same / len(lowerCamelCase_) lowerCAmelCase__ : Optional[Any] = 1.0 * num_same / len(lowerCamelCase_) lowerCAmelCase__ : Optional[Any] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase__ ( lowerCamelCase_ : Union[str, Any] ,lowerCamelCase_ : Any): '''simple docstring''' return normalize_answer(lowerCamelCase_) == normalize_answer(lowerCamelCase_) def lowerCAmelCase__ ( lowerCamelCase_ : List[str] ,lowerCamelCase_ : List[str]): '''simple docstring''' assert len(lowerCamelCase_) == len(lowerCamelCase_) lowerCAmelCase__ : List[str] = 0 for hypo, pred in zip(lowerCamelCase_ ,lowerCamelCase_): em += exact_match_score(lowerCamelCase_ ,lowerCamelCase_) if len(lowerCamelCase_) > 0: em /= len(lowerCamelCase_) return {"em": em} def lowerCAmelCase__ ( lowerCamelCase_ : int): '''simple docstring''' return model_prefix.startswith('''rag''') def lowerCAmelCase__ ( lowerCamelCase_ : List[str] ,lowerCamelCase_ : Dict ,lowerCamelCase_ : str): '''simple docstring''' lowerCAmelCase__ : Any = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead lowerCAmelCase__ : Optional[int] = '''dropout_rate''' for p in extra_params: if getattr(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_): if not hasattr(lowerCamelCase_ ,lowerCamelCase_) and not hasattr(lowerCamelCase_ ,equivalent_param[p]): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowerCamelCase_)) delattr(lowerCamelCase_ ,lowerCamelCase_) continue lowerCAmelCase__ : Dict = p if hasattr(lowerCamelCase_ ,lowerCamelCase_) else equivalent_param[p] setattr(lowerCamelCase_ ,lowerCamelCase_ ,getattr(lowerCamelCase_ ,lowerCamelCase_)) delattr(lowerCamelCase_ ,lowerCamelCase_) return hparams, config
94
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) UpperCAmelCase_ : List[str] = { 'configuration_mobilevit': ['MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileViTConfig', 'MobileViTOnnxConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Union[str, Any] = ['MobileViTFeatureExtractor'] UpperCAmelCase_ : int = ['MobileViTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Optional[Any] = [ 'MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MobileViTForImageClassification', 'MobileViTForSemanticSegmentation', 'MobileViTModel', 'MobileViTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = [ 'TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFMobileViTForImageClassification', 'TFMobileViTForSemanticSegmentation', 'TFMobileViTModel', 'TFMobileViTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys UpperCAmelCase_ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
32
'''simple docstring''' from __future__ import annotations import unittest from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel @require_tf class __a : __a : int = BlenderbotConfig __a : Any = {} __a : str = "gelu" def __init__( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : Optional[Any]=13 , __magic_name__ : Any=7 , __magic_name__ : Optional[Any]=True , __magic_name__ : str=False , __magic_name__ : Any=99 , __magic_name__ : List[Any]=32 , __magic_name__ : Union[str, Any]=2 , __magic_name__ : List[Any]=4 , __magic_name__ : List[str]=37 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : Optional[int]=0.1 , __magic_name__ : List[str]=20 , __magic_name__ : List[str]=2 , __magic_name__ : Any=1 , __magic_name__ : Union[str, Any]=0 , ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : str = parent UpperCAmelCase_ : Dict = batch_size UpperCAmelCase_ : Union[str, Any] = seq_length UpperCAmelCase_ : int = is_training UpperCAmelCase_ : Tuple = use_labels UpperCAmelCase_ : Tuple = vocab_size UpperCAmelCase_ : Union[str, Any] = hidden_size UpperCAmelCase_ : Dict = num_hidden_layers UpperCAmelCase_ : Dict = num_attention_heads UpperCAmelCase_ : Optional[Any] = intermediate_size UpperCAmelCase_ : int = hidden_dropout_prob UpperCAmelCase_ : Dict = attention_probs_dropout_prob UpperCAmelCase_ : Optional[Any] = max_position_embeddings UpperCAmelCase_ : List[Any] = eos_token_id UpperCAmelCase_ : Union[str, Any] = pad_token_id UpperCAmelCase_ : Tuple = bos_token_id def UpperCAmelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" UpperCAmelCase_ : Any = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCAmelCase_ : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCAmelCase_ : str = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCAmelCase_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : Any = self.config_cls( 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_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) UpperCAmelCase_ : str = prepare_blenderbot_inputs_dict(__magic_name__ , __magic_name__ , __magic_name__ ) return config, inputs_dict def UpperCAmelCase__ ( self : str , __magic_name__ : Optional[int] , __magic_name__ : Dict ) -> Tuple: """simple docstring""" UpperCAmelCase_ : List[Any] = TFBlenderbotModel(config=__magic_name__ ).get_decoder() UpperCAmelCase_ : Union[str, Any] = inputs_dict['''input_ids'''] UpperCAmelCase_ : Any = input_ids[:1, :] UpperCAmelCase_ : Tuple = inputs_dict['''attention_mask'''][:1, :] UpperCAmelCase_ : List[str] = inputs_dict['''head_mask'''] UpperCAmelCase_ : Any = 1 # first forward pass UpperCAmelCase_ : Dict = model(__magic_name__ , attention_mask=__magic_name__ , head_mask=__magic_name__ , use_cache=__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ : int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase_ : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase_ : str = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCAmelCase_ : List[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCAmelCase_ : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCAmelCase_ : List[Any] = model(__magic_name__ , attention_mask=__magic_name__ )[0] UpperCAmelCase_ : str = model(__magic_name__ , attention_mask=__magic_name__ , past_key_values=__magic_name__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCAmelCase_ : Union[str, Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCAmelCase_ : Any = output_from_no_past[:, -3:, random_slice_idx] UpperCAmelCase_ : Optional[int] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__magic_name__ , __magic_name__ , rtol=1E-3 ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : Optional[int]=None, SCREAMING_SNAKE_CASE__ : Optional[int]=None, SCREAMING_SNAKE_CASE__ : Optional[int]=None, SCREAMING_SNAKE_CASE__ : Tuple=None, SCREAMING_SNAKE_CASE__ : Any=None, ) -> Any: if attention_mask is None: UpperCAmelCase_ : List[str] = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE__, config.pad_token_id ), tf.inta ) if decoder_attention_mask is None: UpperCAmelCase_ : List[str] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id ), tf.inta ), ], axis=-1, ) if head_mask is None: UpperCAmelCase_ : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase_ : Dict = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCAmelCase_ : Tuple = tf.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": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class __a (lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : Tuple = (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else () __a : Tuple = (TFBlenderbotForConditionalGeneration,) if is_tf_available() else () __a : List[str] = ( { "conversational": TFBlenderbotForConditionalGeneration, "feature-extraction": TFBlenderbotModel, "summarization": TFBlenderbotForConditionalGeneration, "text2text-generation": TFBlenderbotForConditionalGeneration, "translation": TFBlenderbotForConditionalGeneration, } if is_tf_available() else {} ) __a : List[str] = True __a : Any = False __a : Optional[int] = False def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" UpperCAmelCase_ : Any = TFBlenderbotModelTester(self ) UpperCAmelCase_ : List[Any] = ConfigTester(self , config_class=__magic_name__ ) def UpperCAmelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__magic_name__ ) @require_tokenizers @require_tf class __a (unittest.TestCase ): __a : Union[str, Any] = ["My friends are cool but they eat too many carbs."] __a : List[Any] = "facebook/blenderbot-400M-distill" @cached_property def UpperCAmelCase__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" return BlenderbotTokenizer.from_pretrained(self.model_name ) @cached_property def UpperCAmelCase__ ( self : Tuple ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Optional[int] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def UpperCAmelCase__ ( self : Any ) -> Dict: """simple docstring""" UpperCAmelCase_ : List[Any] = self.tokenizer(self.src_text , return_tensors='''tf''' ) UpperCAmelCase_ : List[Any] = self.model.generate( model_inputs.input_ids , ) UpperCAmelCase_ : List[Any] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__magic_name__ )[0] assert ( generated_words == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?" )
125
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class __UpperCAmelCase : '''simple docstring''' __lowerCAmelCase = PegasusConfig __lowerCAmelCase = {} __lowerCAmelCase = '''gelu''' def __init__(self : Union[str, Any] , _lowerCAmelCase : List[str] , _lowerCAmelCase : Union[str, Any]=13 , _lowerCAmelCase : Dict=7 , _lowerCAmelCase : Tuple=True , _lowerCAmelCase : List[Any]=False , _lowerCAmelCase : List[Any]=99 , _lowerCAmelCase : List[str]=32 , _lowerCAmelCase : str=2 , _lowerCAmelCase : str=4 , _lowerCAmelCase : Dict=37 , _lowerCAmelCase : List[Any]=0.1 , _lowerCAmelCase : List[Any]=0.1 , _lowerCAmelCase : Union[str, Any]=40 , _lowerCAmelCase : Tuple=2 , _lowerCAmelCase : Tuple=1 , _lowerCAmelCase : int=0 , ): A = parent A = batch_size A = seq_length A = is_training A = use_labels A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = eos_token_id A = pad_token_id A = bos_token_id def A (self : List[str] ): A = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A = tf.concat([input_ids, eos_tensor] , axis=1 ) A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A = self.config_cls( 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_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) A = prepare_pegasus_inputs_dict(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) return config, inputs_dict def A (self : List[str] , _lowerCAmelCase : str , _lowerCAmelCase : Union[str, Any] ): A = TFPegasusModel(config=_lowerCAmelCase ).get_decoder() A = inputs_dict["""input_ids"""] A = input_ids[:1, :] A = inputs_dict["""attention_mask"""][:1, :] A = inputs_dict["""head_mask"""] A = 1 # first forward pass A = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase , head_mask=_lowerCAmelCase , use_cache=_lowerCAmelCase ) A , A = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A = ids_tensor((self.batch_size, 3) , config.vocab_size ) A = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A = tf.concat([input_ids, next_tokens] , axis=-1 ) A = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase )[0] A = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase , past_key_values=_lowerCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A = output_from_no_past[:, -3:, random_slice_idx] A = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_lowerCAmelCase , _lowerCAmelCase , rtol=1e-3 ) def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , ) ->Tuple: """simple docstring""" if attention_mask is None: A = tf.cast(tf.math.not_equal(UpperCAmelCase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: A = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A = tf.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": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class __UpperCAmelCase ( A__ , A__ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () __lowerCAmelCase = (TFPegasusForConditionalGeneration,) if is_tf_available() else () __lowerCAmelCase = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) __lowerCAmelCase = True __lowerCAmelCase = False __lowerCAmelCase = False def A (self : Tuple ): A = TFPegasusModelTester(self ) A = ConfigTester(self , config_class=_lowerCAmelCase ) def A (self : Any ): self.config_tester.run_common_tests() def A (self : Dict ): A = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_lowerCAmelCase ) @require_sentencepiece @require_tokenizers @require_tf class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] __lowerCAmelCase = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers __lowerCAmelCase = '''google/pegasus-xsum''' @cached_property def A (self : Any ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def A (self : List[Any] ): A = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def A (self : Any , **_lowerCAmelCase : Tuple ): A = self.translate_src_text(**_lowerCAmelCase ) assert self.expected_text == generated_words def A (self : Dict , **_lowerCAmelCase : Tuple ): A = self.tokenizer(self.src_text , **_lowerCAmelCase , padding=_lowerCAmelCase , return_tensors="""tf""" ) A = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=_lowerCAmelCase , ) A = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=_lowerCAmelCase ) return generated_words @slow def A (self : str ): self._assert_generated_batch_equal_expected()
371
'''simple docstring''' from ..utils import DummyObject, requires_backends class __UpperCAmelCase ( metaclass=A__ ): '''simple docstring''' __lowerCAmelCase = ['''torch''', '''transformers''', '''onnx'''] def __init__(self : Tuple , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Dict ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : Optional[int] , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : Any ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : List[str] , *_lowerCAmelCase : Dict , **_lowerCAmelCase : str ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __UpperCAmelCase ( metaclass=A__ ): '''simple docstring''' __lowerCAmelCase = ['''torch''', '''transformers''', '''onnx'''] def __init__(self : List[str] , *_lowerCAmelCase : Dict , **_lowerCAmelCase : int ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : List[Any] , *_lowerCAmelCase : str , **_lowerCAmelCase : str ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : List[str] , *_lowerCAmelCase : Optional[int] , **_lowerCAmelCase : List[Any] ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __UpperCAmelCase ( metaclass=A__ ): '''simple docstring''' __lowerCAmelCase = ['''torch''', '''transformers''', '''onnx'''] def __init__(self : Union[str, Any] , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : int ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : Any , *_lowerCAmelCase : str , **_lowerCAmelCase : Union[str, Any] ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : List[Any] , *_lowerCAmelCase : Dict , **_lowerCAmelCase : Union[str, Any] ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __UpperCAmelCase ( metaclass=A__ ): '''simple docstring''' __lowerCAmelCase = ['''torch''', '''transformers''', '''onnx'''] def __init__(self : List[str] , *_lowerCAmelCase : Dict , **_lowerCAmelCase : Any ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : Optional[int] , *_lowerCAmelCase : Dict , **_lowerCAmelCase : Dict ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : Union[str, Any] , *_lowerCAmelCase : str , **_lowerCAmelCase : List[str] ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __UpperCAmelCase ( metaclass=A__ ): '''simple docstring''' __lowerCAmelCase = ['''torch''', '''transformers''', '''onnx'''] def __init__(self : Union[str, Any] , *_lowerCAmelCase : Any , **_lowerCAmelCase : str ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : Optional[Any] , *_lowerCAmelCase : int , **_lowerCAmelCase : Any ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : Dict , *_lowerCAmelCase : Optional[Any] , **_lowerCAmelCase : int ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __UpperCAmelCase ( metaclass=A__ ): '''simple docstring''' __lowerCAmelCase = ['''torch''', '''transformers''', '''onnx'''] def __init__(self : Dict , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : Optional[int] ): requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : Dict , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : Any ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def A (cls : Optional[Any] , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : Tuple ): requires_backends(cls , ["""torch""", """transformers""", """onnx"""] )
337
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor lowercase__ : Dict = logging.get_logger(__name__) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Dict , *SCREAMING_SNAKE_CASE_ : Union[str, Any] , **SCREAMING_SNAKE_CASE_ : Dict ): warnings.warn( 'The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DonutImageProcessor instead.' , __UpperCamelCase , ) super().__init__(*__UpperCamelCase , **__UpperCamelCase )
224
"""simple docstring""" from __future__ import annotations import math from collections.abc import Callable def lowercase__( __SCREAMING_SNAKE_CASE : Callable[[int | float], int | float] , __SCREAMING_SNAKE_CASE : int | float , __SCREAMING_SNAKE_CASE : int | float , __SCREAMING_SNAKE_CASE : int = 1_00 , ): lowercase_ : Dict = x_start lowercase_ : Optional[Any] = fnc(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = 0.0 for _ in range(__SCREAMING_SNAKE_CASE ): # Approximates curve as a sequence of linear lines and sums their length lowercase_ : Union[str, Any] = (x_end - x_start) / steps + xa lowercase_ : str = fnc(__SCREAMING_SNAKE_CASE ) length += math.hypot(xa - xa , fxa - fxa ) # Increment step lowercase_ : List[Any] = xa lowercase_ : Optional[Any] = fxa return length if __name__ == "__main__": def lowercase__( __SCREAMING_SNAKE_CASE : Any ): return math.sin(10 * x ) print("f(x) = sin(10 * x)") print("The length of the curve from x = -10 to x = 10 is:") __SCREAMING_SNAKE_CASE =10 while i <= 10_0000: print(F"With {i} steps: {line_length(f, -10, 10, i)}") i *= 10
213
0
import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class A : '''simple docstring''' @staticmethod def a_ ( *__lowerCAmelCase : Dict , **__lowerCAmelCase : Optional[Any] ) -> Tuple: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class A (unittest.TestCase ): '''simple docstring''' __lowerCamelCase : Optional[Any] = MODEL_FOR_OBJECT_DETECTION_MAPPING def a_ ( self : str , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : int ) -> List[str]: """simple docstring""" A__ = ObjectDetectionPipeline(model=__lowerCAmelCase , image_processor=__lowerCAmelCase ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def a_ ( self : List[str] , __lowerCAmelCase : Any , __lowerCAmelCase : str ) -> Optional[Any]: """simple docstring""" A__ = object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(__lowerCAmelCase ) , 0 ) for detected_object in outputs: self.assertEqual( __lowerCAmelCase , { """score""": ANY(__lowerCAmelCase ), """label""": ANY(__lowerCAmelCase ), """box""": {"""xmin""": ANY(__lowerCAmelCase ), """ymin""": ANY(__lowerCAmelCase ), """xmax""": ANY(__lowerCAmelCase ), """ymax""": ANY(__lowerCAmelCase )}, } , ) import datasets A__ = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) A__ = [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] A__ = object_detector(__lowerCAmelCase , threshold=0.0 ) self.assertEqual(len(__lowerCAmelCase ) , len(__lowerCAmelCase ) ) for outputs in batch_outputs: self.assertGreater(len(__lowerCAmelCase ) , 0 ) for detected_object in outputs: self.assertEqual( __lowerCAmelCase , { """score""": ANY(__lowerCAmelCase ), """label""": ANY(__lowerCAmelCase ), """box""": {"""xmin""": ANY(__lowerCAmelCase ), """ymin""": ANY(__lowerCAmelCase ), """xmax""": ANY(__lowerCAmelCase ), """ymax""": ANY(__lowerCAmelCase )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def a_ ( self : Dict ) -> int: """simple docstring""" pass @require_torch def a_ ( self : Optional[Any] ) -> str: """simple docstring""" A__ = """hf-internal-testing/tiny-detr-mobilenetsv3""" A__ = AutoModelForObjectDetection.from_pretrained(__lowerCAmelCase ) A__ = AutoFeatureExtractor.from_pretrained(__lowerCAmelCase ) A__ = ObjectDetectionPipeline(model=__lowerCAmelCase , feature_extractor=__lowerCAmelCase ) A__ = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, ] , ) A__ = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, ], [ {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, {"""score""": 0.3_3_7_6, """label""": """LABEL_0""", """box""": {"""xmin""": 1_59, """ymin""": 1_20, """xmax""": 4_80, """ymax""": 3_59}}, ], ] , ) @require_torch @slow def a_ ( self : Any ) -> int: """simple docstring""" A__ = """facebook/detr-resnet-50""" A__ = AutoModelForObjectDetection.from_pretrained(__lowerCAmelCase ) A__ = AutoFeatureExtractor.from_pretrained(__lowerCAmelCase ) A__ = ObjectDetectionPipeline(model=__lowerCAmelCase , feature_extractor=__lowerCAmelCase ) A__ = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ] , ) A__ = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ], [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ], ] , ) @require_torch @slow def a_ ( self : Dict ) -> Any: """simple docstring""" A__ = """facebook/detr-resnet-50""" A__ = pipeline("""object-detection""" , model=__lowerCAmelCase ) A__ = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ] , ) A__ = object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ], [ {"""score""": 0.9_9_8_2, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 70, """xmax""": 1_75, """ymax""": 1_17}}, {"""score""": 0.9_9_6_0, """label""": """remote""", """box""": {"""xmin""": 3_33, """ymin""": 72, """xmax""": 3_68, """ymax""": 1_87}}, {"""score""": 0.9_9_5_5, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_39, """ymax""": 4_73}}, {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ], ] , ) @require_torch @slow def a_ ( self : List[str] ) -> Tuple: """simple docstring""" A__ = 0.9_9_8_5 A__ = """facebook/detr-resnet-50""" A__ = pipeline("""object-detection""" , model=__lowerCAmelCase ) A__ = object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=__lowerCAmelCase ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9_9_8_8, """label""": """cat""", """box""": {"""xmin""": 13, """ymin""": 52, """xmax""": 3_14, """ymax""": 4_70}}, {"""score""": 0.9_9_8_7, """label""": """cat""", """box""": {"""xmin""": 3_45, """ymin""": 23, """xmax""": 6_40, """ymax""": 3_68}}, ] , ) @require_torch @require_pytesseract @slow def a_ ( self : List[str] ) -> Optional[int]: """simple docstring""" A__ = """Narsil/layoutlmv3-finetuned-funsd""" A__ = 0.9_9_9_3 A__ = pipeline("""object-detection""" , model=__lowerCAmelCase , threshold=__lowerCAmelCase ) A__ = object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(__lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.9_9_9_3, """label""": """I-ANSWER""", """box""": {"""xmin""": 2_94, """ymin""": 2_54, """xmax""": 3_43, """ymax""": 2_64}}, {"""score""": 0.9_9_9_3, """label""": """I-ANSWER""", """box""": {"""xmin""": 2_94, """ymin""": 2_54, """xmax""": 3_43, """ymax""": 2_64}}, ] , )
369
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A : '''simple docstring''' def __init__( self : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Tuple=13 , __lowerCAmelCase : Optional[Any]=7 , __lowerCAmelCase : List[str]=False , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : Tuple=False , __lowerCAmelCase : Any=True , __lowerCAmelCase : Union[str, Any]=33 , __lowerCAmelCase : List[str]=32 , __lowerCAmelCase : Optional[Any]=5 , __lowerCAmelCase : Dict=4 , __lowerCAmelCase : List[Any]=37 , __lowerCAmelCase : str="gelu" , __lowerCAmelCase : Any=0.1 , __lowerCAmelCase : str=0.1 , __lowerCAmelCase : List[Any]=5_12 , __lowerCAmelCase : Dict=16 , __lowerCAmelCase : Any=2 , __lowerCAmelCase : List[str]=0.0_2 , __lowerCAmelCase : Dict=3 , __lowerCAmelCase : Optional[int]=4 , __lowerCAmelCase : Tuple=None , ) -> int: """simple docstring""" A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = use_token_type_ids A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = type_vocab_size A__ = type_sequence_label_size A__ = initializer_range A__ = num_labels A__ = num_choices A__ = scope def a_ ( self : List[Any] ) -> Tuple: """simple docstring""" A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length] ) A__ = None A__ = None A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ = ids_tensor([self.batch_size] , self.num_choices ) A__ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self : Optional[int] ) -> str: """simple docstring""" return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def a_ ( self : str , __lowerCAmelCase : List[Any] , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] ) -> str: """simple docstring""" A__ = EsmModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() A__ = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase ) A__ = model(__lowerCAmelCase ) A__ = model(__lowerCAmelCase ) 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 a_ ( self : List[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Any ) -> str: """simple docstring""" A__ = EsmForMaskedLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() A__ = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : List[str] ) -> Any: """simple docstring""" A__ = self.num_labels A__ = EsmForTokenClassification(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() A__ = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self : Any ) -> Dict: """simple docstring""" A__ = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = config_and_inputs A__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : List[str] = False __lowerCamelCase : Union[str, Any] = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __lowerCamelCase : List[Any] = () __lowerCamelCase : Optional[int] = ( { '''feature-extraction''': EsmModel, '''fill-mask''': EsmForMaskedLM, '''text-classification''': EsmForSequenceClassification, '''token-classification''': EsmForTokenClassification, '''zero-shot''': EsmForSequenceClassification, } if is_torch_available() else {} ) __lowerCamelCase : Any = True def a_ ( self : Tuple ) -> Optional[int]: """simple docstring""" A__ = EsmModelTester(self ) A__ = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=37 ) def a_ ( self : Any ) -> str: """simple docstring""" self.config_tester.run_common_tests() def a_ ( self : List[str] ) -> Optional[int]: """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def a_ ( self : Optional[int] ) -> str: """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ = type self.model_tester.create_and_check_model(*__lowerCAmelCase ) def a_ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase ) def a_ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCAmelCase ) @slow def a_ ( self : Optional[int] ) -> int: """simple docstring""" for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = EsmModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def a_ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs()[0] A__ = EsmEmbeddings(config=__lowerCAmelCase ) A__ = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) A__ = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) A__ = create_position_ids_from_input_ids(__lowerCAmelCase , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(__lowerCAmelCase , __lowerCAmelCase ) ) ) def a_ ( self : List[Any] ) -> str: """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs()[0] A__ = EsmEmbeddings(config=__lowerCAmelCase ) A__ = torch.empty(2 , 4 , 30 ) A__ = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] A__ = torch.as_tensor([expected_single_positions, expected_single_positions] ) A__ = embeddings.create_position_ids_from_inputs_embeds(__lowerCAmelCase ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(__lowerCAmelCase , __lowerCAmelCase ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def a_ ( self : Dict ) -> Tuple: """simple docstring""" pass @unittest.skip("""Esm does not support embedding resizing""" ) def a_ ( self : List[str] ) -> Optional[int]: """simple docstring""" pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def a_ ( self : List[Any] ) -> Dict: """simple docstring""" pass @require_torch class A (SCREAMING_SNAKE_CASE ): '''simple docstring''' @slow def a_ ( self : int ) -> Optional[int]: """simple docstring""" with torch.no_grad(): A__ = EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() A__ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) A__ = model(__lowerCAmelCase )[0] A__ = 33 A__ = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , __lowerCAmelCase ) A__ = torch.tensor( [[[8.9_2_1_5, -1_0.5_8_9_8, -6.4_6_7_1], [-6.3_9_6_7, -1_3.9_1_1_4, -1.1_2_1_2], [-7.7_8_1_2, -1_3.9_5_1_6, -3.7_4_0_6]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __lowerCAmelCase , atol=1e-4 ) ) @slow def a_ ( self : List[str] ) -> Tuple: """simple docstring""" with torch.no_grad(): A__ = EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() A__ = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) A__ = model(__lowerCAmelCase )[0] # compare the actual values for a slice. A__ = torch.tensor( [[[0.1_4_4_4, 0.5_4_1_3, 0.3_2_4_8], [0.3_0_3_4, 0.0_0_5_3, 0.3_1_0_8], [0.3_2_2_8, -0.2_4_9_9, 0.3_4_1_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __lowerCAmelCase , atol=1e-4 ) )
276
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase__ : int = { 'configuration_ctrl': ['CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CTRLConfig'], 'tokenization_ctrl': ['CTRLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : List[str] = [ 'CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'CTRLForSequenceClassification', 'CTRLLMHeadModel', 'CTRLModel', 'CTRLPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : int = [ 'TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFCTRLForSequenceClassification', 'TFCTRLLMHeadModel', 'TFCTRLModel', 'TFCTRLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys lowerCAmelCase__ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
98
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { """transfo-xl-wt103""": """https://huggingface.co/transfo-xl-wt103/resolve/main/config.json""", } class A__ ( lowerCAmelCase__ ): lowerCAmelCase__ : Union[str, Any] = "transfo-xl" lowerCAmelCase__ : int = ["mems"] lowerCAmelCase__ : Dict = { "n_token": "vocab_size", "hidden_size": "d_model", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Optional[int] , _UpperCAmelCase : Tuple=26_77_35 , _UpperCAmelCase : Any=[2_00_00, 4_00_00, 20_00_00] , _UpperCAmelCase : Tuple=10_24 , _UpperCAmelCase : Union[str, Any]=10_24 , _UpperCAmelCase : Optional[int]=16 , _UpperCAmelCase : Tuple=64 , _UpperCAmelCase : Tuple=40_96 , _UpperCAmelCase : List[Any]=4 , _UpperCAmelCase : str=False , _UpperCAmelCase : Optional[Any]=18 , _UpperCAmelCase : int=16_00 , _UpperCAmelCase : Optional[int]=10_00 , _UpperCAmelCase : Optional[Any]=True , _UpperCAmelCase : Tuple=True , _UpperCAmelCase : Any=0 , _UpperCAmelCase : Optional[Any]=-1 , _UpperCAmelCase : List[str]=True , _UpperCAmelCase : Optional[Any]=0.1 , _UpperCAmelCase : List[str]=0.0 , _UpperCAmelCase : Optional[Any]=True , _UpperCAmelCase : int="normal" , _UpperCAmelCase : int=0.01 , _UpperCAmelCase : List[Any]=0.01 , _UpperCAmelCase : List[Any]=0.02 , _UpperCAmelCase : Optional[Any]=1e-5 , _UpperCAmelCase : Tuple=0 , **_UpperCAmelCase : List[str] , ) -> Tuple: """simple docstring""" __lowercase = vocab_size __lowercase = [] self.cutoffs.extend(_UpperCAmelCase ) if proj_share_all_but_first: __lowercase = [False] + [True] * len(self.cutoffs ) else: __lowercase = [False] + [False] * len(self.cutoffs ) __lowercase = d_model __lowercase = d_embed __lowercase = d_head __lowercase = d_inner __lowercase = div_val __lowercase = pre_lnorm __lowercase = n_layer __lowercase = n_head __lowercase = mem_len __lowercase = same_length __lowercase = attn_type __lowercase = clamp_len __lowercase = sample_softmax __lowercase = adaptive __lowercase = dropout __lowercase = dropatt __lowercase = untie_r __lowercase = init __lowercase = init_range __lowercase = proj_init_std __lowercase = init_std __lowercase = layer_norm_epsilon super().__init__(eos_token_id=_UpperCAmelCase , **_UpperCAmelCase ) @property def a__ ( self : Tuple ) -> Any: """simple docstring""" logger.info(f"""The model {self.model_type} is one of the few models that has no sequence length limit.""" ) return -1 @max_position_embeddings.setter def a__ ( self : Dict , _UpperCAmelCase : List[str] ) -> Optional[Any]: """simple docstring""" raise NotImplementedError( f"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
325
0
from __future__ import annotations from random import random from typing import Generic, TypeVar __UpperCamelCase : Any = TypeVar("KT") __UpperCamelCase : Optional[int] = TypeVar("VT") class __magic_name__ ( Generic[KT, VT]): def __init__( self : List[str] , lowerCamelCase__ : KT | str = "root" , lowerCamelCase__ : VT | None = None ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ : Optional[Any] = key UpperCamelCase__ : Optional[int] = value UpperCamelCase__ : list[Node[KT, VT]] = [] def __repr__( self : int ) -> str: '''simple docstring''' return F"Node({self.key}: {self.value})" @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: '''simple docstring''' return len(self.forward ) class __magic_name__ ( Generic[KT, VT]): def __init__( self : Union[str, Any] , lowerCamelCase__ : float = 0.5 , lowerCamelCase__ : int = 16 ) -> str: '''simple docstring''' UpperCamelCase__ : Node[KT, VT] = Node[KT, VT]() UpperCamelCase__ : Dict = 0 UpperCamelCase__ : Union[str, Any] = p UpperCamelCase__ : List[Any] = max_level def __str__( self : Optional[Any] ) -> str: '''simple docstring''' UpperCamelCase__ : Tuple = list(self ) if len(UpperCamelCase__ ) == 0: return F"SkipList(level={self.level})" UpperCamelCase__ : Any = max((len(str(UpperCamelCase__ ) ) for item in items) , default=4 ) UpperCamelCase__ : str = max(UpperCamelCase__ , 4 ) + 4 UpperCamelCase__ : int = self.head UpperCamelCase__ : Dict = [] UpperCamelCase__ : List[Any] = node.forward.copy() lines.append(F"[{node.key}]".ljust(UpperCamelCase__ , '''-''' ) + '''* ''' * len(UpperCamelCase__ ) ) lines.append(''' ''' * label_size + '''| ''' * len(UpperCamelCase__ ) ) while len(node.forward ) != 0: UpperCamelCase__ : List[str] = node.forward[0] lines.append( F"[{node.key}]".ljust(UpperCamelCase__ , '''-''' ) + ''' '''.join(str(n.key ) if n.key == node.key else '''|''' for n in forwards ) ) lines.append(''' ''' * label_size + '''| ''' * len(UpperCamelCase__ ) ) UpperCamelCase__ : Dict = node.forward lines.append('''None'''.ljust(UpperCamelCase__ ) + '''* ''' * len(UpperCamelCase__ ) ) return F"SkipList(level={self.level})\n" + "\n".join(UpperCamelCase__ ) def __iter__( self : List[Any] ) -> List[str]: '''simple docstring''' UpperCamelCase__ : Optional[int] = self.head while len(node.forward ) != 0: yield node.forward[0].key UpperCamelCase__ : Optional[Any] = node.forward[0] def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: '''simple docstring''' UpperCamelCase__ : Union[str, Any] = 1 while random() < self.p and level < self.max_level: level += 1 return level def UpperCAmelCase__ ( self : Tuple , lowerCamelCase__ : Optional[int] ) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: '''simple docstring''' UpperCamelCase__ : Union[str, Any] = [] UpperCamelCase__ : str = self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: UpperCamelCase__ : List[str] = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(UpperCamelCase__ ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def UpperCAmelCase__ ( self : Tuple , lowerCamelCase__ : KT ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ : Any = self._locate_node(UpperCamelCase__ ) if node is not None: for i, update_node in enumerate(UpperCamelCase__ ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: UpperCamelCase__ : int = node.forward[i] else: UpperCamelCase__ : Union[str, Any] = update_node.forward[:i] def UpperCAmelCase__ ( self : List[str] , lowerCamelCase__ : KT , lowerCamelCase__ : VT ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ : Dict = self._locate_node(UpperCamelCase__ ) if node is not None: UpperCamelCase__ : List[str] = value else: UpperCamelCase__ : List[str] = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , UpperCamelCase__ ): update_vector.append(self.head ) UpperCamelCase__ : Tuple = level UpperCamelCase__ : List[str] = Node(UpperCamelCase__ , UpperCamelCase__ ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(UpperCamelCase__ ) else: UpperCamelCase__ : List[Any] = new_node def UpperCAmelCase__ ( self : Optional[int] , lowerCamelCase__ : VT ) -> VT | None: '''simple docstring''' UpperCamelCase__ : int = self._locate_node(UpperCamelCase__ ) if node is not None: return node.value return None def _a ( ): """simple docstring""" UpperCamelCase__ : Optional[int] = SkipList() skip_list.insert('''Key1''' , 3 ) skip_list.insert('''Key2''' , 12 ) skip_list.insert('''Key3''' , 41 ) skip_list.insert('''Key4''' , -19 ) UpperCamelCase__ : str = skip_list.head UpperCamelCase__ : Dict = {} while node.level != 0: UpperCamelCase__ : str = node.forward[0] UpperCamelCase__ : Optional[int] = node.value assert len(SCREAMING_SNAKE_CASE__ ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def _a ( ): """simple docstring""" UpperCamelCase__ : str = SkipList() skip_list.insert('''Key1''' , 10 ) skip_list.insert('''Key1''' , 12 ) skip_list.insert('''Key5''' , 7 ) skip_list.insert('''Key7''' , 10 ) skip_list.insert('''Key10''' , 5 ) skip_list.insert('''Key7''' , 7 ) skip_list.insert('''Key5''' , 5 ) skip_list.insert('''Key10''' , 10 ) UpperCamelCase__ : Optional[int] = skip_list.head UpperCamelCase__ : int = {} while node.level != 0: UpperCamelCase__ : Tuple = node.forward[0] UpperCamelCase__ : Tuple = node.value if len(SCREAMING_SNAKE_CASE__ ) != 4: print() assert len(SCREAMING_SNAKE_CASE__ ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def _a ( ): """simple docstring""" UpperCamelCase__ : Optional[Any] = SkipList() assert skip_list.find('''Some key''' ) is None def _a ( ): """simple docstring""" UpperCamelCase__ : Optional[int] = SkipList() skip_list.insert('''Key2''' , 20 ) assert skip_list.find('''Key2''' ) == 20 skip_list.insert('''Some Key''' , 10 ) skip_list.insert('''Key2''' , 8 ) skip_list.insert('''V''' , 13 ) assert skip_list.find('''Y''' ) is None assert skip_list.find('''Key2''' ) == 8 assert skip_list.find('''Some Key''' ) == 10 assert skip_list.find('''V''' ) == 13 def _a ( ): """simple docstring""" UpperCamelCase__ : List[str] = SkipList() skip_list.delete('''Some key''' ) assert len(skip_list.head.forward ) == 0 def _a ( ): """simple docstring""" UpperCamelCase__ : int = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 14 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''V''' ) skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''Key2''' ) is None def _a ( ): """simple docstring""" UpperCamelCase__ : List[Any] = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 14 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''V''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) == 14 assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''X''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key1''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) is None def _a ( ): """simple docstring""" UpperCamelCase__ : List[Any] = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 142 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''X''' ) def traverse_keys(SCREAMING_SNAKE_CASE : List[str] ): yield node.key for forward_node in node.forward: yield from traverse_keys(SCREAMING_SNAKE_CASE__ ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def _a ( ): """simple docstring""" def is_sorted(SCREAMING_SNAKE_CASE : Optional[int] ): return all(next_item >= item for item, next_item in zip(SCREAMING_SNAKE_CASE__ , lst[1:] ) ) UpperCamelCase__ : Tuple = SkipList() for i in range(10 ): skip_list.insert(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert is_sorted(list(SCREAMING_SNAKE_CASE__ ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(SCREAMING_SNAKE_CASE__ ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(SCREAMING_SNAKE_CASE__ ) ) def _a ( ): """simple docstring""" for _ in range(100 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def _a ( ): """simple docstring""" UpperCamelCase__ : Tuple = SkipList() skip_list.insert(2 , '''2''' ) skip_list.insert(4 , '''4''' ) skip_list.insert(6 , '''4''' ) skip_list.insert(4 , '''5''' ) skip_list.insert(8 , '''4''' ) skip_list.insert(9 , '''4''' ) skip_list.delete(4 ) print(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
366
import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __magic_name__ ( __lowerCAmelCase , unittest.TestCase): A: int = CTRLTokenizer A: List[Any] = False A: Dict = False def UpperCAmelCase__ ( self : Optional[Any] ) -> str: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ : Dict = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>'''] UpperCamelCase__ : List[str] = dict(zip(lowerCamelCase__ , range(len(lowerCamelCase__ ) ) ) ) UpperCamelCase__ : Tuple = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</w>''', ''''''] UpperCamelCase__ : int = {'''unk_token''': '''<unk>'''} UpperCamelCase__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCamelCase__ : Optional[int] = 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(lowerCamelCase__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(lowerCamelCase__ ) ) def UpperCAmelCase__ ( self : Tuple , **lowerCamelCase__ : str ) -> Dict: '''simple docstring''' kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase__ ) def UpperCAmelCase__ ( self : List[Any] , lowerCamelCase__ : Any ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ : Tuple = '''adapt react readapt apt''' UpperCamelCase__ : Optional[Any] = '''adapt react readapt apt''' return input_text, output_text def UpperCAmelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' UpperCamelCase__ : int = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ : Optional[Any] = '''adapt react readapt apt''' UpperCamelCase__ : List[Any] = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split() UpperCamelCase__ : Tuple = tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ : Dict = tokens + [tokenizer.unk_token] UpperCamelCase__ : List[str] = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) , lowerCamelCase__ )
51
0
'''simple docstring''' import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset lowerCAmelCase_ : List[Any] = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class __SCREAMING_SNAKE_CASE (nn.Module ): """simple docstring""" def __init__( self : Dict , __a : List[str] ): super().__init__() _a = torchvision.models.resnetaaa(pretrained=__UpperCAmelCase ) _a = list(model.children() )[:-2] _a = nn.Sequential(*__UpperCAmelCase ) _a = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] ) def UpperCamelCase__ ( self : Optional[Any] , __a : Optional[int] ): # Bx3x224x224 -> Bx2048x7x7 -> Bx2048xN -> BxNx2048 _a = self.pool(self.model(__UpperCAmelCase ) ) _a = torch.flatten(__UpperCAmelCase , start_dim=2 ) _a = out.transpose(1 , 2 ).contiguous() return out # BxNx2048 class __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self : List[str] , __a : List[Any] , __a : Union[str, Any] , __a : Any , __a : Dict , __a : Optional[Any] ): _a = [json.loads(__UpperCAmelCase ) for l in open(__UpperCAmelCase )] _a = os.path.dirname(__UpperCAmelCase ) _a = tokenizer _a = labels _a = len(__UpperCAmelCase ) _a = max_seq_length _a = transforms def __len__( self : Any ): return len(self.data ) def __getitem__( self : Union[str, Any] , __a : int ): _a = torch.LongTensor(self.tokenizer.encode(self.data[index]["text"] , add_special_tokens=__UpperCAmelCase ) ) _a , _a , _a = sentence[0], sentence[1:-1], sentence[-1] _a = sentence[: self.max_seq_length] _a = torch.zeros(self.n_classes ) _a = 1 _a = Image.open(os.path.join(self.data_dir , self.data[index]["img"] ) ).convert("RGB" ) _a = self.transforms(__UpperCAmelCase ) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def UpperCamelCase__ ( self : Optional[int] ): _a = Counter() for row in self.data: label_freqs.update(row["label"] ) return label_freqs def _lowerCamelCase ( lowercase : List[str] ) -> List[Any]: _a = [len(row["sentence"] ) for row in batch] _a , _a = len(lowercase ), max(lowercase ) _a = torch.zeros(lowercase , lowercase , dtype=torch.long ) _a = torch.zeros(lowercase , lowercase , dtype=torch.long ) for i_batch, (input_row, length) in enumerate(zip(lowercase , lowercase ) ): _a = input_row["sentence"] _a = 1 _a = torch.stack([row["image"] for row in batch] ) _a = torch.stack([row["label"] for row in batch] ) _a = torch.stack([row["image_start_token"] for row in batch] ) _a = torch.stack([row["image_end_token"] for row in batch] ) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def _lowerCamelCase ( ) -> Union[str, Any]: return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def _lowerCamelCase ( ) -> Optional[Any]: return transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize( mean=[0.46_77_70_44, 0.44_53_14_29, 0.40_66_10_17] , std=[0.12_22_19_94, 0.12_14_58_35, 0.14_38_04_69] , ), ] )
63
"""simple docstring""" def UpperCamelCase ( UpperCAmelCase ) ->str: """simple docstring""" return " ".join( "".join(word[::-1] ) if len(UpperCAmelCase ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('Hey wollef sroirraw'))
243
0
'''simple docstring''' from __future__ import annotations def _a ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ) -> None: """simple docstring""" __snake_case : int = len(_lowerCamelCase ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append([""". """ * i + """Q """ + """. """ * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(_lowerCamelCase ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , _lowerCamelCase , _lowerCamelCase , ) def _a ( _lowerCamelCase ) -> None: """simple docstring""" __snake_case : list[list[str]] = [] depth_first_search([] , [] , [] , _lowerCamelCase , _lowerCamelCase ) # Print all the boards for board in boards: for column in board: print(_lowerCamelCase ) print("""""" ) print(len(_lowerCamelCase ) , """solutions were found.""" ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
359
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _A ( __lowercase , unittest.TestCase ): lowercase__: int = KandinskyImgaImgPipeline lowercase__: Any = ['''prompt''', '''image_embeds''', '''negative_image_embeds''', '''image'''] lowercase__: int = [ '''prompt''', '''negative_prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', ] lowercase__: List[Any] = [ '''generator''', '''height''', '''width''', '''strength''', '''guidance_scale''', '''negative_prompt''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] lowercase__: Any = False @property def lowercase__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" return 32 @property def lowercase__ ( self : str ) -> str: """simple docstring""" return 32 @property def lowercase__ ( self : Tuple ) -> Any: """simple docstring""" return self.time_input_dim @property def lowercase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" return self.time_input_dim * 4 @property def lowercase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" return 1_00 @property def lowercase__ ( self : List[str] ) -> List[str]: """simple docstring""" __snake_case : str = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def lowercase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) __snake_case : int = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=10_05 , ) __snake_case : Tuple = MultilingualCLIP(__magic_name__ ) __snake_case : Optional[Any] = text_encoder.eval() return text_encoder @property def lowercase__ ( self : Tuple ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) __snake_case : int = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } __snake_case : Tuple = UNetaDConditionModel(**__magic_name__ ) return model @property def lowercase__ ( self : str ) -> Dict: """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def lowercase__ ( self : Optional[Any] ) -> int: """simple docstring""" torch.manual_seed(0 ) __snake_case : int = VQModel(**self.dummy_movq_kwargs ) return model def lowercase__ ( self : Tuple ) -> str: """simple docstring""" __snake_case : Tuple = self.dummy_text_encoder __snake_case : Dict = self.dummy_tokenizer __snake_case : Dict = self.dummy_unet __snake_case : int = self.dummy_movq __snake_case : List[Any] = { """num_train_timesteps""": 10_00, """beta_schedule""": """linear""", """beta_start""": 0.00085, """beta_end""": 0.012, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } __snake_case : Dict = DDIMScheduler(**__magic_name__ ) __snake_case : Any = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowercase__ ( self : str , __magic_name__ : str , __magic_name__ : Union[str, Any]=0 ) -> str: """simple docstring""" __snake_case : Dict = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(__magic_name__ ) ).to(__magic_name__ ) __snake_case : int = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(__magic_name__ ) # create init_image __snake_case : Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(__magic_name__ ) ).to(__magic_name__ ) __snake_case : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __snake_case : Optional[int] = Image.fromarray(np.uinta(__magic_name__ ) ).convert("""RGB""" ).resize((2_56, 2_56) ) if str(__magic_name__ ).startswith("""mps""" ): __snake_case : str = torch.manual_seed(__magic_name__ ) else: __snake_case : str = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) __snake_case : Optional[Any] = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def lowercase__ ( self : int ) -> str: """simple docstring""" __snake_case : Dict = """cpu""" __snake_case : Union[str, Any] = self.get_dummy_components() __snake_case : List[str] = self.pipeline_class(**__magic_name__ ) __snake_case : Optional[Any] = pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) __snake_case : List[str] = pipe(**self.get_dummy_inputs(__magic_name__ ) ) __snake_case : List[str] = output.images __snake_case : Any = pipe( **self.get_dummy_inputs(__magic_name__ ) , return_dict=__magic_name__ , )[0] __snake_case : Optional[int] = image[0, -3:, -3:, -1] __snake_case : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __snake_case : int = np.array( [0.61474943, 0.6073539, 0.43308544, 0.5928269, 0.47493595, 0.46755973, 0.4613838, 0.45368797, 0.50119233] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class _A ( unittest.TestCase ): def lowercase__ ( self : List[str] ) -> Optional[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase__ ( self : Optional[int] ) -> str: """simple docstring""" __snake_case : Union[str, Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) __snake_case : List[str] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) __snake_case : List[Any] = """A red cartoon frog, 4k""" __snake_case : str = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(__magic_name__ ) __snake_case : Union[str, Any] = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) __snake_case : Any = pipeline.to(__magic_name__ ) pipeline.set_progress_bar_config(disable=__magic_name__ ) __snake_case : List[str] = torch.Generator(device="""cpu""" ).manual_seed(0 ) __snake_case , __snake_case : Optional[Any] = pipe_prior( __magic_name__ , generator=__magic_name__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() __snake_case : List[str] = pipeline( __magic_name__ , image=__magic_name__ , image_embeds=__magic_name__ , negative_image_embeds=__magic_name__ , generator=__magic_name__ , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type="""np""" , ) __snake_case : Dict = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__magic_name__ , __magic_name__ )
13
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : str = { 'configuration_table_transformer': [ 'TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TableTransformerConfig', 'TableTransformerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[int] = [ 'TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TableTransformerForObjectDetection', 'TableTransformerModel', 'TableTransformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
286
"""simple docstring""" import qiskit def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : Tuple = qiskit.Aer.get_backend('aer_simulator' ) A_ : str = qiskit.QuantumCircuit(4 , 2 ) # encode inputs in qubits 0 and 1 if bita == 1: qc_ha.x(0 ) if bita == 1: qc_ha.x(1 ) qc_ha.barrier() # use cnots to write XOR of the inputs on qubit2 qc_ha.cx(0 , 2 ) qc_ha.cx(1 , 2 ) # use ccx / toffoli gate to write AND of the inputs on qubit3 qc_ha.ccx(0 , 1 , 3 ) qc_ha.barrier() # extract outputs qc_ha.measure(2 , 0 ) # extract XOR value qc_ha.measure(3 , 1 ) # extract AND value # Execute the circuit on the qasm simulator A_ : Optional[Any] = qiskit.execute(_UpperCAmelCase , _UpperCAmelCase , shots=1000 ) # Return the histogram data of the results of the experiment return job.result().get_counts(_UpperCAmelCase ) if __name__ == "__main__": lowerCamelCase_ : List[str] = half_adder(1, 1) print(F"Half Adder Output Qubit Counts: {counts}")
286
1
from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class lowerCAmelCase_: '''simple docstring''' __lowercase : Any = MBartConfig __lowercase : Tuple = {} __lowercase : Optional[Any] = '''gelu''' def __init__( self ,__UpperCAmelCase ,__UpperCAmelCase=13 ,__UpperCAmelCase=7 ,__UpperCAmelCase=True ,__UpperCAmelCase=False ,__UpperCAmelCase=99 ,__UpperCAmelCase=32 ,__UpperCAmelCase=2 ,__UpperCAmelCase=4 ,__UpperCAmelCase=37 ,__UpperCAmelCase=0.1 ,__UpperCAmelCase=0.1 ,__UpperCAmelCase=20 ,__UpperCAmelCase=2 ,__UpperCAmelCase=1 ,__UpperCAmelCase=0 ,) -> List[str]: lowerCAmelCase__ : Dict = parent lowerCAmelCase__ : Dict = batch_size lowerCAmelCase__ : Any = seq_length lowerCAmelCase__ : str = is_training lowerCAmelCase__ : Any = use_labels lowerCAmelCase__ : Union[str, Any] = vocab_size lowerCAmelCase__ : Optional[int] = hidden_size lowerCAmelCase__ : Union[str, Any] = num_hidden_layers lowerCAmelCase__ : List[str] = num_attention_heads lowerCAmelCase__ : List[str] = intermediate_size lowerCAmelCase__ : Tuple = hidden_dropout_prob lowerCAmelCase__ : List[Any] = attention_probs_dropout_prob lowerCAmelCase__ : Any = max_position_embeddings lowerCAmelCase__ : int = eos_token_id lowerCAmelCase__ : Tuple = pad_token_id lowerCAmelCase__ : List[Any] = bos_token_id def UpperCAmelCase_ ( self ) -> Optional[int]: lowerCAmelCase__ : Any = ids_tensor([self.batch_size, self.seq_length - 1] ,self.vocab_size ) lowerCAmelCase__ : Optional[int] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) ,1 ) lowerCAmelCase__ : List[str] = tf.concat([input_ids, eos_tensor] ,axis=1 ) lowerCAmelCase__ : Any = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) lowerCAmelCase__ : Any = self.config_cls( 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_ids=[2] ,bos_token_id=self.bos_token_id ,pad_token_id=self.pad_token_id ,decoder_start_token_id=self.pad_token_id ,**self.config_updates ,) lowerCAmelCase__ : Optional[int] = prepare_mbart_inputs_dict(UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_ ) return config, inputs_dict def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ) -> Optional[Any]: lowerCAmelCase__ : int = TFMBartModel(config=UpperCamelCase_ ).get_decoder() lowerCAmelCase__ : List[Any] = inputs_dict["""input_ids"""] lowerCAmelCase__ : Tuple = input_ids[:1, :] lowerCAmelCase__ : Optional[int] = inputs_dict["""attention_mask"""][:1, :] lowerCAmelCase__ : List[str] = inputs_dict["""head_mask"""] lowerCAmelCase__ : int = 1 # first forward pass lowerCAmelCase__ : List[Any] = model(UpperCamelCase_ ,attention_mask=UpperCamelCase_ ,head_mask=UpperCamelCase_ ,use_cache=UpperCamelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = outputs.to_tuple() lowerCAmelCase__ : Dict = past_key_values[1] def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase=None , UpperCamelCase=None , ): """simple docstring""" if attention_mask is None: lowerCAmelCase__ : Union[str, Any] = tf.cast(tf.math.not_equal(UpperCamelCase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowerCAmelCase__ : Optional[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: lowerCAmelCase__ : Optional[Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowerCAmelCase__ : Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowerCAmelCase__ : Union[str, Any] = tf.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": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class lowerCAmelCase_( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): '''simple docstring''' __lowercase : Tuple = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () __lowercase : Dict = (TFMBartForConditionalGeneration,) if is_tf_available() else () __lowercase : Optional[int] = ( { '''conversational''': TFMBartForConditionalGeneration, '''feature-extraction''': TFMBartModel, '''summarization''': TFMBartForConditionalGeneration, '''text2text-generation''': TFMBartForConditionalGeneration, '''translation''': TFMBartForConditionalGeneration, } if is_tf_available() else {} ) __lowercase : Optional[Any] = True __lowercase : Tuple = False __lowercase : Any = False def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> int: if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def UpperCAmelCase_ ( self ) -> Union[str, Any]: lowerCAmelCase__ : List[str] = TFMBartModelTester(self ) lowerCAmelCase__ : int = ConfigTester(self ,config_class=UpperCamelCase_ ) def UpperCAmelCase_ ( self ) -> Dict: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ) -> Dict: lowerCAmelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*UpperCamelCase_ ) @require_sentencepiece @require_tokenizers @require_tf class lowerCAmelCase_( unittest.TestCase ): '''simple docstring''' __lowercase : Dict = [ ''' UN Chief Says There Is No Military Solution in Syria''', ] __lowercase : Dict = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', ] __lowercase : int = '''facebook/mbart-large-en-ro''' @cached_property def UpperCAmelCase_ ( self ) -> Optional[Any]: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def UpperCAmelCase_ ( self ) -> Dict: lowerCAmelCase__ : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def UpperCAmelCase_ ( self ,**__UpperCAmelCase ) -> Tuple: lowerCAmelCase__ : int = self.translate_src_text(**UpperCamelCase_ ) self.assertListEqual(self.expected_text ,UpperCamelCase_ ) def UpperCAmelCase_ ( self ,**__UpperCAmelCase ) -> Tuple: lowerCAmelCase__ : List[Any] = self.tokenizer(self.src_text ,**UpperCamelCase_ ,return_tensors="""tf""" ) lowerCAmelCase__ : Union[str, Any] = self.model.generate( model_inputs.input_ids ,attention_mask=model_inputs.attention_mask ,num_beams=2 ) lowerCAmelCase__ : Union[str, Any] = self.tokenizer.batch_decode(UpperCamelCase_ ,skip_special_tokens=UpperCamelCase_ ) return generated_words @slow def UpperCAmelCase_ ( self ) -> List[Any]: self._assert_generated_batch_equal_expected()
355
'''simple docstring''' import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): '''simple docstring''' __lowercase : Optional[Any] = VQModel __lowercase : Tuple = '''sample''' @property def UpperCAmelCase_ ( self ,__UpperCAmelCase=(32, 32) ) -> List[Any]: lowerCAmelCase__ : Dict = 4 lowerCAmelCase__ : List[str] = 3 lowerCAmelCase__ : Dict = floats_tensor((batch_size, num_channels) + sizes ).to(__UpperCAmelCase ) return {"sample": image} @property def UpperCAmelCase_ ( self ) -> List[Any]: return (3, 32, 32) @property def UpperCAmelCase_ ( self ) -> Optional[Any]: return (3, 32, 32) def UpperCAmelCase_ ( self ) -> List[Any]: lowerCAmelCase__ : Dict = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } lowerCAmelCase__ : Any = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase_ ( self ) -> Union[str, Any]: pass def UpperCAmelCase_ ( self ) -> Optional[int]: pass def UpperCAmelCase_ ( self ) -> Tuple: lowerCAmelCase__ , lowerCAmelCase__ : Union[str, Any] = VQModel.from_pretrained("""fusing/vqgan-dummy""" ,output_loading_info=__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) self.assertEqual(len(loading_info["""missing_keys"""] ) ,0 ) model.to(__UpperCAmelCase ) lowerCAmelCase__ : List[Any] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCAmelCase_ ( self ) -> List[str]: lowerCAmelCase__ : Tuple = VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(__UpperCAmelCase ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) lowerCAmelCase__ : List[str] = torch.randn(1 ,model.config.in_channels ,model.config.sample_size ,model.config.sample_size ) lowerCAmelCase__ : Optional[Any] = image.to(__UpperCAmelCase ) with torch.no_grad(): lowerCAmelCase__ : Optional[Any] = model(__UpperCAmelCase ).sample lowerCAmelCase__ : Tuple = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off lowerCAmelCase__ : Tuple = torch.tensor([-0.0_1_5_3, -0.4_0_4_4, -0.1_8_8_0, -0.5_1_6_1, -0.2_4_1_8, -0.4_0_7_2, -0.1_6_1_2, -0.0_6_3_3, -0.0_1_4_3] ) # fmt: on self.assertTrue(torch.allclose(__UpperCAmelCase ,__UpperCAmelCase ,atol=1E-3 ) )
184
0
"""simple docstring""" import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) 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 snake_case_ = 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.14.0""", """To fix: pip install -r examples/pytorch/audio-classification/requirements.txt""") def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ = 16000 ): UpperCAmelCase = int(round(sample_rate * max_length ) ) if len(lowercase_ ) <= sample_length: return wav UpperCAmelCase = randint(0 , len(lowercase_ ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class A_ : """simple docstring""" __UpperCamelCase = field(default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Name of a dataset from the datasets package"""} ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """A file containing the training audio paths and labels."""} ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """A file containing the validation audio paths and labels."""} ) __UpperCamelCase = field( default="""train""" , metadata={ """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'""" } , ) __UpperCamelCase = field( default="""validation""" , metadata={ """help""": ( """The name of the training data set split to use (via the datasets library). Defaults to 'validation'""" ) } , ) __UpperCamelCase = field( default="""audio""" , metadata={"""help""": """The name of the dataset column containing the audio data. Defaults to 'audio'"""} , ) __UpperCamelCase = field( default="""label""" , metadata={"""help""": """The name of the dataset column containing the labels. Defaults to 'label'"""} ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) __UpperCamelCase = field( default=20 , metadata={"""help""": """Audio clips will be randomly cut to this length during training if the value is set."""} , ) @dataclass class A_ : """simple docstring""" __UpperCamelCase = field( default="""facebook/wav2vec2-base""" , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} , ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from the Hub"""} ) __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=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Name or path of preprocessor config."""} ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Whether to freeze the feature encoder layers of the model."""} ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Whether to generate an attention mask in the feature extractor."""} ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""} ) __UpperCamelCase = field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""} , ) def UpperCAmelCase__ ( self :Dict ) -> Union[str, Any]: if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( 'The argument `--freeze_feature_extractor` is deprecated and ' 'will be removed in a future version. Use `--freeze_feature_encoder`' 'instead. Setting `freeze_feature_encoder==True`.' , lowercase_ , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( 'The argument `--freeze_feature_extractor` is deprecated and ' 'should not be used in combination with `--freeze_feature_encoder`.' 'Only make use of `--freeze_feature_encoder`.' ) def _lowerCAmelCase ( ): # 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, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCAmelCase , 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_audio_classification' , lowercase_ , lowercase_ ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() UpperCAmelCase = training_args.get_process_log_level() logger.setLevel(lowercase_ ) transformers.utils.logging.set_verbosity(lowercase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} """ + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Set seed before initializing model. set_seed(training_args.seed ) # 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 train from scratch.' ) 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 and prepare it for the audio classification task. UpperCAmelCase = DatasetDict() UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F"""--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. """ 'Make sure to set `--audio_column_name` to the correct audio column - one of ' F"""{', '.join(raw_datasets['train'].column_names )}.""" ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F"""--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. """ 'Make sure to set `--label_column_name` to the correct text column - one of ' F"""{', '.join(raw_datasets['train'].column_names )}.""" ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy UpperCAmelCase = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. UpperCAmelCase = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) UpperCAmelCase = feature_extractor.model_input_names[0] def train_transforms(lowercase_ ): UpperCAmelCase = [] for audio in batch[data_args.audio_column_name]: UpperCAmelCase = random_subsample( audio['array'] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(lowercase_ ) UpperCAmelCase = feature_extractor(lowercase_ , sampling_rate=feature_extractor.sampling_rate ) UpperCAmelCase = {model_input_name: inputs.get(lowercase_ )} UpperCAmelCase = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(lowercase_ ): UpperCAmelCase = [audio['array'] for audio in batch[data_args.audio_column_name]] UpperCAmelCase = feature_extractor(lowercase_ , sampling_rate=feature_extractor.sampling_rate ) UpperCAmelCase = {model_input_name: inputs.get(lowercase_ )} UpperCAmelCase = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. UpperCAmelCase = raw_datasets['train'].features[data_args.label_column_name].names UpperCAmelCase , UpperCAmelCase = {}, {} for i, label in enumerate(lowercase_ ): UpperCAmelCase = str(lowercase_ ) UpperCAmelCase = label # Load the accuracy metric from the datasets package UpperCAmelCase = evaluate.load('accuracy' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(lowercase_ ): UpperCAmelCase = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=lowercase_ , references=eval_pred.label_ids ) UpperCAmelCase = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(lowercase_ ) , labelaid=lowercase_ , idalabel=lowercase_ , finetuning_task='audio-classification' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) UpperCAmelCase = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=lowercase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: UpperCAmelCase = ( raw_datasets['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(lowercase_ , output_all_columns=lowercase_ ) if training_args.do_eval: if data_args.max_eval_samples is not None: UpperCAmelCase = ( raw_datasets['eval'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(lowercase_ , output_all_columns=lowercase_ ) # Initialize our trainer UpperCAmelCase = Trainer( model=lowercase_ , args=lowercase_ , train_dataset=raw_datasets['train'] if training_args.do_train else None , eval_dataset=raw_datasets['eval'] if training_args.do_eval else None , compute_metrics=lowercase_ , tokenizer=lowercase_ , ) # Training if training_args.do_train: UpperCAmelCase = None if training_args.resume_from_checkpoint is not None: UpperCAmelCase = training_args.resume_from_checkpoint elif last_checkpoint is not None: UpperCAmelCase = last_checkpoint UpperCAmelCase = trainer.train(resume_from_checkpoint=lowercase_ ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: UpperCAmelCase = trainer.evaluate() trainer.log_metrics('eval' , lowercase_ ) trainer.save_metrics('eval' , lowercase_ ) # Write model card and (optionally) push to hub UpperCAmelCase = { 'finetuned_from': model_args.model_name_or_path, 'tasks': 'audio-classification', 'dataset': data_args.dataset_name, 'tags': ['audio-classification'], } if training_args.push_to_hub: trainer.push_to_hub(**lowercase_ ) else: trainer.create_model_card(**lowercase_ ) if __name__ == "__main__": main()
78
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot import BlenderbotTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation a : List[str] = logging.get_logger(__name__) a : List[Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } a : List[str] = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } a : int = {'facebook/blenderbot-3B': 128} class _a ( _lowerCAmelCase ): A = VOCAB_FILES_NAMES A = PRETRAINED_VOCAB_FILES_MAP A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A = ['''input_ids''', '''attention_mask'''] A = BlenderbotTokenizer def __init__(self, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_="replace", SCREAMING_SNAKE_CASE_="<s>", SCREAMING_SNAKE_CASE_="</s>", SCREAMING_SNAKE_CASE_="</s>", SCREAMING_SNAKE_CASE_="<s>", SCREAMING_SNAKE_CASE_="<unk>", SCREAMING_SNAKE_CASE_="<pad>", SCREAMING_SNAKE_CASE_="<mask>", SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=True, **SCREAMING_SNAKE_CASE_, ) -> Dict: super().__init__( SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, tokenizer_file=SCREAMING_SNAKE_CASE_, errors=SCREAMING_SNAKE_CASE_, bos_token=SCREAMING_SNAKE_CASE_, eos_token=SCREAMING_SNAKE_CASE_, sep_token=SCREAMING_SNAKE_CASE_, cls_token=SCREAMING_SNAKE_CASE_, unk_token=SCREAMING_SNAKE_CASE_, pad_token=SCREAMING_SNAKE_CASE_, mask_token=SCREAMING_SNAKE_CASE_, add_prefix_space=SCREAMING_SNAKE_CASE_, trim_offsets=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_, ) UpperCAmelCase_: Any = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""", SCREAMING_SNAKE_CASE_ ) != add_prefix_space: UpperCAmelCase_: int = getattr(SCREAMING_SNAKE_CASE_, pre_tok_state.pop("""type""" ) ) UpperCAmelCase_: Union[str, Any] = add_prefix_space UpperCAmelCase_: List[Any] = pre_tok_class(**SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Tuple = add_prefix_space UpperCAmelCase_: Optional[Any] = """post_processor""" UpperCAmelCase_: List[str] = getattr(self.backend_tokenizer, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) if tokenizer_component_instance: UpperCAmelCase_: Optional[Any] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: UpperCAmelCase_: Optional[Any] = tuple(state["""sep"""] ) if "cls" in state: UpperCAmelCase_: int = tuple(state["""cls"""] ) UpperCAmelCase_: int = False if state.get("""add_prefix_space""", SCREAMING_SNAKE_CASE_ ) != add_prefix_space: UpperCAmelCase_: Any = add_prefix_space UpperCAmelCase_: str = True if state.get("""trim_offsets""", SCREAMING_SNAKE_CASE_ ) != trim_offsets: UpperCAmelCase_: Tuple = trim_offsets UpperCAmelCase_: Tuple = True if changes_to_apply: UpperCAmelCase_: str = getattr(SCREAMING_SNAKE_CASE_, state.pop("""type""" ) ) UpperCAmelCase_: str = component_class(**SCREAMING_SNAKE_CASE_ ) setattr(self.backend_tokenizer, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) @property # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot def __snake_case (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 __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> int: UpperCAmelCase_: Dict = AddedToken(SCREAMING_SNAKE_CASE_, lstrip=SCREAMING_SNAKE_CASE_, rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) else value UpperCAmelCase_: Optional[int] = value def __snake_case (self, *SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) -> BatchEncoding: UpperCAmelCase_: List[str] = kwargs.get("""is_split_into_words""", SCREAMING_SNAKE_CASE_ ) assert self.add_prefix_space or not is_split_into_words, ( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) def __snake_case (self, *SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) -> BatchEncoding: UpperCAmelCase_: List[Any] = kwargs.get("""is_split_into_words""", SCREAMING_SNAKE_CASE_ ) assert self.add_prefix_space or not is_split_into_words, ( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._encode_plus(*SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: UpperCAmelCase_: str = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_, name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> List[int]: UpperCAmelCase_: List[Any] = [self.sep_token_id] UpperCAmelCase_: int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> Union[str, Any]: return token_ids_a + [self.eos_token_id] def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> List[int]: UpperCAmelCase_: Optional[Any] = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(""" """ + text ) else: # Generated responses should contain them already. inputs.append(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: int = """ """.join(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Tuple = self.encode(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > self.model_max_length: UpperCAmelCase_: int = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
147
0
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def lowerCamelCase__ ( __snake_case ) -> List[Any]: """simple docstring""" if "cls_token" in name: _UpperCamelCase = name.replace('''cls_token''', '''vit.embeddings.cls_token''' ) if "mask_token" in name: _UpperCamelCase = name.replace('''mask_token''', '''decoder.mask_token''' ) if "decoder_pos_embed" in name: _UpperCamelCase = name.replace('''decoder_pos_embed''', '''decoder.decoder_pos_embed''' ) if "pos_embed" in name and "decoder" not in name: _UpperCamelCase = name.replace('''pos_embed''', '''vit.embeddings.position_embeddings''' ) if "patch_embed.proj" in name: _UpperCamelCase = name.replace('''patch_embed.proj''', '''vit.embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: _UpperCamelCase = name.replace('''patch_embed.norm''', '''vit.embeddings.norm''' ) if "decoder_blocks" in name: _UpperCamelCase = name.replace('''decoder_blocks''', '''decoder.decoder_layers''' ) if "blocks" in name: _UpperCamelCase = name.replace('''blocks''', '''vit.encoder.layer''' ) if "attn.proj" in name: _UpperCamelCase = name.replace('''attn.proj''', '''attention.output.dense''' ) if "attn" in name: _UpperCamelCase = name.replace('''attn''', '''attention.self''' ) if "norm1" in name: _UpperCamelCase = name.replace('''norm1''', '''layernorm_before''' ) if "norm2" in name: _UpperCamelCase = name.replace('''norm2''', '''layernorm_after''' ) if "mlp.fc1" in name: _UpperCamelCase = name.replace('''mlp.fc1''', '''intermediate.dense''' ) if "mlp.fc2" in name: _UpperCamelCase = name.replace('''mlp.fc2''', '''output.dense''' ) if "decoder_embed" in name: _UpperCamelCase = name.replace('''decoder_embed''', '''decoder.decoder_embed''' ) if "decoder_norm" in name: _UpperCamelCase = name.replace('''decoder_norm''', '''decoder.decoder_norm''' ) if "decoder_pred" in name: _UpperCamelCase = name.replace('''decoder_pred''', '''decoder.decoder_pred''' ) if "norm.weight" in name and "decoder" not in name: _UpperCamelCase = name.replace('''norm.weight''', '''vit.layernorm.weight''' ) if "norm.bias" in name and "decoder" not in name: _UpperCamelCase = name.replace('''norm.bias''', '''vit.layernorm.bias''' ) return name def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[int]: """simple docstring""" for key in orig_state_dict.copy().keys(): _UpperCamelCase = orig_state_dict.pop(__snake_case ) if "qkv" in key: _UpperCamelCase = key.split('''.''' ) _UpperCamelCase = int(key_split[1] ) if "decoder_blocks" in key: _UpperCamelCase = config.decoder_hidden_size _UpperCamelCase = '''decoder.decoder_layers.''' if "weight" in key: _UpperCamelCase = val[:dim, :] _UpperCamelCase = val[dim : dim * 2, :] _UpperCamelCase = val[-dim:, :] elif "bias" in key: _UpperCamelCase = val[:dim] _UpperCamelCase = val[dim : dim * 2] _UpperCamelCase = val[-dim:] else: _UpperCamelCase = config.hidden_size _UpperCamelCase = '''vit.encoder.layer.''' if "weight" in key: _UpperCamelCase = val[:dim, :] _UpperCamelCase = val[dim : dim * 2, :] _UpperCamelCase = val[-dim:, :] elif "bias" in key: _UpperCamelCase = val[:dim] _UpperCamelCase = val[dim : dim * 2] _UpperCamelCase = val[-dim:] else: _UpperCamelCase = val return orig_state_dict def lowerCamelCase__ ( __snake_case, __snake_case ) -> Tuple: """simple docstring""" _UpperCamelCase = ViTMAEConfig() if "large" in checkpoint_url: _UpperCamelCase = 10_24 _UpperCamelCase = 40_96 _UpperCamelCase = 24 _UpperCamelCase = 16 elif "huge" in checkpoint_url: _UpperCamelCase = 14 _UpperCamelCase = 12_80 _UpperCamelCase = 51_20 _UpperCamelCase = 32 _UpperCamelCase = 16 _UpperCamelCase = ViTMAEForPreTraining(__snake_case ) _UpperCamelCase = torch.hub.load_state_dict_from_url(__snake_case, map_location='''cpu''' )['''model'''] _UpperCamelCase = ViTMAEImageProcessor(size=config.image_size ) _UpperCamelCase = convert_state_dict(__snake_case, __snake_case ) model.load_state_dict(__snake_case ) model.eval() _UpperCamelCase = '''https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg''' _UpperCamelCase = Image.open(requests.get(__snake_case, stream=__snake_case ).raw ) _UpperCamelCase = ViTMAEImageProcessor(size=config.image_size ) _UpperCamelCase = image_processor(images=__snake_case, return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) _UpperCamelCase = model(**__snake_case ) _UpperCamelCase = outputs.logits if "large" in checkpoint_url: _UpperCamelCase = torch.tensor( [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]] ) elif "huge" in checkpoint_url: _UpperCamelCase = torch.tensor( [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]] ) else: _UpperCamelCase = torch.tensor( [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]] ) # verify logits assert torch.allclose(logits[0, :3, :3], __snake_case, atol=1e-4 ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(__snake_case ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(__snake_case ) if __name__ == "__main__": _a = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth""", type=str, help="""URL of the checkpoint you\'d like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) _a = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
366
"""simple docstring""" from __future__ import annotations def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[int]: """simple docstring""" if len(__snake_case ) <= 1 or n <= 1: return insert_next(__snake_case, n - 1 ) rec_insertion_sort(__snake_case, n - 1 ) def lowerCamelCase__ ( __snake_case, __snake_case ) -> Dict: """simple docstring""" if index >= len(__snake_case ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order _UpperCamelCase , _UpperCamelCase = ( collection[index], collection[index - 1], ) insert_next(__snake_case, index + 1 ) if __name__ == "__main__": _a = input("""Enter integers separated by spaces: """) _a = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
100
0
"""simple docstring""" from __future__ import annotations from typing import Any def _SCREAMING_SNAKE_CASE ( _lowercase : list ) ->int: '''simple docstring''' if not postfix_notation: return 0 a : List[str] = {"+", "-", "*", "/"} a : list[Any] = [] for token in postfix_notation: if token in operations: a, a : int = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(_lowercase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
105
import math def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ = 0 , lowerCamelCase__ = 0 ): lowerCamelCase_ = end or len(lowerCamelCase__ ) for i in range(lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = i lowerCamelCase_ = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: lowerCamelCase_ = array[temp_index - 1] temp_index -= 1 lowerCamelCase_ = temp_index_value return array def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): # Max Heap lowerCamelCase_ = index lowerCamelCase_ = 2 * index + 1 # Left Node lowerCamelCase_ = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: lowerCamelCase_ = left_index if right_index < heap_size and array[largest] < array[right_index]: lowerCamelCase_ = right_index if largest != index: lowerCamelCase_ , lowerCamelCase_ = array[largest], array[index] heapify(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = len(lowerCamelCase__ ) for i in range(n // 2 , -1 , -1 ): heapify(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) for i in range(n - 1 , 0 , -1 ): lowerCamelCase_ , lowerCamelCase_ = array[0], array[i] heapify(lowerCamelCase__ , 0 , lowerCamelCase__ ) return array def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = low lowerCamelCase_ = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i lowerCamelCase_ , lowerCamelCase_ = array[j], array[i] i += 1 def lowerCamelCase_ ( lowerCamelCase__ ): if len(lowerCamelCase__ ) == 0: return array lowerCamelCase_ = 2 * math.ceil(math.loga(len(lowerCamelCase__ ) ) ) lowerCamelCase_ = 1_6 return intro_sort(lowerCamelCase__ , 0 , len(lowerCamelCase__ ) , lowerCamelCase__ , lowerCamelCase__ ) def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): while end - start > size_threshold: if max_depth == 0: return heap_sort(lowerCamelCase__ ) max_depth -= 1 lowerCamelCase_ = median_of_a(lowerCamelCase__ , lowerCamelCase__ , start + ((end - start) // 2) + 1 , end - 1 ) lowerCamelCase_ = partition(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) intro_sort(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) lowerCamelCase_ = p return insertion_sort(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod() __A =input('''Enter numbers separated by a comma : ''').strip() __A =[float(item) for item in user_input.split(''',''')] print(sort(unsorted))
19
0
"""simple docstring""" import argparse import json from tqdm import tqdm def snake_case (): '''simple docstring''' a : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--src_path' , type=A_ , default='biencoder-nq-dev.json' , help='Path to raw DPR training data' , ) parser.add_argument( '--evaluation_set' , type=A_ , help='where to store parsed evaluation_set file' , ) parser.add_argument( '--gold_data_path' , type=A_ , help='where to store parsed gold_data_path file' , ) a : Dict = parser.parse_args() with open(args.src_path , 'r' ) as src_file, open(args.evaluation_set , 'w' ) as eval_file, open( args.gold_data_path , 'w' ) as gold_file: a : Dict = json.load(A_ ) for dpr_record in tqdm(A_ ): a : Dict = dpr_record['question'] a : Union[str, Any] = [context['title'] for context in dpr_record['positive_ctxs']] eval_file.write(question + '\n' ) gold_file.write('\t'.join(A_ ) + '\n' ) if __name__ == "__main__": main()
186
"""simple docstring""" import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin _UpperCamelCase : int = get_tests_dir('fixtures/test_sentencepiece_bpe.model') class snake_case ( UpperCAmelCase , unittest.TestCase ): __magic_name__ = BartphoTokenizer __magic_name__ = False __magic_name__ = True def lowerCamelCase__ ( self : List[Any] ): '''simple docstring''' super().setUp() a : Any = ['▁This', '▁is', '▁a', '▁t', 'est'] a : List[Any] = dict(zip(A , range(len(A ) ) ) ) a : int = {'unk_token': '<unk>'} a : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['monolingual_vocab_file'] ) with open(self.monolingual_vocab_file , 'w' , encoding='utf-8' ) as fp: for token in vocab_tokens: fp.write(F'''{token} {vocab_tokens[token]}\n''' ) a : Optional[int] = BartphoTokenizer(A , self.monolingual_vocab_file , **self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self : Dict , **A : str ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname , **A ) def lowerCamelCase__ ( self : Optional[int] , A : Dict ): '''simple docstring''' a : Tuple = 'This is a là test' a : List[Any] = 'This is a<unk><unk> test' return input_text, output_text def lowerCamelCase__ ( self : Optional[Any] ): '''simple docstring''' a : Tuple = BartphoTokenizer(A , self.monolingual_vocab_file , **self.special_tokens_map ) a : int = 'This is a là test' a : int = '▁This ▁is ▁a ▁l à ▁t est'.split() a : str = tokenizer.tokenize(A ) self.assertListEqual(A , A ) a : Union[str, Any] = tokens + [tokenizer.unk_token] a : Dict = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) , A )
186
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class snake_case_ ( unittest.TestCase ): def __init__( self : Tuple , lowercase_ : List[Any] , lowercase_ : Union[str, Any]=2 , lowercase_ : Union[str, Any]=56 , lowercase_ : Tuple=True , lowercase_ : Optional[Any]=True , lowercase_ : Optional[Any]=True , lowercase_ : int=True , lowercase_ : Any=99 , lowercase_ : int=32 , lowercase_ : str=2 , lowercase_ : Union[str, Any]=2 , lowercase_ : Dict=7 , lowercase_ : Dict="gelu_new" , lowercase_ : Tuple=0.1 , lowercase_ : List[Any]=0.1 , lowercase_ : Tuple=5_12 , lowercase_ : Optional[Any]=16 , lowercase_ : List[Any]=2 , lowercase_ : Dict=0.02 , lowercase_ : int=4 , lowercase_ : Tuple="block_sparse" , lowercase_ : Dict=True , lowercase_ : Optional[int]=False , lowercase_ : Dict=2 , lowercase_ : int=3 , ) -> Union[str, Any]: lowercase__ : Dict = parent lowercase__ : Dict = batch_size lowercase__ : Tuple = seq_length lowercase__ : Dict = is_training lowercase__ : Dict = use_attention_mask lowercase__ : Tuple = use_token_type_ids lowercase__ : Optional[int] = use_labels lowercase__ : List[Any] = vocab_size lowercase__ : Any = hidden_size lowercase__ : List[Any] = num_hidden_layers lowercase__ : Union[str, Any] = num_attention_heads lowercase__ : str = intermediate_size lowercase__ : int = hidden_act lowercase__ : str = hidden_dropout_prob lowercase__ : List[str] = attention_probs_dropout_prob lowercase__ : Optional[Any] = max_position_embeddings lowercase__ : Union[str, Any] = type_vocab_size lowercase__ : Dict = type_sequence_label_size lowercase__ : Any = initializer_range lowercase__ : List[str] = num_choices lowercase__ : str = rescale_embeddings lowercase__ : Optional[Any] = attention_type lowercase__ : Optional[int] = use_bias lowercase__ : Optional[int] = block_size lowercase__ : str = num_random_blocks def __UpperCamelCase ( self : str ) -> Optional[Any]: lowercase__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ : str = None if self.use_attention_mask: lowercase__ : Any = random_attention_mask([self.batch_size, self.seq_length] ) lowercase__ : Optional[int] = None if self.use_token_type_ids: lowercase__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase__ : int = BigBirdConfig( 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=lowercase_ , initializer_range=self.initializer_range , attention_type=self.attention_type , block_size=self.block_size , num_random_blocks=self.num_random_blocks , use_bias=self.use_bias , rescale_embeddings=self.rescale_embeddings , ) return config, input_ids, token_type_ids, attention_mask def __UpperCamelCase ( self : Union[str, Any] ) -> int: lowercase__ : int = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ , lowercase__ : Dict = config_and_inputs lowercase__ : Union[str, Any] = { "input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask, } return config, inputs_dict @require_flax class snake_case_ ( __A ,unittest.TestCase ): __A : Optional[int] = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) __A : List[str] = False __A : Any = False def __UpperCamelCase ( self : List[str] ) -> List[Any]: lowercase__ : Union[str, Any] = FlaxBigBirdModelTester(self ) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCamelCase ( self : Optional[int] ) -> Dict: super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCamelCase ( self : List[str] ) -> Any: super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCamelCase ( self : Tuple ) -> str: super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCamelCase ( self : Dict ) -> Union[str, Any]: super().test_hidden_states_output() @slow def __UpperCamelCase ( self : Optional[int] ) -> Tuple: for model_class_name in self.all_model_classes: lowercase__ : Optional[Any] = model_class_name.from_pretrained("google/bigbird-roberta-base" ) self.assertIsNotNone(lowercase_ ) def __UpperCamelCase ( self : int ) -> Optional[int]: if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCamelCase ( self : str ) -> Any: lowercase__ , lowercase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase__ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_ ) lowercase__ : Optional[Any] = model_class(lowercase_ ) @jax.jit def model_jitted(lowercase_ : Tuple , lowercase_ : int=None , **lowercase_ : Dict ): return model(input_ids=lowercase_ , attention_mask=lowercase_ , **lowercase_ ) with self.subTest("JIT Enabled" ): lowercase__ : int = model_jitted(**lowercase_ ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): lowercase__ : Any = model_jitted(**lowercase_ ).to_tuple() self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) for jitted_output, output in zip(lowercase_ , lowercase_ ): self.assertEqual(jitted_output.shape , output.shape ) def __UpperCamelCase ( self : List[Any] , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Optional[int] , lowercase_ : List[Any]=1E-5 , lowercase_ : Any="outputs" , lowercase_ : List[str]=None ) -> List[Any]: # `bigbird_block_sparse_attention` in `FlaxBigBird` returns `attention_probs = None`, while in PyTorch version, # an effort was done to return `attention_probs` (yet to be verified). if name.startswith("outputs.attentions" ): return else: super().check_pt_flax_outputs(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ )
87
0
import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Optional[int] = """facebook/bart-large-mnli""" snake_case__ : Optional[int] = ( """This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which """ """should be the text to classify, and `labels`, which should be the list of labels to use for classification. """ """It returns the most likely label in the list of provided `labels` for the input text.""" ) snake_case__ : int = """text_classifier""" snake_case__ : Tuple = AutoTokenizer snake_case__ : Optional[int] = AutoModelForSequenceClassification snake_case__ : Any = ["""text""", ["""text"""]] snake_case__ : Dict = ["""text"""] def _A ( self : Union[str, Any] ): super().setup() UpperCamelCase :Dict = self.model.config UpperCamelCase :List[str] = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail""" ): UpperCamelCase :Tuple = int(snake_case_ ) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""" ) def _A ( self : Tuple , __lowerCamelCase : int , __lowerCamelCase : Tuple ): UpperCamelCase :Union[str, Any] = labels return self.pre_processor( [text] * len(snake_case_ ) , [F"""This example is {label}""" for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def _A ( self : int , __lowerCamelCase : Tuple ): UpperCamelCase :str = outputs.logits UpperCamelCase :Optional[Any] = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
371
import string def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str ) -> None: """simple docstring""" for key in range(len(string.ascii_uppercase ) ): UpperCamelCase :List[str] = """""" for symbol in message: if symbol in string.ascii_uppercase: UpperCamelCase :Optional[Any] = string.ascii_uppercase.find(__magic_name__ ) UpperCamelCase :Any = num - key if num < 0: UpperCamelCase :Optional[Any] = num + len(string.ascii_uppercase ) UpperCamelCase :int = translated + string.ascii_uppercase[num] else: UpperCamelCase :Optional[Any] = translated + symbol print(f"""Decryption using Key #{key}: {translated}""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: """simple docstring""" UpperCamelCase :List[Any] = input("""Encrypted message: """ ) UpperCamelCase :Optional[Any] = message.upper() decrypt(__magic_name__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
62
0
'''simple docstring''' import sys a : Dict = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def __magic_name__ ( __UpperCAmelCase ) -> int: '''simple docstring''' snake_case_ = 1 for digit in s: product *= int(__UpperCAmelCase ) return product def __magic_name__ ( __UpperCAmelCase = N ) -> int: '''simple docstring''' snake_case_ = -sys.maxsize - 1 snake_case_ = n[:13] snake_case_ = 13 while cur_index < len(__UpperCAmelCase ) - 13: if int(n[cur_index] ) >= int(substr[0] ): snake_case_ = substr[1:] + n[cur_index] cur_index += 1 else: snake_case_ = max(__UpperCAmelCase, str_eval(__UpperCAmelCase ) ) snake_case_ = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f'''{solution() = }''')
56
'''simple docstring''' import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __snake_case ( _SCREAMING_SNAKE_CASE ,unittest.TestCase): """simple docstring""" lowercase = BioGptTokenizer lowercase = False def __lowercase ( self : List[Any] ) -> List[str]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCAmelCase_ : Optional[Any] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] lowerCAmelCase_ : int = dict(zip(lowerCamelCase , range(len(lowerCamelCase ) ) ) ) lowerCAmelCase_ : int = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] lowerCAmelCase_ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) lowerCAmelCase_ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(lowerCamelCase ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(lowerCamelCase ) ) def __lowercase ( self : Union[str, Any] , lowerCamelCase : Any ) -> List[str]: lowerCAmelCase_ : Dict = """lower newer""" lowerCAmelCase_ : str = """lower newer""" return input_text, output_text def __lowercase ( self : Optional[int] ) -> str: lowerCAmelCase_ : Any = BioGptTokenizer(self.vocab_file , self.merges_file ) lowerCAmelCase_ : int = """lower""" lowerCAmelCase_ : str = ["""low""", """er</w>"""] lowerCAmelCase_ : Any = tokenizer.tokenize(lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) lowerCAmelCase_ : Dict = tokens + ["""<unk>"""] lowerCAmelCase_ : Optional[Any] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase ) , lowerCamelCase ) @slow def __lowercase ( self : str ) -> Optional[Any]: lowerCAmelCase_ : Dict = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) lowerCAmelCase_ : int = tokenizer.encode("""sequence builders""" , add_special_tokens=lowerCamelCase ) lowerCAmelCase_ : Optional[Any] = tokenizer.encode("""multi-sequence build""" , add_special_tokens=lowerCamelCase ) lowerCAmelCase_ : str = tokenizer.build_inputs_with_special_tokens(lowerCamelCase ) lowerCAmelCase_ : Optional[int] = tokenizer.build_inputs_with_special_tokens(lowerCamelCase , lowerCamelCase ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
120
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A = {'''configuration_reformer''': ['''REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ReformerConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''ReformerTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ['''ReformerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ '''REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ReformerAttention''', '''ReformerForMaskedLM''', '''ReformerForQuestionAnswering''', '''ReformerForSequenceClassification''', '''ReformerLayer''', '''ReformerModel''', '''ReformerModelWithLMHead''', '''ReformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
277
import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def __a ( lowerCAmelCase_ : Optional[int] ) -> List[Any]: '''simple docstring''' UpperCAmelCase_= [ """decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(lowerCAmelCase_ ,lowerCAmelCase_ ) def __a ( lowerCAmelCase_ : Any ) -> str: '''simple docstring''' UpperCAmelCase_, UpperCAmelCase_= emb.weight.shape UpperCAmelCase_= nn.Linear(lowerCAmelCase_ ,lowerCAmelCase_ ,bias=lowerCAmelCase_ ) UpperCAmelCase_= emb.weight.data return lin_layer def __a ( lowerCAmelCase_ : List[str] ) -> List[str]: '''simple docstring''' UpperCAmelCase_= torch.load(lowerCAmelCase_ ,map_location="""cpu""" ) UpperCAmelCase_= Namespace(**checkpoint["""cfg"""]["""model"""] ) UpperCAmelCase_= checkpoint["""model"""] remove_ignore_keys_(lowerCAmelCase_ ) UpperCAmelCase_= state_dict["""decoder.embed_tokens.weight"""].shape[0] UpperCAmelCase_= {key.replace("""decoder""" ,"""model""" ): val for key, val in state_dict.items()} UpperCAmelCase_= XGLMConfig( vocab_size=lowerCAmelCase_ ,max_position_embeddings=args.max_target_positions ,num_layers=args.decoder_layers ,attention_heads=args.decoder_attention_heads ,ffn_dim=args.decoder_ffn_embed_dim ,d_model=args.decoder_embed_dim ,layerdrop=args.decoder_layerdrop ,dropout=args.dropout ,attention_dropout=args.attention_dropout ,activation_dropout=args.activation_dropout ,activation_function="""gelu""" ,scale_embedding=not args.no_scale_embedding ,tie_word_embeddings=args.share_decoder_input_output_embed ,) UpperCAmelCase_= XGLMForCausalLM(lowerCAmelCase_ ) UpperCAmelCase_= model.load_state_dict(lowerCAmelCase_ ,strict=lowerCAmelCase_ ) print(lowerCAmelCase_ ) UpperCAmelCase_= make_linear_from_emb(model.model.embed_tokens ) return model if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument('''fairseq_path''', type=str, help='''path to a model.pt on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') __A = parser.parse_args() __A = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) model.save_pretrained(args.pytorch_dump_folder_path)
277
1
'''simple docstring''' import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() _snake_case = logging.get_logger('transformers.models.speecht5') def _A ( snake_case , snake_case , snake_case ) -> Dict: hf_model.apply_weight_norm() _lowercase : int = checkpoint['input_conv.weight_g'] _lowercase : Union[str, Any] = checkpoint['input_conv.weight_v'] _lowercase : Tuple = checkpoint['input_conv.bias'] for i in range(len(config.upsample_rates ) ): _lowercase : Tuple = checkpoint[F'''upsamples.{i}.1.weight_g'''] _lowercase : int = checkpoint[F'''upsamples.{i}.1.weight_v'''] _lowercase : List[str] = checkpoint[F'''upsamples.{i}.1.bias'''] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): _lowercase : str = checkpoint[F'''blocks.{i}.convs1.{j}.1.weight_g'''] _lowercase : str = checkpoint[F'''blocks.{i}.convs1.{j}.1.weight_v'''] _lowercase : List[str] = checkpoint[F'''blocks.{i}.convs1.{j}.1.bias'''] _lowercase : List[str] = checkpoint[F'''blocks.{i}.convs2.{j}.1.weight_g'''] _lowercase : Optional[Any] = checkpoint[F'''blocks.{i}.convs2.{j}.1.weight_v'''] _lowercase : Any = checkpoint[F'''blocks.{i}.convs2.{j}.1.bias'''] _lowercase : Optional[int] = checkpoint['output_conv.1.weight_g'] _lowercase : str = checkpoint['output_conv.1.weight_v'] _lowercase : Any = checkpoint['output_conv.1.bias'] hf_model.remove_weight_norm() @torch.no_grad() def _A ( snake_case , snake_case , snake_case , snake_case=None , snake_case=None , ) -> Optional[int]: if config_path is not None: _lowercase : List[Any] = SpeechTaHifiGanConfig.from_pretrained(UpperCAmelCase_ ) else: _lowercase : Optional[Any] = SpeechTaHifiGanConfig() _lowercase : Union[str, Any] = SpeechTaHifiGan(UpperCAmelCase_ ) _lowercase : List[Any] = torch.load(UpperCAmelCase_ ) load_weights(orig_checkpoint["model"]["generator"] , UpperCAmelCase_ , UpperCAmelCase_ ) _lowercase : Union[str, Any] = np.load(UpperCAmelCase_ ) _lowercase : Optional[Any] = stats[0].reshape(-1 ) _lowercase : Dict = stats[1].reshape(-1 ) _lowercase : int = torch.from_numpy(UpperCAmelCase_ ).float() _lowercase : int = torch.from_numpy(UpperCAmelCase_ ).float() model.save_pretrained(UpperCAmelCase_ ) if repo_id: print("Pushing to the hub..." ) model.push_to_hub(UpperCAmelCase_ ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--stats_path', required=True, default=None, type=str, help='Path to stats.npy file') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) _snake_case = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
250
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = "▁" lowercase__ = {"vocab_file": "spiece.model"} lowercase__ = { "vocab_file": { "google/reformer-crime-and-punishment": ( "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model" ) } } lowercase__ = { "google/reformer-crime-and-punishment": 524288, } class A_ ( _snake_case ): '''simple docstring''' UpperCAmelCase_ : Dict = VOCAB_FILES_NAMES UpperCAmelCase_ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ : Dict = ["""input_ids""", """attention_mask"""] def __init__( self : str , lowercase_ : Dict , lowercase_ : Tuple="</s>" , lowercase_ : Dict="<unk>" , lowercase_ : Tuple=[] , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : List[str] , ) -> None: UpperCAmelCase : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=lowercase_ , unk_token=lowercase_ , additional_special_tokens=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) UpperCAmelCase : List[Any] = vocab_file UpperCAmelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase_ ) @property def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: return self.sp_model.get_piece_size() def UpperCAmelCase_ ( self : List[str] ) -> Dict[str, int]: UpperCAmelCase : int = {self.convert_ids_to_tokens(lowercase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Any ) -> str: UpperCAmelCase : Tuple = self.__dict__.copy() UpperCAmelCase : Union[str, Any] = None return state def __setstate__( self : Optional[Any] , lowercase_ : Any ) -> List[str]: UpperCAmelCase : Dict = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): UpperCAmelCase : Dict = {} UpperCAmelCase : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCAmelCase_ ( self : List[Any] , lowercase_ : str ) -> List[str]: return self.sp_model.encode(lowercase_ , out_type=lowercase_ ) def UpperCAmelCase_ ( self : int , lowercase_ : Tuple ) -> Optional[int]: return self.sp_model.piece_to_id(lowercase_ ) def UpperCAmelCase_ ( self : List[str] , lowercase_ : Optional[int] ) -> List[str]: if index < self.sp_model.get_piece_size(): UpperCAmelCase : Tuple = self.sp_model.IdToPiece(lowercase_ ) return token def UpperCAmelCase_ ( self : List[str] , lowercase_ : Optional[int] ) -> Optional[int]: UpperCAmelCase : Dict = [] UpperCAmelCase : int = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(lowercase_ ) + token UpperCAmelCase : Any = [] else: current_sub_tokens.append(lowercase_ ) out_string += self.sp_model.decode(lowercase_ ) return out_string.strip() def UpperCAmelCase_ ( self : Union[str, Any] , lowercase_ : str , lowercase_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(lowercase_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase : int = os.path.join( lowercase_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowercase_ , 'wb' ) as fi: UpperCAmelCase : Optional[int] = self.sp_model.serialized_model_proto() fi.write(lowercase_ ) return (out_vocab_file,)
151
0
'''simple docstring''' import doctest from collections import deque import numpy as np class __lowerCamelCase : """simple docstring""" def __init__( self : List[Any]): _A : Any = [2, 1, 2, -1] _A : Optional[int] = [1, 2, 3, 4] def A ( self : int): _A : Any = len(self.first_signal) _A : Any = len(self.second_signal) _A : Union[str, Any] = max(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # create a zero matrix of max_length x max_length _A : Union[str, Any] = [[0] * max_length for i in range(SCREAMING_SNAKE_CASE)] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(SCREAMING_SNAKE_CASE): _A : str = deque(self.second_signal) rotated_signal.rotate(SCREAMING_SNAKE_CASE) for j, item in enumerate(SCREAMING_SNAKE_CASE): matrix[i][j] += item # multiply the matrix with the first signal _A : Union[str, Any] = np.matmul(np.transpose(SCREAMING_SNAKE_CASE) , np.transpose(self.first_signal)) # rounding-off to two decimal places return [round(SCREAMING_SNAKE_CASE , 2) for i in final_signal] if __name__ == "__main__": doctest.testmod()
227
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A : str = { '''configuration_blip''': [ '''BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BlipConfig''', '''BlipTextConfig''', '''BlipVisionConfig''', ], '''processing_blip''': ['''BlipProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[Any] = ['''BlipImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[Any] = [ '''BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BlipModel''', '''BlipPreTrainedModel''', '''BlipForConditionalGeneration''', '''BlipForQuestionAnswering''', '''BlipVisionModel''', '''BlipTextModel''', '''BlipForImageTextRetrieval''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Union[str, Any] = [ '''TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFBlipModel''', '''TFBlipPreTrainedModel''', '''TFBlipForConditionalGeneration''', '''TFBlipForQuestionAnswering''', '''TFBlipVisionModel''', '''TFBlipTextModel''', '''TFBlipForImageTextRetrieval''', ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys A : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
227
1
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset a_ = random.Random() def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase=1.0 , __UpperCamelCase=None , __UpperCamelCase=None ): if rng is None: __lowercase : Optional[int] = global_rng __lowercase : Dict = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCAmelCase_ ( unittest.TestCase ): def __init__( self , UpperCamelCase_ , UpperCamelCase_=7 , UpperCamelCase_=4_00 , UpperCamelCase_=20_00 , UpperCamelCase_=20_48 , UpperCamelCase_=1_28 , UpperCamelCase_=1 , UpperCamelCase_=5_12 , UpperCamelCase_=30 , UpperCamelCase_=4_41_00 , ) -> Dict: __lowercase : Optional[Any] = parent __lowercase : Optional[int] = batch_size __lowercase : Union[str, Any] = min_seq_length __lowercase : Dict = max_seq_length __lowercase : Any = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __lowercase : Optional[int] = spectrogram_length __lowercase : int = feature_size __lowercase : int = num_audio_channels __lowercase : Optional[Any] = hop_length __lowercase : Any = chunk_length __lowercase : List[str] = sampling_rate def _lowerCamelCase ( self ) -> Tuple: return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def _lowerCamelCase ( self , UpperCamelCase_=False , UpperCamelCase_=False ) -> Union[str, Any]: def _flatten(UpperCamelCase_ ): return list(itertools.chain(*lowercase_ ) ) if equal_length: __lowercase : List[Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __lowercase : List[Any] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __lowercase : Optional[int] = [np.asarray(lowercase_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCAmelCase_ ( UpperCamelCase_ , unittest.TestCase ): UpperCamelCase =TvltFeatureExtractor def _lowerCamelCase ( self ) -> List[str]: __lowercase : Any = TvltFeatureExtractionTester(self ) def _lowerCamelCase ( self ) -> Tuple: __lowercase : Tuple = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(lowercase_ , '''spectrogram_length''' ) ) self.assertTrue(hasattr(lowercase_ , '''feature_size''' ) ) self.assertTrue(hasattr(lowercase_ , '''num_audio_channels''' ) ) self.assertTrue(hasattr(lowercase_ , '''hop_length''' ) ) self.assertTrue(hasattr(lowercase_ , '''chunk_length''' ) ) self.assertTrue(hasattr(lowercase_ , '''sampling_rate''' ) ) def _lowerCamelCase ( self ) -> Tuple: __lowercase : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowercase : str = feat_extract_first.save_pretrained(lowercase_ )[0] check_json_file_has_correct_format(lowercase_ ) __lowercase : int = self.feature_extraction_class.from_pretrained(lowercase_ ) __lowercase : List[Any] = feat_extract_first.to_dict() __lowercase : Dict = feat_extract_second.to_dict() __lowercase : Optional[int] = dict_first.pop('''mel_filters''' ) __lowercase : List[str] = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(lowercase_ , lowercase_ ) ) self.assertEqual(lowercase_ , lowercase_ ) def _lowerCamelCase ( self ) -> Optional[Any]: __lowercase : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __lowercase : str = os.path.join(lowercase_ , '''feat_extract.json''' ) feat_extract_first.to_json_file(lowercase_ ) __lowercase : Tuple = self.feature_extraction_class.from_json_file(lowercase_ ) __lowercase : str = feat_extract_first.to_dict() __lowercase : Union[str, Any] = feat_extract_second.to_dict() __lowercase : Optional[int] = dict_first.pop('''mel_filters''' ) __lowercase : Dict = dict_second.pop('''mel_filters''' ) self.assertTrue(np.allclose(lowercase_ , lowercase_ ) ) self.assertEqual(lowercase_ , lowercase_ ) def _lowerCamelCase ( self ) -> Tuple: __lowercase : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 __lowercase : Any = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] __lowercase : List[str] = [np.asarray(lowercase_ ) for speech_input in speech_inputs] # Test not batched input __lowercase : Tuple = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched __lowercase : Optional[int] = feature_extractor(lowercase_ , return_tensors='''np''' , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking __lowercase : int = feature_extractor( lowercase_ , return_tensors='''np''' , sampling_rate=4_41_00 , mask_audio=lowercase_ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. __lowercase : Any = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] __lowercase : List[str] = np.asarray(lowercase_ ) __lowercase : Optional[Any] = feature_extractor(lowercase_ , return_tensors='''np''' , sampling_rate=4_41_00 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> str: __lowercase : Any = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech __lowercase : Tuple = ds.sort('''id''' ).select(range(lowercase_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def _lowerCamelCase ( self ) -> Union[str, Any]: __lowercase : str = self._load_datasamples(1 ) __lowercase : Optional[int] = TvltFeatureExtractor() __lowercase : int = feature_extractor(lowercase_ , return_tensors='''pt''' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 1_92, 1_28) ) __lowercase : str = torch.tensor([[-0.3_0_3_2, -0.2_7_0_8], [-0.4_4_3_4, -0.4_0_0_7]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , lowercase_ , atol=1E-4 ) )
249
import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers lowerCamelCase = 'python tqdm regex requests packaging filelock numpy tokenizers'.split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append('dataclasses') if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append('importlib_metadata') for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(F"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""") def a_ ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str=None ): '''simple docstring''' require_version(deps[pkg] , SCREAMING_SNAKE_CASE__ )
199
0
import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase_ : List[str] = logging.get_logger(__name__) UpperCAmelCase_ : str = { '''facebook/detr-resnet-50''': '''https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json''', # See all DETR models at https://huggingface.co/models?filter=detr } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : int = """detr""" snake_case__ : str = ["""past_key_values"""] snake_case__ : Tuple = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self : int , __lowerCamelCase : Tuple=True , __lowerCamelCase : Tuple=None , __lowerCamelCase : Optional[int]=3 , __lowerCamelCase : List[str]=100 , __lowerCamelCase : Optional[int]=6 , __lowerCamelCase : Optional[int]=2_048 , __lowerCamelCase : Any=8 , __lowerCamelCase : List[Any]=6 , __lowerCamelCase : Optional[Any]=2_048 , __lowerCamelCase : Union[str, Any]=8 , __lowerCamelCase : List[Any]=0.0 , __lowerCamelCase : Dict=0.0 , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : Tuple="relu" , __lowerCamelCase : Any=256 , __lowerCamelCase : List[Any]=0.1 , __lowerCamelCase : List[Any]=0.0 , __lowerCamelCase : Optional[int]=0.0 , __lowerCamelCase : Dict=0.02 , __lowerCamelCase : Dict=1.0 , __lowerCamelCase : Union[str, Any]=False , __lowerCamelCase : List[str]="sine" , __lowerCamelCase : Union[str, Any]="resnet50" , __lowerCamelCase : str=True , __lowerCamelCase : Union[str, Any]=False , __lowerCamelCase : Optional[int]=1 , __lowerCamelCase : Tuple=5 , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : Tuple=1 , __lowerCamelCase : List[Any]=1 , __lowerCamelCase : Optional[int]=5 , __lowerCamelCase : Union[str, Any]=2 , __lowerCamelCase : Optional[Any]=0.1 , **__lowerCamelCase : Dict , ): if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) UpperCamelCase :List[str] = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase :int = backbone_config.get("""model_type""" ) UpperCamelCase :Tuple = CONFIG_MAPPING[backbone_model_type] UpperCamelCase :List[Any] = config_class.from_dict(__lowerCamelCase ) # set timm attributes to None UpperCamelCase :List[Any] = None, None, None UpperCamelCase :int = use_timm_backbone UpperCamelCase :Tuple = backbone_config UpperCamelCase :Union[str, Any] = num_channels UpperCamelCase :Any = num_queries UpperCamelCase :List[str] = d_model UpperCamelCase :Optional[Any] = encoder_ffn_dim UpperCamelCase :str = encoder_layers UpperCamelCase :str = encoder_attention_heads UpperCamelCase :Any = decoder_ffn_dim UpperCamelCase :Optional[Any] = decoder_layers UpperCamelCase :List[str] = decoder_attention_heads UpperCamelCase :str = dropout UpperCamelCase :Tuple = attention_dropout UpperCamelCase :int = activation_dropout UpperCamelCase :int = activation_function UpperCamelCase :int = init_std UpperCamelCase :Tuple = init_xavier_std UpperCamelCase :int = encoder_layerdrop UpperCamelCase :Any = decoder_layerdrop UpperCamelCase :Dict = encoder_layers UpperCamelCase :Any = auxiliary_loss UpperCamelCase :List[Any] = position_embedding_type UpperCamelCase :List[Any] = backbone UpperCamelCase :List[str] = use_pretrained_backbone UpperCamelCase :List[Any] = dilation # Hungarian matcher UpperCamelCase :Tuple = class_cost UpperCamelCase :Tuple = bbox_cost UpperCamelCase :Optional[int] = giou_cost # Loss coefficients UpperCamelCase :int = mask_loss_coefficient UpperCamelCase :List[Any] = dice_loss_coefficient UpperCamelCase :Optional[int] = bbox_loss_coefficient UpperCamelCase :Dict = giou_loss_coefficient UpperCamelCase :List[Any] = eos_coefficient super().__init__(is_encoder_decoder=__lowerCamelCase , **__lowerCamelCase ) @property def _A ( self : Any ): return self.encoder_attention_heads @property def _A ( self : List[str] ): return self.d_model @classmethod def _A ( cls : str , __lowerCamelCase : PretrainedConfig , **__lowerCamelCase : str ): return cls(backbone_config=__lowerCamelCase , **__lowerCamelCase ) def _A ( self : List[Any] ): UpperCamelCase :Dict = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: UpperCamelCase :List[str] = self.backbone_config.to_dict() UpperCamelCase :List[Any] = self.__class__.model_type return output class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : List[str] = version.parse("""1.11""" ) @property def _A ( self : Any ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def _A ( self : Optional[int] ): return 1E-5 @property def _A ( self : Any ): return 12
360
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Union[str, Any] = """char""" snake_case__ : Optional[int] = """bpe""" snake_case__ : Dict = """wp""" UpperCAmelCase_ : List[Any] = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : List[Any] = ["""image_processor""", """char_tokenizer"""] snake_case__ : Dict = """ViTImageProcessor""" snake_case__ : List[str] = """MgpstrTokenizer""" def __init__( self : Optional[int] , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Dict=None , **__lowerCamelCase : Any ): UpperCamelCase :Optional[Any] = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __lowerCamelCase , ) UpperCamelCase :Optional[int] = kwargs.pop("""feature_extractor""" ) UpperCamelCase :List[str] = 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`.""" ) UpperCamelCase :Optional[int] = tokenizer UpperCamelCase :int = AutoTokenizer.from_pretrained("""gpt2""" ) UpperCamelCase :int = AutoTokenizer.from_pretrained("""bert-base-uncased""" ) super().__init__(__lowerCamelCase , __lowerCamelCase ) def __call__( self : str , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Dict=None , __lowerCamelCase : str=None , **__lowerCamelCase : Dict ): if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: UpperCamelCase :Tuple = self.image_processor(__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase ) if text is not None: UpperCamelCase :Any = self.char_tokenizer(__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase ) if text is None: return inputs elif images is None: return encodings else: UpperCamelCase :Dict = encodings["""input_ids"""] return inputs def _A ( self : Tuple , __lowerCamelCase : str ): UpperCamelCase , UpperCamelCase , UpperCamelCase :int = sequences UpperCamelCase :Tuple = char_preds.size(0 ) UpperCamelCase , UpperCamelCase :str = self._decode_helper(__lowerCamelCase , """char""" ) UpperCamelCase , UpperCamelCase :List[Any] = self._decode_helper(__lowerCamelCase , """bpe""" ) UpperCamelCase , UpperCamelCase :List[Any] = self._decode_helper(__lowerCamelCase , """wp""" ) UpperCamelCase :Any = [] UpperCamelCase :str = [] for i in range(__lowerCamelCase ): UpperCamelCase :Union[str, Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] UpperCamelCase :Any = [char_strs[i], bpe_strs[i], wp_strs[i]] UpperCamelCase :str = scores.index(max(__lowerCamelCase ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) UpperCamelCase :Optional[Any] = {} UpperCamelCase :Dict = final_strs UpperCamelCase :Union[str, Any] = final_scores UpperCamelCase :List[str] = char_strs UpperCamelCase :Tuple = bpe_strs UpperCamelCase :Optional[Any] = wp_strs return out def _A ( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] ): if format == DecodeType.CHARACTER: UpperCamelCase :List[str] = self.char_decode UpperCamelCase :Union[str, Any] = 1 UpperCamelCase :Optional[Any] = """[s]""" elif format == DecodeType.BPE: UpperCamelCase :Union[str, Any] = self.bpe_decode UpperCamelCase :str = 2 UpperCamelCase :int = """#""" elif format == DecodeType.WORDPIECE: UpperCamelCase :int = self.wp_decode UpperCamelCase :Any = 102 UpperCamelCase :int = """[SEP]""" else: raise ValueError(F"""Format {format} is not supported.""" ) UpperCamelCase , UpperCamelCase :int = [], [] UpperCamelCase :Any = pred_logits.size(0 ) UpperCamelCase :List[Any] = pred_logits.size(1 ) UpperCamelCase , UpperCamelCase :Optional[int] = pred_logits.topk(1 , dim=-1 , largest=__lowerCamelCase , sorted=__lowerCamelCase ) UpperCamelCase :Optional[Any] = preds_index.view(-1 , __lowerCamelCase )[:, 1:] UpperCamelCase :int = decoder(__lowerCamelCase ) UpperCamelCase , UpperCamelCase :Optional[int] = torch.nn.functional.softmax(__lowerCamelCase , dim=2 ).max(dim=2 ) UpperCamelCase :Tuple = preds_max_prob[:, 1:] for index in range(__lowerCamelCase ): UpperCamelCase :Tuple = preds_str[index].find(__lowerCamelCase ) UpperCamelCase :List[Any] = preds_str[index][:pred_eos] UpperCamelCase :List[Any] = preds_index[index].cpu().tolist() UpperCamelCase :Optional[Any] = pred_index.index(__lowerCamelCase ) if eos_token in pred_index else -1 UpperCamelCase :List[str] = preds_max_prob[index][: pred_eos_index + 1] UpperCamelCase :List[str] = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(__lowerCamelCase ) conf_scores.append(__lowerCamelCase ) return dec_strs, conf_scores def _A ( self : Optional[Any] , __lowerCamelCase : str ): UpperCamelCase :Dict = [seq.replace(""" """ , """""" ) for seq in self.char_tokenizer.batch_decode(__lowerCamelCase )] return decode_strs def _A ( self : Union[str, Any] , __lowerCamelCase : str ): return self.bpe_tokenizer.batch_decode(__lowerCamelCase ) def _A ( self : int , __lowerCamelCase : Optional[int] ): UpperCamelCase :Any = [seq.replace(""" """ , """""" ) for seq in self.wp_tokenizer.batch_decode(__lowerCamelCase )] return decode_strs
62
0
from itertools import product def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> list[int]: lowerCamelCase : List[str] = sides_number lowerCamelCase : int = max_face_number * dice_number lowerCamelCase : List[Any] = [0] * (max_total + 1) lowerCamelCase : int = 1 lowerCamelCase : Union[str, Any] = range(lowerCAmelCase_ ,max_face_number + 1 ) for dice_numbers in product(lowerCAmelCase_ ,repeat=lowerCAmelCase_ ): lowerCamelCase : List[str] = sum(lowerCAmelCase_ ) totals_frequencies[total] += 1 return totals_frequencies def A ( ) -> float: lowerCamelCase : Tuple = total_frequency_distribution( sides_number=4 ,dice_number=9 ) lowerCamelCase : Union[str, Any] = total_frequency_distribution( sides_number=6 ,dice_number=6 ) lowerCamelCase : Union[str, Any] = 0 lowerCamelCase : List[str] = 9 lowerCamelCase : str = 4 * 9 lowerCamelCase : Optional[int] = 6 for peter_total in range(lowerCAmelCase_ ,max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) lowerCamelCase : Optional[int] = (4**9) * (6**6) lowerCamelCase : Optional[int] = peter_wins_count / total_games_number lowerCamelCase : Optional[int] = round(lowerCAmelCase_ ,ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(f'''{solution() = }''')
48
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase A_ : Any = logging.get_logger(__name__) A_ : Optional[int] = { """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json""", """allenai/longformer-large-4096""": """https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json""", """allenai/longformer-large-4096-finetuned-triviaqa""": ( """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json""" ), """allenai/longformer-base-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json""" ), """allenai/longformer-large-4096-extra.pos.embd.only""": ( """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json""" ), } class lowercase ( _lowerCamelCase ): """simple docstring""" UpperCAmelCase = """longformer""" def __init__( self ,a_ = 512 ,a_ = 2 ,a_ = 1 ,a_ = 0 ,a_ = 2 ,a_ = 30_522 ,a_ = 768 ,a_ = 12 ,a_ = 12 ,a_ = 3_072 ,a_ = "gelu" ,a_ = 0.1 ,a_ = 0.1 ,a_ = 512 ,a_ = 2 ,a_ = 0.02 ,a_ = 1E-1_2 ,a_ = False ,**a_ ,) -> List[Any]: super().__init__(pad_token_id=a_ ,**a_ ) _UpperCAmelCase : List[Any] = attention_window _UpperCAmelCase : Any = sep_token_id _UpperCAmelCase : Dict = bos_token_id _UpperCAmelCase : Tuple = eos_token_id _UpperCAmelCase : Tuple = vocab_size _UpperCAmelCase : Optional[Any] = hidden_size _UpperCAmelCase : Optional[int] = num_hidden_layers _UpperCAmelCase : Union[str, Any] = num_attention_heads _UpperCAmelCase : Optional[int] = hidden_act _UpperCAmelCase : str = intermediate_size _UpperCAmelCase : List[Any] = hidden_dropout_prob _UpperCAmelCase : Union[str, Any] = attention_probs_dropout_prob _UpperCAmelCase : List[str] = max_position_embeddings _UpperCAmelCase : Optional[int] = type_vocab_size _UpperCAmelCase : Any = initializer_range _UpperCAmelCase : Optional[int] = layer_norm_eps _UpperCAmelCase : Union[str, Any] = onnx_export class lowercase ( _lowerCamelCase ): """simple docstring""" def __init__( self ,a_ ,a_ = "default" ,a_ = None ) -> int: super().__init__(a_ ,a_ ,a_ ) _UpperCAmelCase : Tuple = True @property def _snake_case ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _UpperCAmelCase : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _UpperCAmelCase : Tuple = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""global_attention_mask""", dynamic_axis), ] ) @property def _snake_case ( self ) -> Mapping[str, Mapping[int, str]]: _UpperCAmelCase : str = super().outputs if self.task == "default": _UpperCAmelCase : int = {0: """batch"""} return outputs @property def _snake_case ( self ) -> float: return 1E-4 @property def _snake_case ( self ) -> int: # needs to be >= 14 to support tril operator return max(super().default_onnx_opset ,14 ) def _snake_case ( self ,a_ ,a_ = -1 ,a_ = -1 ,a_ = False ,a_ = None ,) -> Mapping[str, Any]: _UpperCAmelCase : List[str] = super().generate_dummy_inputs( preprocessor=a_ ,batch_size=a_ ,seq_length=a_ ,is_pair=a_ ,framework=a_ ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly _UpperCAmelCase : int = torch.zeros_like(inputs["""input_ids"""] ) # make every second token global _UpperCAmelCase : List[str] = 1 return inputs
215
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCAmelCase__ = { "configuration_clip": [ "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPConfig", "CLIPOnnxConfig", "CLIPTextConfig", "CLIPVisionConfig", ], "processing_clip": ["CLIPProcessor"], "tokenization_clip": ["CLIPTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["CLIPTokenizerFast"] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["CLIPFeatureExtractor"] UpperCAmelCase__ = ["CLIPImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPModel", "CLIPPreTrainedModel", "CLIPTextModel", "CLIPTextModelWithProjection", "CLIPVisionModel", "CLIPVisionModelWithProjection", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCLIPModel", "TFCLIPPreTrainedModel", "TFCLIPTextModel", "TFCLIPVisionModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "FlaxCLIPModel", "FlaxCLIPPreTrainedModel", "FlaxCLIPTextModel", "FlaxCLIPTextPreTrainedModel", "FlaxCLIPVisionModel", "FlaxCLIPVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
290
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def A ( ) -> tuple[list[int], int]: '''simple docstring''' _UpperCAmelCase = [randint(-1_000 , 1_000 ) for i in range(10 )] _UpperCAmelCase = randint(-5_000 , 5_000 ) return (arr, r) UpperCAmelCase__ = make_dataset() def A ( _UpperCAmelCase : list[int] , _UpperCAmelCase : int ) -> tuple[int, ...]: '''simple docstring''' for triplet in permutations(_UpperCAmelCase , 3 ): if sum(_UpperCAmelCase ) == target: return tuple(sorted(_UpperCAmelCase ) ) return (0, 0, 0) def A ( _UpperCAmelCase : list[int] , _UpperCAmelCase : int ) -> tuple[int, int, int]: '''simple docstring''' arr.sort() _UpperCAmelCase = len(_UpperCAmelCase ) for i in range(n - 1 ): _UpperCAmelCase , _UpperCAmelCase = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def A ( ) -> tuple[float, float]: '''simple docstring''' _UpperCAmelCase = '\nfrom __main__ import dataset, triplet_sum1, triplet_sum2\n' _UpperCAmelCase = '\ntriplet_sum1(*dataset)\n' _UpperCAmelCase = '\ntriplet_sum2(*dataset)\n' _UpperCAmelCase = repeat(setup=_UpperCAmelCase , stmt=_UpperCAmelCase , repeat=5 , number=10_000 ) _UpperCAmelCase = repeat(setup=_UpperCAmelCase , stmt=_UpperCAmelCase , repeat=5 , number=10_000 ) return (min(_UpperCAmelCase ), min(_UpperCAmelCase )) if __name__ == "__main__": from doctest import testmod testmod() UpperCAmelCase__ = solution_times() print(f"""The time for naive implementation is {times[0]}.""") print(f"""The time for optimized implementation is {times[1]}.""")
290
1
'''simple docstring''' import re def UpperCAmelCase ( a_ ) -> list: """simple docstring""" return [char.split() for char in re.split(R"""[^ a-z A-Z 0-9 \s]""" , str_ )] def UpperCAmelCase ( a_ ) -> str: """simple docstring""" A_ : str = split_input(str_ ) return "".join( ["""""".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def UpperCAmelCase ( a_ , a_ , a_ ) -> str: """simple docstring""" try: A_ : Union[str, Any] = split_input(a_ ) if upper: A_ : Any = """""".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: A_ : Tuple = """""".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 UpperCAmelCase ( a_ ) -> str: """simple docstring""" return to_simple_case(a_ ) def UpperCAmelCase ( a_ ) -> str: """simple docstring""" try: A_ : str = to_simple_case(a_ ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" return to_complex_case(a_ , a_ , """_""" ) def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" return to_complex_case(a_ , a_ , """-""" ) if __name__ == "__main__": __import__('doctest').testmod()
344
'''simple docstring''' class _lowerCAmelCase : """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> Union[str, Any]: A_ : Optional[Any] = name A_ : Dict = value A_ : Union[str, Any] = weight def __repr__( self ) -> List[str]: return F"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})" def UpperCAmelCase_ ( self ) -> Optional[Any]: return self.value def UpperCAmelCase_ ( self ) -> List[str]: return self.name def UpperCAmelCase_ ( self ) -> Tuple: return self.weight def UpperCAmelCase_ ( self ) -> Optional[int]: return self.value / self.weight def UpperCAmelCase ( a_ , a_ , a_ ) -> str: """simple docstring""" A_ : Optional[int] = [] for i in range(len(a_ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def UpperCAmelCase ( a_ , a_ , a_ ) -> List[Any]: """simple docstring""" A_ : Optional[Any] = sorted(a_ , key=a_ , reverse=a_ ) A_ : str = [] A_ , A_ : Dict = 0.0, 0.0 for i in range(len(a_ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def UpperCAmelCase ( ) -> Tuple: """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
344
1
def UpperCAmelCase__ ( lowerCamelCase, lowerCamelCase ): if not isinstance(lowerCamelCase, lowerCamelCase ): raise ValueError("iterations must be defined as integers" ) if not isinstance(lowerCamelCase, lowerCamelCase ) or not number >= 1: raise ValueError( "starting number must be\n and integer and be more than 0" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz" ) lowercase :Any = "" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(lowerCamelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
158
from collections.abc import Iterable from typing import Generic, TypeVar _UpperCAmelCase : Any = TypeVar("_T") class __lowerCAmelCase ( Generic[_T]): def __init__( self: Union[str, Any] , _lowerCAmelCase: Iterable[_T] | None = None ): lowercase :list[_T] = list(iterable or [] ) lowercase :list[_T] = [] def __len__( self: Dict ): return len(self._stacka ) + len(self._stacka ) def __repr__( self: List[Any] ): return F"Queue({tuple(self._stacka[::-1] + self._stacka )})" def SCREAMING_SNAKE_CASE ( self: Union[str, Any] , _lowerCAmelCase: _T ): self._stacka.append(_lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self: Any ): lowercase :int = self._stacka.pop lowercase :List[Any] = self._stacka.append if not self._stacka: while self._stacka: stacka_append(stacka_pop() ) if not self._stacka: raise IndexError("Queue is empty" ) return self._stacka.pop() if __name__ == "__main__": from doctest import testmod testmod()
158
1
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split __lowerCAmelCase : List[Any] =datasets.load_iris() __lowerCAmelCase : Tuple =np.array(data['data']) __lowerCAmelCase : Dict =np.array(data['target']) __lowerCAmelCase : List[str] =data['target_names'] __lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase : str =train_test_split(X, y) def _UpperCamelCase ( lowercase__ , lowercase__ ): return np.linalg.norm(np.array(lowercase__ ) - np.array(lowercase__ ) ) def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__=5 ): __SCREAMING_SNAKE_CASE : Optional[int] = zip(lowercase__ , lowercase__ ) # List of distances of all points from the point to be classified __SCREAMING_SNAKE_CASE : Dict = [] for data_point in data: __SCREAMING_SNAKE_CASE : Tuple = euclidean_distance(data_point[0] , lowercase__ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. __SCREAMING_SNAKE_CASE : int = [i[1] for i in sorted(lowercase__ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified __SCREAMING_SNAKE_CASE : Any = Counter(lowercase__ ).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]))
9
import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class _lowercase : '''simple docstring''' @staticmethod def __magic_name__( *lowerCAmelCase__ :Union[str, Any] , **lowerCAmelCase__ :str ) -> Union[str, Any]: pass def _UpperCamelCase ( lowercase__ ): return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. __lowerCAmelCase : str =( 'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png' ) @is_pipeline_test @require_torch @require_vision class _lowercase ( unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def __magic_name__( self :Any , lowerCAmelCase__ :List[str] , lowerCAmelCase__ :Optional[Any] , lowerCAmelCase__ :Any ) -> Any: __SCREAMING_SNAKE_CASE : Optional[int] = pipeline( '''document-question-answering''' , model=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Dict = INVOICE_URL __SCREAMING_SNAKE_CASE : Optional[Any] = list(zip(*apply_tesseract(load_image(lowerCAmelCase__ ) , lowerCAmelCase__ , '''''' ) ) ) __SCREAMING_SNAKE_CASE : str = '''What is the placebo?''' __SCREAMING_SNAKE_CASE : str = [ { '''image''': load_image(lowerCAmelCase__ ), '''question''': question, }, { '''image''': image, '''question''': question, }, { '''image''': image, '''question''': question, '''word_boxes''': word_boxes, }, ] return dqa_pipeline, examples def __magic_name__( self :Optional[Any] , lowerCAmelCase__ :Tuple , lowerCAmelCase__ :Tuple ) -> str: __SCREAMING_SNAKE_CASE : Any = dqa_pipeline(lowerCAmelCase__ , top_k=2 ) self.assertEqual( lowerCAmelCase__ , [ [ {'''score''': ANY(lowerCAmelCase__ ), '''answer''': ANY(lowerCAmelCase__ ), '''start''': ANY(lowerCAmelCase__ ), '''end''': ANY(lowerCAmelCase__ )}, {'''score''': ANY(lowerCAmelCase__ ), '''answer''': ANY(lowerCAmelCase__ ), '''start''': ANY(lowerCAmelCase__ ), '''end''': ANY(lowerCAmelCase__ )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def __magic_name__( self :Dict ) -> List[str]: __SCREAMING_SNAKE_CASE : Tuple = pipeline('''document-question-answering''' , model='''hf-internal-testing/tiny-random-layoutlmv2''' ) __SCREAMING_SNAKE_CASE : Dict = INVOICE_URL __SCREAMING_SNAKE_CASE : int = '''How many cats are there?''' __SCREAMING_SNAKE_CASE : Optional[int] = [ {'''score''': 0.0001, '''answer''': '''oy 2312/2019''', '''start''': 38, '''end''': 39}, {'''score''': 0.0001, '''answer''': '''oy 2312/2019 DUE''', '''start''': 38, '''end''': 40}, ] __SCREAMING_SNAKE_CASE : Tuple = dqa_pipeline(image=lowerCAmelCase__ , question=lowerCAmelCase__ , top_k=2 ) self.assertEqual(nested_simplify(lowerCAmelCase__ , decimals=4 ) , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Dict = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual(nested_simplify(lowerCAmelCase__ , decimals=4 ) , lowerCAmelCase__ ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably __SCREAMING_SNAKE_CASE : Any = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' __SCREAMING_SNAKE_CASE : List[Any] = dqa_pipeline(image=lowerCAmelCase__ , question=lowerCAmelCase__ , top_k=2 ) self.assertEqual(lowerCAmelCase__ , [] ) # We can optionnally pass directly the words and bounding boxes __SCREAMING_SNAKE_CASE : Union[str, Any] = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' __SCREAMING_SNAKE_CASE : Union[str, Any] = [] __SCREAMING_SNAKE_CASE : Union[str, Any] = [] __SCREAMING_SNAKE_CASE : Union[str, Any] = dqa_pipeline(image=lowerCAmelCase__ , question=lowerCAmelCase__ , words=lowerCAmelCase__ , boxes=lowerCAmelCase__ , top_k=2 ) self.assertEqual(lowerCAmelCase__ , [] ) @slow @require_torch @require_detectrona @require_pytesseract def __magic_name__( self :int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE : List[Any] = pipeline( '''document-question-answering''' , model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''' , revision='''9977165''' , ) __SCREAMING_SNAKE_CASE : Dict = INVOICE_URL __SCREAMING_SNAKE_CASE : Any = '''What is the invoice number?''' __SCREAMING_SNAKE_CASE : Any = dqa_pipeline(image=lowerCAmelCase__ , question=lowerCAmelCase__ , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ {'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) __SCREAMING_SNAKE_CASE : Tuple = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ {'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) __SCREAMING_SNAKE_CASE : List[Any] = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ [ {'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def __magic_name__( self :Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE : int = pipeline( '''document-question-answering''' , model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''' , revision='''9977165''' , max_seq_len=50 , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = INVOICE_URL __SCREAMING_SNAKE_CASE : Tuple = '''What is the invoice number?''' __SCREAMING_SNAKE_CASE : List[str] = dqa_pipeline(image=lowerCAmelCase__ , question=lowerCAmelCase__ , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ {'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, {'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) __SCREAMING_SNAKE_CASE : int = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ {'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, {'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) __SCREAMING_SNAKE_CASE : str = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ [ {'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, {'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def __magic_name__( self :int ) -> List[Any]: __SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained( '''impira/layoutlm-document-qa''' , revision='''3dc6de3''' , add_prefix_space=lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Dict = pipeline( '''document-question-answering''' , model='''impira/layoutlm-document-qa''' , tokenizer=lowerCAmelCase__ , revision='''3dc6de3''' , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = INVOICE_URL __SCREAMING_SNAKE_CASE : str = '''What is the invoice number?''' __SCREAMING_SNAKE_CASE : Dict = dqa_pipeline(image=lowerCAmelCase__ , question=lowerCAmelCase__ , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ] , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ] , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ [ {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ] ] * 2 , ) __SCREAMING_SNAKE_CASE : Optional[int] = list(zip(*apply_tesseract(load_image(lowerCAmelCase__ ) , lowerCAmelCase__ , '''''' ) ) ) # This model should also work if `image` is set to None __SCREAMING_SNAKE_CASE : str = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ] , ) @slow @require_torch @require_pytesseract @require_vision def __magic_name__( self :str ) -> Dict: __SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained( '''impira/layoutlm-document-qa''' , revision='''3dc6de3''' , add_prefix_space=lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Tuple = pipeline( '''document-question-answering''' , model='''impira/layoutlm-document-qa''' , tokenizer=lowerCAmelCase__ , revision='''3dc6de3''' , max_seq_len=50 , ) __SCREAMING_SNAKE_CASE : List[str] = INVOICE_URL __SCREAMING_SNAKE_CASE : Dict = '''What is the invoice number?''' __SCREAMING_SNAKE_CASE : List[Any] = dqa_pipeline(image=lowerCAmelCase__ , question=lowerCAmelCase__ , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ {'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) __SCREAMING_SNAKE_CASE : Optional[int] = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ [ {'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] ] * 2 , ) __SCREAMING_SNAKE_CASE : List[str] = list(zip(*apply_tesseract(load_image(lowerCAmelCase__ ) , lowerCAmelCase__ , '''''' ) ) ) # This model should also work if `image` is set to None __SCREAMING_SNAKE_CASE : List[Any] = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase__ , decimals=4 ) , [ {'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) @slow @require_torch def __magic_name__( self :Union[str, Any] ) -> Tuple: __SCREAMING_SNAKE_CASE : str = pipeline( '''document-question-answering''' , model='''naver-clova-ix/donut-base-finetuned-docvqa''' , tokenizer=AutoTokenizer.from_pretrained('''naver-clova-ix/donut-base-finetuned-docvqa''' ) , feature_extractor='''naver-clova-ix/donut-base-finetuned-docvqa''' , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = INVOICE_URL __SCREAMING_SNAKE_CASE : Optional[int] = '''What is the invoice number?''' __SCREAMING_SNAKE_CASE : Tuple = dqa_pipeline(image=lowerCAmelCase__ , question=lowerCAmelCase__ , top_k=2 ) self.assertEqual(nested_simplify(lowerCAmelCase__ , decimals=4 ) , [{'''answer''': '''us-001'''}] ) @require_tf @unittest.skip('''Document question answering not implemented in TF''' ) def __magic_name__( self :Union[str, Any] ) -> Tuple: pass
9
1
"""simple docstring""" from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) SCREAMING_SNAKE_CASE = 2_9979_2458 # Symbols SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = symbols("ct x y z") def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> float: if velocity > c: raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!" ) elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError("Speed must be greater than or equal to 1!" ) return velocity / c def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> float: return 1 / sqrt(1 - beta(lowercase_ ) ** 2 ) def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> np.ndarray: return np.array( [ [gamma(lowercase_ ), -gamma(lowercase_ ) * beta(lowercase_ ), 0, 0], [-gamma(lowercase_ ) * beta(lowercase_ ), gamma(lowercase_ ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def _SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ = None ) -> np.ndarray: # Ensure event is not empty if event is None: A__ = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(lowercase_ ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: SCREAMING_SNAKE_CASE = transform(2997_9245) print("Example of four vector: ") print(f'ct\' = {four_vector[0]}') print(f'x\' = {four_vector[1]}') print(f'y\' = {four_vector[2]}') print(f'z\' = {four_vector[3]}') # Substitute symbols with numerical values SCREAMING_SNAKE_CASE = {ct: c, x: 1, y: 1, z: 1} SCREAMING_SNAKE_CASE = [four_vector[i].subs(sub_dict) for i in range(4)] print(f'\n{numerical_vector}')
354
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def _SCREAMING_SNAKE_CASE ( lowercase_=None ) -> Any: if subparsers is not None: A__ = subparsers.add_parser("env" ) else: A__ = argparse.ArgumentParser("Accelerate env command" ) parser.add_argument( "--config_file" , default=lowercase_ , help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=lowercase_ ) return parser def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: A__ = torch.__version__ A__ = torch.cuda.is_available() A__ = is_xpu_available() A__ = is_npu_available() A__ = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowercase_ ): A__ = load_config_from_file(args.config_file ).to_dict() A__ = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "PyTorch XPU available": str(lowercase_ ), "PyTorch NPU available": str(lowercase_ ), "System RAM": f"""{psutil.virtual_memory().total / 10_24 ** 3:.2f} GB""", } if pt_cuda_available: A__ = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n" ) print("\n".join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:" ) A__ = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(lowercase_ , lowercase_ ) else f"""\t{accelerate_config}""" ) print(lowercase_ ) A__ = accelerate_config return info def _SCREAMING_SNAKE_CASE ( ) -> int: A__ = env_command_parser() A__ = parser.parse_args() env_command(lowercase_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
230
0
def lowerCamelCase__ ( __lowerCamelCase : int = 600851475143 ): try: __UpperCAmelCase : Optional[Any] = int(__lowerCamelCase ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""Parameter n must be greater than or equal to one.""" ) __UpperCAmelCase : Union[str, Any] = 1 __UpperCAmelCase : str = 2 while i * i <= n: while n % i == 0: __UpperCAmelCase : str = i n //= i i += 1 if n > 1: __UpperCAmelCase : Any = n return int(__lowerCamelCase ) if __name__ == "__main__": print(f"""{solution() = }""")
114
from __future__ import annotations from math import pi def lowerCamelCase__ ( __lowerCamelCase : float , __lowerCamelCase : float , __lowerCamelCase : float ): if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if inductance < 0: raise ValueError("""Inductance cannot be negative""" ) if frequency < 0: raise ValueError("""Frequency cannot be negative""" ) if reactance < 0: raise ValueError("""Inductive reactance cannot be negative""" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
114
1
'''simple docstring''' import os from pathlib import Path def SCREAMING_SNAKE_CASE_ ( __A : Tuple , __A : List[Any] , __A : List[Any] ) -> int: _SCREAMING_SNAKE_CASE = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] _SCREAMING_SNAKE_CASE = { "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } _SCREAMING_SNAKE_CASE = f"""{src_lang}-{tgt_lang}""" _SCREAMING_SNAKE_CASE = f""" --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt19 - facebook license: apache-2.0 datasets: - wmt19 metrics: - bleu --- # FSMT ## Model description This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}. For more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616). The abbreviation FSMT stands for FairSeqMachineTranslation All four models are available: * [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru) * [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en) * [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de) * [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = \"facebook/wmt19-{src_lang}-{tgt_lang}\" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = \"{texts[src_lang]}\" input_ids = tokenizer.encode(input, return_tensors=\"pt\") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias - The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981) ## Training data Pretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616). ## Eval results pair | fairseq | transformers -------|---------|---------- {pair} | {scores[pair][0]} | {scores[pair][1]} The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support: - model ensemble, therefore the best performing checkpoint was ported (``model4.pt``). - re-ranking The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=15 mkdir -p $DATA_DIR sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`. ## Data Sources - [training, etc.](http://www.statmt.org/wmt19/) - [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561) ### BibTeX entry and citation info ```bibtex @inproceedings{{..., year={{2020}}, title={{Facebook FAIR's WMT19 News Translation Task Submission}}, author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}}, booktitle={{Proc. of WMT}}, }} ``` ## TODO - port model ensemble (fairseq uses 4 model checkpoints) """ os.makedirs(__A , exist_ok=__A ) _SCREAMING_SNAKE_CASE = os.path.join(__A , "README.md" ) print(f"""Generating {path}""" ) with open(__A , "w" , encoding="utf-8" ) as f: f.write(__A ) # make sure we are under the root of the project lowerCamelCase_ = Path(__file__).resolve().parent.parent.parent lowerCamelCase_ = repo_dir / "model_cards" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = model_name.split("-") lowerCamelCase_ = model_cards_dir / "facebook" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
358
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase_ = { 'configuration_bridgetower': [ 'BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BridgeTowerConfig', 'BridgeTowerTextConfig', 'BridgeTowerVisionConfig', ], 'processing_bridgetower': ['BridgeTowerProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['BridgeTowerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ 'BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST', 'BridgeTowerForContrastiveLearning', 'BridgeTowerForImageAndTextRetrieval', 'BridgeTowerForMaskedLM', 'BridgeTowerModel', 'BridgeTowerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure)
111
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _lowerCamelCase : Optional[int] = { '''configuration_encodec''': [ '''ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''EncodecConfig''', ], '''feature_extraction_encodec''': ['''EncodecFeatureExtractor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Optional[int] = [ '''ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST''', '''EncodecModel''', '''EncodecPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys _lowerCamelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
282
import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' @slow def A ( self : int ): '''simple docstring''' _snake_case = FlaxXLMRobertaModel.from_pretrained('xlm-roberta-base' ) _snake_case = AutoTokenizer.from_pretrained('xlm-roberta-base' ) _snake_case = 'The dog is cute and lives in the garden house' _snake_case = jnp.array([tokenizer.encode(lowercase )] ) _snake_case = (1, 12, 768) # batch_size, sequence_length, embedding_vector_dim _snake_case = jnp.array( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) _snake_case = model(lowercase )['last_hidden_state'] self.assertEqual(output.shape , lowercase ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] , lowercase , atol=1E-3 ) )
282
1
import math def UpperCAmelCase_( a__ , a__): """simple docstring""" if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(a__) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError('''This should never happen''') if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. a__ : List[Any] = '''Enter the base and the power separated by a comma: ''' a__ : Dict = map(int, input(prompt).split(''',''')) a__ : Union[str, Any] = map(int, input(prompt).split(''',''')) # We find the log of each number, using the function res(), which takes two # arguments. a__ : Tuple = res(xa, ya) a__ : List[str] = res(xa, ya) # We check for the largest number if resa > resa: print('''Largest number is''', xa, '''^''', ya) elif resa > resa: print('''Largest number is''', xa, '''^''', ya) else: print('''Both are equal''')
365
import math a__ : List[str] = 10 a__ : Optional[int] = 7 a__ : int = BALLS_PER_COLOUR * NUM_COLOURS def UpperCAmelCase_( a__ = 20 ): """simple docstring""" SCREAMING_SNAKE_CASE : str = math.comb(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) SCREAMING_SNAKE_CASE : Any = NUM_COLOURS * (1 - missing_colour / total) return F"""{result:.9f}""" if __name__ == "__main__": print(solution(20))
19
0
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy lowerCamelCase__ : Optional[int] = logging.getLogger(__name__) def UpperCAmelCase_ ( __UpperCAmelCase : torch.nn.Module , __UpperCAmelCase : BnbQuantizationConfig , __UpperCAmelCase : Union[str, os.PathLike] = None , __UpperCAmelCase : Optional[Dict[str, Union[int, str, torch.device]]] = None , __UpperCAmelCase : Optional[List[str]] = None , __UpperCAmelCase : Optional[Dict[Union[int, str], Union[int, str]]] = None , __UpperCAmelCase : Optional[Union[str, os.PathLike]] = None , __UpperCAmelCase : bool = False , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = bnb_quantization_config.load_in_abit SCREAMING_SNAKE_CASE_ = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( 'You have a version of `bitsandbytes` that is not compatible with 8bit quantization,' ' make sure you have the latest version of `bitsandbytes` installed.' ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( 'You have a version of `bitsandbytes` that is not compatible with 4bit quantization,' 'make sure you have the latest version of `bitsandbytes` installed.' ) SCREAMING_SNAKE_CASE_ = [] # custom device map if isinstance(__UpperCAmelCase , __UpperCAmelCase ) and len(device_map.keys() ) > 1: SCREAMING_SNAKE_CASE_ = [key for key, value in device_map.items() if value in ['disk', 'cpu']] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: SCREAMING_SNAKE_CASE_ = get_keys_to_not_convert(__UpperCAmelCase ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__UpperCAmelCase ) # compatibility with peft SCREAMING_SNAKE_CASE_ = load_in_abit SCREAMING_SNAKE_CASE_ = load_in_abit SCREAMING_SNAKE_CASE_ = get_parameter_device(__UpperCAmelCase ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( 'It is not recommended to quantize a loaded model. ' 'The model should be instantiated under the `init_empty_weights` context manager.' ) SCREAMING_SNAKE_CASE_ = replace_with_bnb_layers(__UpperCAmelCase , __UpperCAmelCase , modules_to_not_convert=__UpperCAmelCase ) # convert param to the right dtype SCREAMING_SNAKE_CASE_ = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: SCREAMING_SNAKE_CASE_ = name.replace('.weight' , '' ).replace('.bias' , '' ) SCREAMING_SNAKE_CASE_ = getattr(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__UpperCAmelCase ): param.to(__UpperCAmelCase ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError('No GPU found. A GPU is needed for quantization.' ) logger.info( f"The model device type is {model_device.type}. However, cuda is needed for quantization." 'We move the model to cuda.' ) return model elif weights_location is None: raise RuntimeError( f"`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} " ) else: with init_empty_weights(): SCREAMING_SNAKE_CASE_ = replace_with_bnb_layers( __UpperCAmelCase , __UpperCAmelCase , modules_to_not_convert=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = get_quantized_model_device_map( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , max_memory=__UpperCAmelCase , no_split_module_classes=__UpperCAmelCase , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = any(x in list(device_map.values() ) for x in ['cpu', 'disk'] ) load_checkpoint_in_model( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , dtype=bnb_quantization_config.torch_dtype , offload_folder=__UpperCAmelCase , offload_state_dict=__UpperCAmelCase , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__UpperCAmelCase , device_map=__UpperCAmelCase , offload_dir=__UpperCAmelCase ) def UpperCAmelCase_ ( __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict , __UpperCAmelCase : Tuple=None , __UpperCAmelCase : Any=None , __UpperCAmelCase : List[str]=None ) -> Optional[int]: if device_map is None: if torch.cuda.is_available(): SCREAMING_SNAKE_CASE_ = {'': torch.cuda.current_device()} else: raise RuntimeError('No GPU found. A GPU is needed for quantization.' ) logger.info('The device_map was not initialized.' 'Setting device_map to `{\'\':torch.cuda.current_device()}`.' ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( 'If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or ' '\'sequential\'.' ) SCREAMING_SNAKE_CASE_ = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = special_dtypes SCREAMING_SNAKE_CASE_ = no_split_module_classes SCREAMING_SNAKE_CASE_ = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": SCREAMING_SNAKE_CASE_ = get_balanced_memory( __UpperCAmelCase , low_zero=(device_map == 'balanced_low_0') , max_memory=__UpperCAmelCase , **__UpperCAmelCase , ) SCREAMING_SNAKE_CASE_ = max_memory SCREAMING_SNAKE_CASE_ = infer_auto_device_map(__UpperCAmelCase , **__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ): # check if don't have any quantized module on the cpu SCREAMING_SNAKE_CASE_ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules SCREAMING_SNAKE_CASE_ = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( '\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n ' ) else: logger.info( 'Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit' ) del device_map_without_some_modules return device_map def UpperCAmelCase_ ( __UpperCAmelCase : Tuple , __UpperCAmelCase : str , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : int=None ) -> Tuple: if modules_to_not_convert is None: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _replace_with_bnb_layers( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if not has_been_replaced: logger.warning( 'You are loading your model in 8bit or 4bit but no linear modules were found in your model.' ' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.' ' Please double check your model architecture, or submit an issue on github if you think this is' ' a bug.' ) return model def UpperCAmelCase_ ( __UpperCAmelCase : Optional[int] , __UpperCAmelCase : int , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : Optional[int]=None , ) -> str: SCREAMING_SNAKE_CASE_ = False for name, module in model.named_children(): if current_key_name is None: SCREAMING_SNAKE_CASE_ = [] current_key_name.append(__UpperCAmelCase ) if isinstance(__UpperCAmelCase , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` SCREAMING_SNAKE_CASE_ = '.'.join(__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: SCREAMING_SNAKE_CASE_ = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: SCREAMING_SNAKE_CASE_ = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__UpperCAmelCase , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: SCREAMING_SNAKE_CASE_ = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError('load_in_8bit and load_in_4bit can\'t be both False' ) SCREAMING_SNAKE_CASE_ = module.weight.data if module.bias is not None: SCREAMING_SNAKE_CASE_ = module.bias.data bnb_module.requires_grad_(__UpperCAmelCase ) setattr(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = True if len(list(module.children() ) ) > 0: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _replace_with_bnb_layers( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def UpperCAmelCase_ ( __UpperCAmelCase : Optional[Any] ) -> List[Any]: # Create a copy of the model with init_empty_weights(): SCREAMING_SNAKE_CASE_ = deepcopy(__UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` SCREAMING_SNAKE_CASE_ = find_tied_parameters(__UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(__UpperCAmelCase , __UpperCAmelCase ): SCREAMING_SNAKE_CASE_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: SCREAMING_SNAKE_CASE_ = sum(__UpperCAmelCase , [] ) SCREAMING_SNAKE_CASE_ = len(__UpperCAmelCase ) > 0 # Check if it is a base model SCREAMING_SNAKE_CASE_ = False if hasattr(__UpperCAmelCase , 'base_model_prefix' ): SCREAMING_SNAKE_CASE_ = not hasattr(__UpperCAmelCase , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head SCREAMING_SNAKE_CASE_ = list(model.named_children() ) SCREAMING_SNAKE_CASE_ = [list_modules[-1][0]] # add last module together with tied weights SCREAMING_SNAKE_CASE_ = set(__UpperCAmelCase ) - set(__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = list(set(__UpperCAmelCase ) ) + list(__UpperCAmelCase ) # remove ".weight" from the keys SCREAMING_SNAKE_CASE_ = ['.weight', '.bias'] SCREAMING_SNAKE_CASE_ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: SCREAMING_SNAKE_CASE_ = name.replace(__UpperCAmelCase , '' ) filtered_module_names.append(__UpperCAmelCase ) return filtered_module_names def UpperCAmelCase_ ( __UpperCAmelCase : Optional[int] ) -> List[Any]: for m in model.modules(): if isinstance(__UpperCAmelCase , bnb.nn.Linearabit ): return True return False def UpperCAmelCase_ ( __UpperCAmelCase : nn.Module ) -> Optional[Any]: return next(parameter.parameters() ).device def UpperCAmelCase_ ( __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[int] ) -> int: # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(__UpperCAmelCase , __UpperCAmelCase , 0 , dtype=__UpperCAmelCase , value=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = param_name SCREAMING_SNAKE_CASE_ = model if "." in tensor_name: SCREAMING_SNAKE_CASE_ = tensor_name.split('.' ) for split in splits[:-1]: SCREAMING_SNAKE_CASE_ = getattr(__UpperCAmelCase , __UpperCAmelCase ) if new_module is None: raise ValueError(f"{module} has no attribute {split}." ) SCREAMING_SNAKE_CASE_ = new_module SCREAMING_SNAKE_CASE_ = splits[-1] # offload weights SCREAMING_SNAKE_CASE_ = False offload_weight(module._parameters[tensor_name] , __UpperCAmelCase , __UpperCAmelCase , index=__UpperCAmelCase ) if hasattr(module._parameters[tensor_name] , 'SCB' ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace('weight' , 'SCB' ) , __UpperCAmelCase , index=__UpperCAmelCase , ) else: offload_weight(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , index=__UpperCAmelCase ) offload_weight(__UpperCAmelCase , param_name.replace('weight' , 'SCB' ) , __UpperCAmelCase , index=__UpperCAmelCase ) set_module_tensor_to_device(__UpperCAmelCase , __UpperCAmelCase , 'meta' , dtype=__UpperCAmelCase , value=torch.empty(*param.size() ) )
225
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ : str = { 'configuration_mask2former': [ 'MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Mask2FormerConfig', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ : int = ['Mask2FormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ : Dict = [ 'MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'Mask2FormerForUniversalSegmentation', 'Mask2FormerModel', 'Mask2FormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowerCamelCase__ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
225
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : Optional[Any] = {'configuration_plbart': ['PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PLBartConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Union[str, Any] = ['PLBartTokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ 'PLBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'PLBartForCausalLM', 'PLBartForConditionalGeneration', 'PLBartForSequenceClassification', 'PLBartModel', 'PLBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys UpperCAmelCase_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
364
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: a_ : List[str] = torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0] ) a_ : Union[str, Any] = get_activation('gelu' ) self.assertTrue(torch.allclose(gelu_python(SCREAMING_SNAKE_CASE__ ) , torch_builtin(SCREAMING_SNAKE_CASE__ ) ) ) self.assertFalse(torch.allclose(gelu_python(SCREAMING_SNAKE_CASE__ ) , gelu_new(SCREAMING_SNAKE_CASE__ ) ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: a_ : List[str] = torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0] ) a_ : Union[str, Any] = get_activation('gelu' ) a_ : str = get_activation('gelu_10' ) a_ : Tuple = torch_builtin(SCREAMING_SNAKE_CASE__ ) a_ : str = geluaa(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(SCREAMING_SNAKE_CASE__ ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: get_activation('gelu' ) get_activation('gelu_10' ) get_activation('gelu_fast' ) get_activation('gelu_new' ) get_activation('gelu_python' ) get_activation('gelu_pytorch_tanh' ) get_activation('linear' ) get_activation('mish' ) get_activation('quick_gelu' ) get_activation('relu' ) get_activation('sigmoid' ) get_activation('silu' ) get_activation('swish' ) get_activation('tanh' ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): get_activation('bogus' ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): get_activation(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : str ) -> str: a_ : Any = get_activation('gelu' ) a_ : Any = 1 a_ : int = get_activation('gelu' ) self.assertEqual(acta.a , 1 ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ): a_ : Tuple = acta.a
120
0
def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: SCREAMING_SNAKE_CASE_: str = mf_knapsack(i - 1 , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) else: SCREAMING_SNAKE_CASE_: Tuple = max( mf_knapsack(i - 1 , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) , mf_knapsack(i - 1 , _UpperCAmelCase , _UpperCAmelCase , j - wt[i - 1] ) + val[i - 1] , ) SCREAMING_SNAKE_CASE_: Any = val return f[i][j] def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Any = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1 , n + 1 ): for w_ in range(1 , w + 1 ): if wt[i - 1] <= w_: SCREAMING_SNAKE_CASE_: Optional[int] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] ) else: SCREAMING_SNAKE_CASE_: List[str] = dp[i - 1][w_] return dp[n][w_], dp def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): if not (isinstance(_UpperCAmelCase , (list, tuple) ) and isinstance(_UpperCAmelCase , (list, tuple) )): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) SCREAMING_SNAKE_CASE_: int = len(_UpperCAmelCase ) if num_items != len(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Tuple = ( "The number of weights must be the same as the number of values.\n" f"But got {num_items} weights and {len(_UpperCAmelCase )} values" ) raise ValueError(_UpperCAmelCase ) for i in range(_UpperCAmelCase ): if not isinstance(wt[i] , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Tuple = ( "All weights must be integers but got weight of " f"type {type(wt[i] )} at index {i}" ) raise TypeError(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Any = knapsack(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: set = set() _construct_solution(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) return optimal_val, example_optional_set def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(_UpperCAmelCase , _UpperCAmelCase , i - 1 , _UpperCAmelCase , _UpperCAmelCase ) else: optimal_set.add(_UpperCAmelCase ) _construct_solution(_UpperCAmelCase , _UpperCAmelCase , i - 1 , j - wt[i - 1] , _UpperCAmelCase ) if __name__ == "__main__": lowerCAmelCase : Optional[int] = [3, 2, 4, 4] lowerCAmelCase : str = [4, 3, 2, 3] lowerCAmelCase : Any = 4 lowerCAmelCase : List[Any] = 6 lowerCAmelCase : List[str] = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] lowerCAmelCase , lowerCAmelCase : Any = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 lowerCAmelCase , lowerCAmelCase : Any = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("""optimal_value = """, optimal_solution) print("""An optimal subset corresponding to the optimal value""", optimal_subset)
13
def __lowerCamelCase ( ): '''simple docstring''' return [list(range(1000 - i , -1000 - i , -1 ) ) for i in range(1000 )] _UpperCAmelCase : Union[str, Any] = generate_large_matrix() _UpperCAmelCase : Tuple = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' assert all(row == sorted(UpperCamelCase__ , reverse=UpperCamelCase__ ) for row in grid ) assert all(list(UpperCamelCase__ ) == sorted(UpperCamelCase__ , reverse=UpperCamelCase__ ) for col in zip(*UpperCamelCase__ ) ) def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' snake_case_ = 0 snake_case_ = len(UpperCamelCase__ ) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: snake_case_ = (left + right) // 2 snake_case_ = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: snake_case_ = mid + 1 else: snake_case_ = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(UpperCamelCase__ ) def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' snake_case_ = 0 snake_case_ = len(grid[0] ) for i in range(len(UpperCamelCase__ ) ): snake_case_ = find_negative_index(grid[i][:bound] ) total += bound return (len(UpperCamelCase__ ) * len(grid[0] )) - total def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' return len([number for row in grid for number in row if number < 0] ) def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' snake_case_ = 0 for row in grid: for i, number in enumerate(UpperCamelCase__ ): if number < 0: total += len(UpperCamelCase__ ) - i break return total def __lowerCamelCase ( ): '''simple docstring''' from timeit import timeit print('Running benchmarks' ) snake_case_ = ( 'from __main__ import count_negatives_binary_search, ' 'count_negatives_brute_force, count_negatives_brute_force_with_break, grid' ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): snake_case_ = timeit(F'''{func}(grid=grid)''' , setup=UpperCamelCase__ , number=500 ) print(F'''{func}() took {time:0.4f} seconds''' ) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
285
0
"""simple docstring""" def lowercase ( a__ : int = 1000 ) -> int: _UpperCamelCase = 2**power _UpperCamelCase = 0 while n: _UpperCamelCase , _UpperCamelCase = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
54
"""simple docstring""" from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class UpperCAmelCase_ ( _lowercase): snake_case__ = ['''image_processor''', '''tokenizer'''] snake_case__ = '''BlipImageProcessor''' snake_case__ = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self : Optional[Any] , __UpperCamelCase : List[str] , __UpperCamelCase : Optional[int] ) -> int: _UpperCamelCase = False super().__init__(__UpperCamelCase , __UpperCamelCase ) _UpperCamelCase = self.image_processor def __call__( self : Any , __UpperCamelCase : ImageInput = None , __UpperCamelCase : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __UpperCamelCase : bool = True , __UpperCamelCase : Union[bool, str, PaddingStrategy] = False , __UpperCamelCase : Union[bool, str, TruncationStrategy] = None , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : int = 0 , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : Optional[bool] = None , __UpperCamelCase : bool = False , __UpperCamelCase : bool = False , __UpperCamelCase : bool = False , __UpperCamelCase : bool = False , __UpperCamelCase : bool = False , __UpperCamelCase : bool = True , __UpperCamelCase : Optional[Union[str, TensorType]] = None , **__UpperCamelCase : List[str] , ) -> BatchEncoding: if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: _UpperCamelCase = self.tokenizer _UpperCamelCase = self.tokenizer( text=__UpperCamelCase , add_special_tokens=__UpperCamelCase , padding=__UpperCamelCase , truncation=__UpperCamelCase , max_length=__UpperCamelCase , stride=__UpperCamelCase , pad_to_multiple_of=__UpperCamelCase , return_attention_mask=__UpperCamelCase , return_overflowing_tokens=__UpperCamelCase , return_special_tokens_mask=__UpperCamelCase , return_offsets_mapping=__UpperCamelCase , return_token_type_ids=__UpperCamelCase , return_length=__UpperCamelCase , verbose=__UpperCamelCase , return_tensors=__UpperCamelCase , **__UpperCamelCase , ) return text_encoding # add pixel_values _UpperCamelCase = self.image_processor(__UpperCamelCase , return_tensors=__UpperCamelCase ) if text is not None: _UpperCamelCase = self.tokenizer( text=__UpperCamelCase , add_special_tokens=__UpperCamelCase , padding=__UpperCamelCase , truncation=__UpperCamelCase , max_length=__UpperCamelCase , stride=__UpperCamelCase , pad_to_multiple_of=__UpperCamelCase , return_attention_mask=__UpperCamelCase , return_overflowing_tokens=__UpperCamelCase , return_special_tokens_mask=__UpperCamelCase , return_offsets_mapping=__UpperCamelCase , return_token_type_ids=__UpperCamelCase , return_length=__UpperCamelCase , verbose=__UpperCamelCase , return_tensors=__UpperCamelCase , **__UpperCamelCase , ) else: _UpperCamelCase = None if text_encoding is not None: encoding_image_processor.update(__UpperCamelCase ) return encoding_image_processor def _UpperCamelCase ( self : Union[str, Any] , *__UpperCamelCase : str , **__UpperCamelCase : Any ) -> List[Any]: return self.tokenizer.batch_decode(*__UpperCamelCase , **__UpperCamelCase ) def _UpperCamelCase ( self : Optional[int] , *__UpperCamelCase : List[Any] , **__UpperCamelCase : str ) -> str: return self.tokenizer.decode(*__UpperCamelCase , **__UpperCamelCase ) @property def _UpperCamelCase ( self : List[str] ) -> Dict: _UpperCamelCase = self.tokenizer.model_input_names _UpperCamelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
54
1
import csv import tweepy # Twitter API credentials __a = "" __a = "" __a = "" __a = "" def a ( snake_case__: str ): '''simple docstring''' lowercase_ = tweepy.OAuthHandler(A__ , A__ ) auth.set_access_token(A__ , A__ ) lowercase_ = tweepy.API(A__ ) # initialize a list to hold all the tweepy Tweets lowercase_ = [] # make initial request for most recent tweets (200 is the maximum allowed count) lowercase_ = api.user_timeline(screen_name=A__ , count=200 ) # save most recent tweets alltweets.extend(A__ ) # save the id of the oldest tweet less one lowercase_ = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(A__ ) > 0: print(F'''getting tweets before {oldest}''' ) # all subsequent requests use the max_id param to prevent duplicates lowercase_ = api.user_timeline( screen_name=A__ , count=200 , max_id=A__ ) # save most recent tweets alltweets.extend(A__ ) # update the id of the oldest tweet less one lowercase_ = alltweets[-1].id - 1 print(F'''...{len(A__ )} tweets downloaded so far''' ) # transform the tweepy tweets into a 2D array that will populate the csv lowercase_ = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F'''new_{screen_name}_tweets.csv''' , '''w''' ) as f: lowercase_ = csv.writer(A__ ) writer.writerow(['''id''', '''created_at''', '''text'''] ) writer.writerows(A__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets('FirePing32')
30
'''simple docstring''' import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class __snake_case ( unittest.TestCase): """simple docstring""" def __lowercase ( self : str ) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights lowerCAmelCase_ : int = FlaxDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-pipe""" , safety_checker=lowerCamelCase , cache_dir=lowerCamelCase ) lowerCAmelCase_ : Dict = [t[-1] for t in os.walk(os.path.join(lowerCamelCase , os.listdir(lowerCamelCase )[0] , """snapshots""" ) )] lowerCAmelCase_ : List[Any] = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith(""".bin""" ) for f in files ) @slow @require_flax class __snake_case ( unittest.TestCase): """simple docstring""" def __lowercase ( self : Any ) -> Optional[int]: lowerCAmelCase_, lowerCAmelCase_ : Union[str, Any] = FlaxStableDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-pipe""" , safety_checker=lowerCamelCase ) lowerCAmelCase_ : List[str] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) lowerCAmelCase_ : Tuple = jax.random.PRNGKey(0 ) lowerCAmelCase_ : Optional[Any] = 4 lowerCAmelCase_ : Dict = jax.device_count() lowerCAmelCase_ : Tuple = num_samples * [prompt] lowerCAmelCase_ : Optional[int] = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng lowerCAmelCase_ : Optional[Any] = replicate(lowerCamelCase ) lowerCAmelCase_ : Optional[int] = jax.random.split(lowerCamelCase , lowerCamelCase ) lowerCAmelCase_ : int = shard(lowerCamelCase ) lowerCAmelCase_ : str = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1_514_745 ) < 1E-3 assert np.abs(np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 49_947.875 ) < 5E-1 lowerCAmelCase_ : List[Any] = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(lowerCamelCase ) == num_samples def __lowercase ( self : Optional[int] ) -> List[str]: lowerCAmelCase_, lowerCAmelCase_ : Tuple = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""flax""" , safety_checker=lowerCamelCase ) lowerCAmelCase_ : Dict = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) lowerCAmelCase_ : Union[str, Any] = jax.random.PRNGKey(0 ) lowerCAmelCase_ : List[Any] = 50 lowerCAmelCase_ : str = jax.device_count() lowerCAmelCase_ : Optional[Any] = num_samples * [prompt] lowerCAmelCase_ : Dict = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng lowerCAmelCase_ : Optional[Any] = replicate(lowerCamelCase ) lowerCAmelCase_ : str = jax.random.split(lowerCamelCase , lowerCamelCase ) lowerCAmelCase_ : Union[str, Any] = shard(lowerCamelCase ) lowerCAmelCase_ : Optional[int] = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 5_12, 5_12, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.05_652_401) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2_383_808.2) ) < 5E-1 def __lowercase ( self : List[Any] ) -> List[Any]: lowerCAmelCase_, lowerCAmelCase_ : Optional[Any] = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=lowerCamelCase ) lowerCAmelCase_ : Optional[int] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) lowerCAmelCase_ : List[str] = jax.random.PRNGKey(0 ) lowerCAmelCase_ : Union[str, Any] = 50 lowerCAmelCase_ : Dict = jax.device_count() lowerCAmelCase_ : List[Any] = num_samples * [prompt] lowerCAmelCase_ : Tuple = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng lowerCAmelCase_ : Optional[int] = replicate(lowerCamelCase ) lowerCAmelCase_ : Any = jax.random.split(lowerCamelCase , lowerCamelCase ) lowerCAmelCase_ : Optional[int] = shard(lowerCamelCase ) lowerCAmelCase_ : Any = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 5_12, 5_12, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_003_906) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2_373_516.75) ) < 5E-1 def __lowercase ( self : int ) -> Optional[int]: lowerCAmelCase_, lowerCAmelCase_ : int = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa ) lowerCAmelCase_ : List[str] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) lowerCAmelCase_ : str = jax.random.PRNGKey(0 ) lowerCAmelCase_ : List[Any] = 50 lowerCAmelCase_ : Union[str, Any] = jax.device_count() lowerCAmelCase_ : Optional[Any] = num_samples * [prompt] lowerCAmelCase_ : List[Any] = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng lowerCAmelCase_ : List[Any] = replicate(lowerCamelCase ) lowerCAmelCase_ : List[str] = jax.random.split(lowerCamelCase , lowerCamelCase ) lowerCAmelCase_ : List[str] = shard(lowerCamelCase ) lowerCAmelCase_ : Tuple = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 5_12, 5_12, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_003_906) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2_373_516.75) ) < 5E-1 def __lowercase ( self : List[str] ) -> Any: lowerCAmelCase_ : List[Any] = FlaxDDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , set_alpha_to_one=lowerCamelCase , steps_offset=1 , ) lowerCAmelCase_, lowerCAmelCase_ : List[str] = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , scheduler=lowerCamelCase , safety_checker=lowerCamelCase , ) lowerCAmelCase_ : Any = scheduler.create_state() lowerCAmelCase_ : Optional[Any] = scheduler_state lowerCAmelCase_ : List[Any] = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) lowerCAmelCase_ : int = jax.random.PRNGKey(0 ) lowerCAmelCase_ : List[str] = 50 lowerCAmelCase_ : str = jax.device_count() lowerCAmelCase_ : List[Any] = num_samples * [prompt] lowerCAmelCase_ : int = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng lowerCAmelCase_ : List[str] = replicate(lowerCamelCase ) lowerCAmelCase_ : Any = jax.random.split(lowerCamelCase , lowerCamelCase ) lowerCAmelCase_ : Union[str, Any] = shard(lowerCamelCase ) lowerCAmelCase_ : Tuple = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 5_12, 5_12, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.045_043_945) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2_347_693.5) ) < 5E-1 def __lowercase ( self : Any ) -> Union[str, Any]: lowerCAmelCase_ : int = ( """A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of""" """ field, close up, split lighting, cinematic""" ) lowerCAmelCase_ : Any = jax.device_count() lowerCAmelCase_ : Optional[Any] = num_samples * [prompt] lowerCAmelCase_ : Union[str, Any] = jax.random.split(jax.random.PRNGKey(0 ) , lowerCamelCase ) lowerCAmelCase_, lowerCAmelCase_ : Union[str, Any] = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=lowerCamelCase , ) lowerCAmelCase_ : Optional[int] = replicate(lowerCamelCase ) lowerCAmelCase_ : Optional[int] = pipeline.prepare_inputs(lowerCamelCase ) lowerCAmelCase_ : Optional[int] = shard(lowerCamelCase ) lowerCAmelCase_ : Tuple = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 5_12, 5_12, 3) lowerCAmelCase_ : Dict = images[2, 0, 2_56, 10:17, 1] # With memory efficient attention lowerCAmelCase_, lowerCAmelCase_ : Any = FlaxStableDiffusionPipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""bf16""" , dtype=jnp.bfloataa , safety_checker=lowerCamelCase , use_memory_efficient_attention=lowerCamelCase , ) lowerCAmelCase_ : List[str] = replicate(lowerCamelCase ) lowerCAmelCase_ : Dict = pipeline.prepare_inputs(lowerCamelCase ) lowerCAmelCase_ : Union[str, Any] = shard(lowerCamelCase ) lowerCAmelCase_ : Optional[int] = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images_eff.shape == (num_samples, 1, 5_12, 5_12, 3) lowerCAmelCase_ : List[Any] = images[2, 0, 2_56, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1E-2
120
0
"""simple docstring""" import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def A ( lowercase ) -> tuple: '''simple docstring''' return (data["data"], data["target"]) def A ( lowercase , lowercase ) -> XGBClassifier: '''simple docstring''' UpperCamelCase = XGBClassifier() classifier.fit(lowercase , lowercase ) return classifier def A ( ) -> None: '''simple docstring''' UpperCamelCase = load_iris() UpperCamelCase , UpperCamelCase = data_handling(lowercase ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = train_test_split( lowercase , lowercase , test_size=0.2_5 ) UpperCamelCase = iris['target_names'] # Create an XGBoost Classifier from the training data UpperCamelCase = xgboost(lowercase , lowercase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( lowercase , lowercase , lowercase , display_labels=lowercase , cmap='Blues' , normalize='true' , ) plt.title('Normalized Confusion Matrix - IRIS Dataset' ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
353
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class lowercase ( _SCREAMING_SNAKE_CASE ): __lowercase : torch.FloatTensor class lowercase ( nn.Module ): def __init__( self , A_=3 , A_=3 , A_=("DownEncoderBlock2D",) , A_=(64,) , A_=2 , A_=32 , A_="silu" , A_=True , ) -> List[Any]: """simple docstring""" super().__init__() UpperCamelCase = layers_per_block UpperCamelCase = torch.nn.Convad( A_ , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) UpperCamelCase = None UpperCamelCase = nn.ModuleList([] ) # down UpperCamelCase = block_out_channels[0] for i, down_block_type in enumerate(A_ ): UpperCamelCase = output_channel UpperCamelCase = block_out_channels[i] UpperCamelCase = i == len(A_ ) - 1 UpperCamelCase = get_down_block( A_ , num_layers=self.layers_per_block , in_channels=A_ , out_channels=A_ , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=A_ , resnet_groups=A_ , attention_head_dim=A_ , temb_channels=A_ , ) self.down_blocks.append(A_ ) # mid UpperCamelCase = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=A_ , output_scale_factor=1 , resnet_time_scale_shift='default' , attention_head_dim=block_out_channels[-1] , resnet_groups=A_ , temb_channels=A_ , ) # out UpperCamelCase = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=A_ , eps=1e-6 ) UpperCamelCase = nn.SiLU() UpperCamelCase = 2 * out_channels if double_z else out_channels UpperCamelCase = nn.Convad(block_out_channels[-1] , A_ , 3 , padding=1 ) UpperCamelCase = False def __UpperCamelCase ( self , A_ ) -> Optional[Any]: """simple docstring""" UpperCamelCase = x UpperCamelCase = self.conv_in(A_ ) if self.training and self.gradient_checkpointing: def create_custom_forward(A_ ): def custom_forward(*A_ ): return module(*A_ ) return custom_forward # down if is_torch_version('>=' , '1.11.0' ): for down_block in self.down_blocks: UpperCamelCase = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) , A_ , use_reentrant=A_ ) # middle UpperCamelCase = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , A_ , use_reentrant=A_ ) else: for down_block in self.down_blocks: UpperCamelCase = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) , A_ ) # middle UpperCamelCase = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , A_ ) else: # down for down_block in self.down_blocks: UpperCamelCase = down_block(A_ ) # middle UpperCamelCase = self.mid_block(A_ ) # post-process UpperCamelCase = self.conv_norm_out(A_ ) UpperCamelCase = self.conv_act(A_ ) UpperCamelCase = self.conv_out(A_ ) return sample class lowercase ( nn.Module ): def __init__( self , A_=3 , A_=3 , A_=("UpDecoderBlock2D",) , A_=(64,) , A_=2 , A_=32 , A_="silu" , A_="group" , ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase = layers_per_block UpperCamelCase = nn.Convad( A_ , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) UpperCamelCase = None UpperCamelCase = nn.ModuleList([] ) UpperCamelCase = in_channels if norm_type == 'spatial' else None # mid UpperCamelCase = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=A_ , output_scale_factor=1 , resnet_time_scale_shift='default' if norm_type == 'group' else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=A_ , temb_channels=A_ , ) # up UpperCamelCase = list(reversed(A_ ) ) UpperCamelCase = reversed_block_out_channels[0] for i, up_block_type in enumerate(A_ ): UpperCamelCase = output_channel UpperCamelCase = reversed_block_out_channels[i] UpperCamelCase = i == len(A_ ) - 1 UpperCamelCase = get_up_block( A_ , num_layers=self.layers_per_block + 1 , in_channels=A_ , out_channels=A_ , prev_output_channel=A_ , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=A_ , resnet_groups=A_ , attention_head_dim=A_ , temb_channels=A_ , resnet_time_scale_shift=A_ , ) self.up_blocks.append(A_ ) UpperCamelCase = output_channel # out if norm_type == "spatial": UpperCamelCase = SpatialNorm(block_out_channels[0] , A_ ) else: UpperCamelCase = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=A_ , eps=1e-6 ) UpperCamelCase = nn.SiLU() UpperCamelCase = nn.Convad(block_out_channels[0] , A_ , 3 , padding=1 ) UpperCamelCase = False def __UpperCamelCase ( self , A_ , A_=None ) -> Dict: """simple docstring""" UpperCamelCase = z UpperCamelCase = self.conv_in(A_ ) UpperCamelCase = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(A_ ): def custom_forward(*A_ ): return module(*A_ ) return custom_forward if is_torch_version('>=' , '1.11.0' ): # middle UpperCamelCase = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , A_ , A_ , use_reentrant=A_ ) UpperCamelCase = sample.to(A_ ) # up for up_block in self.up_blocks: UpperCamelCase = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) , A_ , A_ , use_reentrant=A_ ) else: # middle UpperCamelCase = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , A_ , A_ ) UpperCamelCase = sample.to(A_ ) # up for up_block in self.up_blocks: UpperCamelCase = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) , A_ , A_ ) else: # middle UpperCamelCase = self.mid_block(A_ , A_ ) UpperCamelCase = sample.to(A_ ) # up for up_block in self.up_blocks: UpperCamelCase = up_block(A_ , A_ ) # post-process if latent_embeds is None: UpperCamelCase = self.conv_norm_out(A_ ) else: UpperCamelCase = self.conv_norm_out(A_ , A_ ) UpperCamelCase = self.conv_act(A_ ) UpperCamelCase = self.conv_out(A_ ) return sample class lowercase ( nn.Module ): def __init__( self , A_ , A_ , A_ , A_=None , A_="random" , A_=False , A_=True ) -> Tuple: """simple docstring""" super().__init__() UpperCamelCase = n_e UpperCamelCase = vq_embed_dim UpperCamelCase = beta UpperCamelCase = legacy UpperCamelCase = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) UpperCamelCase = remap if self.remap is not None: self.register_buffer('used' , torch.tensor(np.load(self.remap ) ) ) UpperCamelCase = self.used.shape[0] UpperCamelCase = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": UpperCamelCase = self.re_embed UpperCamelCase = self.re_embed + 1 print( F'''Remapping {self.n_e} indices to {self.re_embed} indices. ''' F'''Using {self.unknown_index} for unknown indices.''' ) else: UpperCamelCase = n_e UpperCamelCase = sane_index_shape def __UpperCamelCase ( self , A_ ) -> Dict: """simple docstring""" UpperCamelCase = inds.shape assert len(A_ ) > 1 UpperCamelCase = inds.reshape(ishape[0] , -1 ) UpperCamelCase = self.used.to(A_ ) UpperCamelCase = (inds[:, :, None] == used[None, None, ...]).long() UpperCamelCase = match.argmax(-1 ) UpperCamelCase = match.sum(2 ) < 1 if self.unknown_index == "random": UpperCamelCase = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: UpperCamelCase = self.unknown_index return new.reshape(A_ ) def __UpperCamelCase ( self , A_ ) -> List[str]: """simple docstring""" UpperCamelCase = inds.shape assert len(A_ ) > 1 UpperCamelCase = inds.reshape(ishape[0] , -1 ) UpperCamelCase = self.used.to(A_ ) if self.re_embed > self.used.shape[0]: # extra token UpperCamelCase = 0 # simply set to zero UpperCamelCase = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , A_ ) return back.reshape(A_ ) def __UpperCamelCase ( self , A_ ) -> List[str]: """simple docstring""" # reshape z -> (batch, height, width, channel) and flatten UpperCamelCase = z.permute(0 , 2 , 3 , 1 ).contiguous() UpperCamelCase = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z UpperCamelCase = torch.argmin(torch.cdist(A_ , self.embedding.weight ) , dim=1 ) UpperCamelCase = self.embedding(A_ ).view(z.shape ) UpperCamelCase = None UpperCamelCase = None # compute loss for embedding if not self.legacy: UpperCamelCase = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: UpperCamelCase = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients UpperCamelCase = z + (z_q - z).detach() # reshape back to match original input shape UpperCamelCase = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: UpperCamelCase = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis UpperCamelCase = self.remap_to_used(A_ ) UpperCamelCase = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: UpperCamelCase = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def __UpperCamelCase ( self , A_ , A_ ) -> Optional[int]: """simple docstring""" # shape specifying (batch, height, width, channel) if self.remap is not None: UpperCamelCase = indices.reshape(shape[0] , -1 ) # add batch axis UpperCamelCase = self.unmap_to_all(A_ ) UpperCamelCase = indices.reshape(-1 ) # flatten again # get quantized latent vectors UpperCamelCase = self.embedding(A_ ) if shape is not None: UpperCamelCase = z_q.view(A_ ) # reshape back to match original input shape UpperCamelCase = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class lowercase ( _SCREAMING_SNAKE_CASE ): def __init__( self , A_ , A_=False ) -> Any: """simple docstring""" UpperCamelCase = parameters UpperCamelCase , UpperCamelCase = torch.chunk(A_ , 2 , dim=1 ) UpperCamelCase = torch.clamp(self.logvar , -30.0 , 20.0 ) UpperCamelCase = deterministic UpperCamelCase = torch.exp(0.5 * self.logvar ) UpperCamelCase = torch.exp(self.logvar ) if self.deterministic: UpperCamelCase = UpperCamelCase = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def __UpperCamelCase ( self , A_ = None ) -> torch.FloatTensor: """simple docstring""" # make sure sample is on the same device as the parameters and has same dtype UpperCamelCase = randn_tensor( self.mean.shape , generator=A_ , device=self.parameters.device , dtype=self.parameters.dtype ) UpperCamelCase = self.mean + self.std * sample return x def __UpperCamelCase ( self , A_=None ) -> Tuple: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def __UpperCamelCase ( self , A_ , A_=[1, 2, 3] ) -> Optional[Any]: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) UpperCamelCase = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=A_ ) def __UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" return self.mean
110
0
"""simple docstring""" from __future__ import annotations from collections.abc import Generator def __lowerCAmelCase (): __lowerCAmelCase : dict[int, int] = {} __lowerCAmelCase : List[str] = 2 while True: __lowerCAmelCase : List[Any] = factor_map.pop(_UpperCamelCase , _UpperCamelCase ) if factor: __lowerCAmelCase : Optional[Any] = factor + prime while x in factor_map: x += factor __lowerCAmelCase : str = factor else: __lowerCAmelCase : List[Any] = prime yield prime prime += 1 def __lowerCAmelCase (_UpperCamelCase = 1e1_0 ): __lowerCAmelCase : Dict = sieve() __lowerCAmelCase : Optional[Any] = 1 while True: __lowerCAmelCase : int = next(_UpperCamelCase ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(_UpperCamelCase ) n += 2 if __name__ == "__main__": print(solution())
86
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Union[str, Any] = { "configuration_convbert": ["CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvBertConfig", "ConvBertOnnxConfig"], "tokenization_convbert": ["ConvBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = ["ConvBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ "CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "ConvBertForMaskedLM", "ConvBertForMultipleChoice", "ConvBertForQuestionAnswering", "ConvBertForSequenceClassification", "ConvBertForTokenClassification", "ConvBertLayer", "ConvBertModel", "ConvBertPreTrainedModel", "load_tf_weights_in_convbert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Tuple = [ "TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFConvBertForMaskedLM", "TFConvBertForMultipleChoice", "TFConvBertForQuestionAnswering", "TFConvBertForSequenceClassification", "TFConvBertForTokenClassification", "TFConvBertLayer", "TFConvBertModel", "TFConvBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
204
0
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class lowercase: '''simple docstring''' def __init__( self: int, a_: List[Any], a_: str=13, a_: Union[str, Any]=2, a_: List[Any]=24, a_: Any=16, a_: Optional[int]=True, a_: Optional[int]=True, a_: Union[str, Any]=32, a_: int=5, a_: int=4, a_: Union[str, Any]=37, a_: Optional[Any]="gelu", a_: int=0.1, a_: str=0.1, a_: Dict=10, a_: Any=0.02, a_: Tuple=None, a_: Optional[Any]=2, a_: Dict=2, ): '''simple docstring''' _snake_case : List[Any] = parent _snake_case : Union[str, Any] = batch_size _snake_case : List[Any] = patch_size _snake_case : List[str] = max_length _snake_case : Optional[Any] = num_mel_bins _snake_case : Tuple = is_training _snake_case : Optional[Any] = use_labels _snake_case : List[str] = hidden_size _snake_case : List[str] = num_hidden_layers _snake_case : List[Any] = num_attention_heads _snake_case : Union[str, Any] = intermediate_size _snake_case : Tuple = hidden_act _snake_case : Tuple = hidden_dropout_prob _snake_case : Optional[int] = attention_probs_dropout_prob _snake_case : str = type_sequence_label_size _snake_case : List[Any] = initializer_range _snake_case : List[str] = scope _snake_case : Dict = frequency_stride _snake_case : Optional[Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) _snake_case : str = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 _snake_case : str = (self.max_length - self.patch_size) // self.time_stride + 1 _snake_case : Union[str, Any] = frequency_out_dimension * time_out_dimension _snake_case : str = num_patches + 2 def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case : Union[str, Any] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) _snake_case : Tuple = None if self.use_labels: _snake_case : Optional[int] = ids_tensor([self.batch_size], self.type_sequence_label_size ) _snake_case : int = self.get_config() return config, input_values, labels def UpperCamelCase_ ( self: str ): '''simple docstring''' return ASTConfig( patch_size=self.patch_size, max_length=self.max_length, num_mel_bins=self.num_mel_bins, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, is_decoder=a_, initializer_range=self.initializer_range, frequency_stride=self.frequency_stride, time_stride=self.time_stride, ) def UpperCamelCase_ ( self: Tuple, a_: str, a_: Dict, a_: Tuple ): '''simple docstring''' _snake_case : Union[str, Any] = ASTModel(config=a_ ) model.to(a_ ) model.eval() _snake_case : int = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Union[str, Any] = self.prepare_config_and_inputs() ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) : List[Any] = config_and_inputs _snake_case : int = {"""input_values""": input_values} return config, inputs_dict @require_torch class lowercase( __a , __a , unittest.TestCase ): '''simple docstring''' lowercase__ = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) lowercase__ = ( {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel} if is_torch_available() else {} ) lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False def UpperCamelCase_ ( self: Union[str, Any], a_: str, a_: str, a_: int, a_: List[Any], a_: Tuple ): '''simple docstring''' if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' _snake_case : List[Any] = ASTModelTester(self ) _snake_case : Dict = ConfigTester(self, config_class=a_, has_text_modality=a_, hidden_size=37 ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""AST does not use inputs_embeds""" ) def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' pass def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case , _snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case : List[str] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) _snake_case : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_, nn.Linear ) ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case , _snake_case : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case : Optional[Any] = model_class(a_ ) _snake_case : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _snake_case : str = [*signature.parameters.keys()] _snake_case : List[str] = ["""input_values"""] self.assertListEqual(arg_names[:1], a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) @slow def UpperCamelCase_ ( self: str ): '''simple docstring''' for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case : Dict = ASTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : Dict = hf_hub_download( repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" , filename="""sample_audio.flac""" , repo_type="""dataset""" ) _snake_case , _snake_case : List[Any] = torchaudio.load(snake_case__ ) return audio, sampling_rate @require_torch @require_torchaudio class lowercase( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' return ( ASTFeatureExtractor.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593""" ) if is_torchaudio_available() else None ) @slow def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Dict = self.default_feature_extractor _snake_case : List[Any] = ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593""" ).to(a_ ) _snake_case : Optional[int] = self.default_feature_extractor _snake_case , _snake_case : str = prepare_audio() _snake_case : Union[str, Any] = audio.squeeze().numpy() _snake_case : str = feature_extractor(a_, sampling_rate=a_, return_tensors="""pt""" ).to(a_ ) # forward pass with torch.no_grad(): _snake_case : Optional[int] = model(**a_ ) # verify the logits _snake_case : Optional[Any] = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape, a_ ) _snake_case : Any = torch.tensor([-0.8_760, -7.0_042, -8.6_602] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3], a_, atol=1E-4 ) )
132
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : int ): """simple docstring""" _snake_case : Optional[Any] = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def UpperCAmelCase__ (snake_case__ : int = 50_00 ): """simple docstring""" _snake_case : List[str] = [(i * (3 * i - 1)) // 2 for i in range(1 , snake_case__ )] for i, pentagonal_i in enumerate(snake_case__ ): for j in range(snake_case__ , len(snake_case__ ) ): _snake_case : Dict = pentagonal_nums[j] _snake_case : Optional[Any] = pentagonal_i + pentagonal_j _snake_case : List[str] = pentagonal_j - pentagonal_i if is_pentagonal(snake_case__ ) and is_pentagonal(snake_case__ ): return b return -1 if __name__ == "__main__": print(F'''{solution() = }''')
132
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available __A = { "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
10
"""simple docstring""" from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time __A = Lock() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->List[Any]: """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCAmelCase__ :Any = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCAmelCase__ :Tuple = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(_SCREAMING_SNAKE_CASE ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCAmelCase__ :Optional[int] = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCAmelCase__ :Optional[int] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # after all swaps are performed, send the values back to main result_pipe[1].send(_SCREAMING_SNAKE_CASE ) def __A (_SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" lowerCAmelCase__ :str = [] lowerCAmelCase__ :Optional[Any] = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCAmelCase__ :List[str] = Pipe() lowerCAmelCase__ :List[Any] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCAmelCase__ :Dict = temp_rs lowerCAmelCase__ :Optional[Any] = temp_rr for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ): lowerCAmelCase__ :Union[str, Any] = Pipe() lowerCAmelCase__ :List[str] = Pipe() process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCAmelCase__ :Union[str, Any] = temp_rs lowerCAmelCase__ :Any = temp_rr process_array_.append( Process( target=_SCREAMING_SNAKE_CASE , args=( len(_SCREAMING_SNAKE_CASE ) - 1, arr[len(_SCREAMING_SNAKE_CASE ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ): lowerCAmelCase__ :str = result_pipe[p][0].recv() process_array_[p].join() return arr def __A () ->List[Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = list(range(10 , 0 , -1 ) ) print('Initial List' ) print(*_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :List[str] = odd_even_transposition(_SCREAMING_SNAKE_CASE ) print('Sorted List\n' ) print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
293
0
"""simple docstring""" import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a ( _lowerCamelCase, unittest.TestCase ): """simple docstring""" UpperCAmelCase = GPTaTokenizer UpperCAmelCase = GPTaTokenizerFast UpperCAmelCase = True UpperCAmelCase = {"add_prefix_space": True} UpperCAmelCase = False def UpperCamelCase ( self: int ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", """<|endoftext|>""", ] A__ = dict(zip(UpperCamelCase , range(len(UpperCamelCase ) ) ) ) A__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] A__ = {"""unk_token""": """<unk>"""} A__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) A__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(UpperCamelCase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(UpperCamelCase ) ) def UpperCamelCase ( self: List[Any] , **UpperCamelCase: Optional[int] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase ) def UpperCamelCase ( self: List[str] , **UpperCamelCase: Union[str, Any] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase ) def UpperCamelCase ( self: Optional[int] , UpperCamelCase: List[Any] ): """simple docstring""" A__ = """lower newer""" A__ = """lower newer""" return input_text, output_text def UpperCamelCase ( self: List[str] ): """simple docstring""" A__ = GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) A__ = """lower newer""" A__ = ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] A__ = tokenizer.tokenize(UpperCamelCase , add_prefix_space=UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) A__ = tokens + [tokenizer.unk_token] A__ = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase ) , UpperCamelCase ) def UpperCamelCase ( self: Tuple ): """simple docstring""" if not self.test_rust_tokenizer: return A__ = self.get_tokenizer() A__ = self.get_rust_tokenizer(add_prefix_space=UpperCamelCase ) A__ = """lower newer""" # Testing tokenization A__ = tokenizer.tokenize(UpperCamelCase , add_prefix_space=UpperCamelCase ) A__ = rust_tokenizer.tokenize(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) # Testing conversion to ids without special tokens A__ = tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase , add_prefix_space=UpperCamelCase ) A__ = rust_tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) # Testing conversion to ids with special tokens A__ = self.get_rust_tokenizer(add_prefix_space=UpperCamelCase ) A__ = tokenizer.encode(UpperCamelCase , add_prefix_space=UpperCamelCase ) A__ = rust_tokenizer.encode(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) # Testing the unknown token A__ = tokens + [rust_tokenizer.unk_token] A__ = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(UpperCamelCase ) , UpperCamelCase ) def UpperCamelCase ( self: Optional[Any] , *UpperCamelCase: List[Any] , **UpperCamelCase: Any ): """simple docstring""" pass def UpperCamelCase ( self: List[str] , UpperCamelCase: str=15 ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): A__ = self.rust_tokenizer_class.from_pretrained(UpperCamelCase , **UpperCamelCase ) # Simple input A__ = """This is a simple input""" A__ = ["""This is a simple input 1""", """This is a simple input 2"""] A__ = ("""This is a simple input""", """This is a pair""") A__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(UpperCamelCase , tokenizer_r.encode , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" ) # Simple input self.assertRaises(UpperCamelCase , tokenizer_r.encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" ) # Simple input self.assertRaises( UpperCamelCase , tokenizer_r.batch_encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" , ) # Pair input self.assertRaises(UpperCamelCase , tokenizer_r.encode , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" ) # Pair input self.assertRaises(UpperCamelCase , tokenizer_r.encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" ) # Pair input self.assertRaises( UpperCamelCase , tokenizer_r.batch_encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding="""max_length""" , ) def UpperCamelCase ( self: Union[str, Any] ): """simple docstring""" A__ = GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token="""<pad>""" ) # Simple input A__ = """This is a simple input""" A__ = ["""This is a simple input looooooooong""", """This is a simple input"""] A__ = ("""This is a simple input""", """This is a pair""") A__ = [ ("""This is a simple input loooooong""", """This is a simple input"""), ("""This is a simple pair loooooong""", """This is a simple pair"""), ] A__ = tokenizer.pad_token_id A__ = tokenizer(UpperCamelCase , padding="""max_length""" , max_length=30 , return_tensors="""np""" ) A__ = tokenizer(UpperCamelCase , padding=UpperCamelCase , truncate=UpperCamelCase , return_tensors="""np""" ) A__ = tokenizer(*UpperCamelCase , padding="""max_length""" , max_length=60 , return_tensors="""np""" ) A__ = tokenizer(UpperCamelCase , padding=UpperCamelCase , truncate=UpperCamelCase , return_tensors="""np""" ) # s # test single string max_length padding self.assertEqual(out_s["""input_ids"""].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s["""input_ids"""] ) self.assertTrue(0 in out_s["""attention_mask"""] ) # s2 # test automatic padding self.assertEqual(out_sa["""input_ids"""].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] ) self.assertFalse(0 in out_sa["""attention_mask"""][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] ) self.assertTrue(0 in out_sa["""attention_mask"""][1] ) # p # test single pair max_length padding self.assertEqual(out_p["""input_ids"""].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p["""input_ids"""] ) self.assertTrue(0 in out_p["""attention_mask"""] ) # p2 # test automatic padding pair self.assertEqual(out_pa["""input_ids"""].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] ) self.assertFalse(0 in out_pa["""attention_mask"""][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] ) self.assertTrue(0 in out_pa["""attention_mask"""][1] ) def UpperCamelCase ( self: Any ): """simple docstring""" A__ = """$$$""" A__ = GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=UpperCamelCase , add_bos_token=UpperCamelCase ) A__ = """This is a simple input""" A__ = ["""This is a simple input 1""", """This is a simple input 2"""] A__ = tokenizer.bos_token_id A__ = tokenizer(UpperCamelCase ) A__ = tokenizer(UpperCamelCase ) self.assertEqual(out_s.input_ids[0] , UpperCamelCase ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) A__ = tokenizer.decode(out_s.input_ids ) A__ = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , UpperCamelCase ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def UpperCamelCase ( self: List[str] ): """simple docstring""" pass def UpperCamelCase ( self: Any ): """simple docstring""" A__ = [self.get_tokenizer(do_lower_case=UpperCamelCase , add_bos_token=UpperCamelCase )] for tokenizer in tokenizers: with self.subTest(f"""{tokenizer.__class__.__name__}""" ): A__ = """Encode this.""" A__ = """This one too please.""" A__ = tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) encoded_sequence += tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) A__ = tokenizer.encode_plus( UpperCamelCase , UpperCamelCase , add_special_tokens=UpperCamelCase , return_special_tokens_mask=UpperCamelCase , ) A__ = encoded_sequence_dict["""input_ids"""] A__ = encoded_sequence_dict["""special_tokens_mask"""] self.assertEqual(len(UpperCamelCase ) , len(UpperCamelCase ) ) A__ = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(UpperCamelCase ) ] A__ = [x for x in filtered_sequence if x is not None] self.assertEqual(UpperCamelCase , UpperCamelCase ) @require_tokenizers class a ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self: List[str] ): """simple docstring""" A__ = AutoTokenizer.from_pretrained("""facebook/opt-350m""" , from_slow=UpperCamelCase ) A__ = """A photo of a cat""" A__ = tokenizer.encode( UpperCamelCase , ) self.assertEqual(UpperCamelCase , [2, 2_50, 13_45, 9, 10, 47_58] ) tokenizer.save_pretrained("""test_opt""" ) A__ = AutoTokenizer.from_pretrained("""./test_opt""" ) A__ = tokenizer.encode( UpperCamelCase , ) self.assertEqual(UpperCamelCase , [2, 2_50, 13_45, 9, 10, 47_58] ) def UpperCamelCase ( self: List[Any] ): """simple docstring""" A__ = AutoTokenizer.from_pretrained("""facebook/opt-350m""" , use_slow=UpperCamelCase ) A__ = """A photo of a cat""" A__ = tokenizer.encode( UpperCamelCase , ) # Same as above self.assertEqual(UpperCamelCase , [2, 2_50, 13_45, 9, 10, 47_58] ) @unittest.skip("""This test is failing because of a bug in the fast tokenizer""" ) def UpperCamelCase ( self: Dict ): """simple docstring""" A__ = AutoTokenizer.from_pretrained("""facebook/opt-350m""" , from_slow=UpperCamelCase ) A__ = """bos""" A__ = tokenizer.get_vocab()["""bos"""] A__ = """A photo of a cat""" A__ = tokenizer.encode( UpperCamelCase , ) # We changed the bos token self.assertEqual(UpperCamelCase , [3_19_57, 2_50, 13_45, 9, 10, 47_58] ) tokenizer.save_pretrained("""./tok""" ) A__ = AutoTokenizer.from_pretrained("""./tok""" ) self.assertTrue(tokenizer.is_fast ) A__ = tokenizer.encode( UpperCamelCase , ) self.assertEqual(UpperCamelCase , [3_19_57, 2_50, 13_45, 9, 10, 47_58] )
69
"""simple docstring""" import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class a ( _lowerCamelCase ): """simple docstring""" def __init__( self: int , UpperCamelCase: int , UpperCamelCase: Union[str, Any]=13 , UpperCamelCase: List[Any]=7 , UpperCamelCase: Any=True , UpperCamelCase: Optional[Any]=True , UpperCamelCase: Optional[Any]=True , UpperCamelCase: str=True , UpperCamelCase: Optional[int]=99 , UpperCamelCase: Optional[Any]=32 , UpperCamelCase: Tuple=5 , UpperCamelCase: Optional[int]=4 , UpperCamelCase: int=37 , UpperCamelCase: str="gelu" , UpperCamelCase: Optional[Any]=0.1 , UpperCamelCase: List[Any]=0.1 , UpperCamelCase: Tuple=5_12 , UpperCamelCase: List[str]=16 , UpperCamelCase: List[str]=2 , UpperCamelCase: List[Any]=0.02 , UpperCamelCase: List[str]=False , UpperCamelCase: int=True , UpperCamelCase: Union[str, Any]="None" , UpperCamelCase: Optional[int]=3 , UpperCamelCase: List[str]=4 , UpperCamelCase: List[str]=None , ): """simple docstring""" A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = use_token_type_ids A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = type_vocab_size A__ = type_sequence_label_size A__ = initializer_range A__ = num_labels A__ = num_choices A__ = relative_attention A__ = position_biased_input A__ = pos_att_type A__ = scope def UpperCamelCase ( self: Tuple ): """simple docstring""" A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ = None if self.use_input_mask: A__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) A__ = None if self.use_token_type_ids: A__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ = None A__ = None A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ = ids_tensor([self.batch_size] , self.num_choices ) A__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase ( self: str ): """simple docstring""" return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def UpperCamelCase ( self: Optional[int] ): """simple docstring""" A__ = self.get_config() A__ = 3_00 return config def UpperCamelCase ( self: List[Any] , UpperCamelCase: str ): """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def UpperCamelCase ( self: Tuple , UpperCamelCase: List[Any] , UpperCamelCase: List[str] , UpperCamelCase: List[Any] , UpperCamelCase: List[str] , UpperCamelCase: List[str] , UpperCamelCase: Optional[Any] , UpperCamelCase: Tuple ): """simple docstring""" A__ = DebertaModel(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() A__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase )[0] A__ = model(UpperCamelCase , token_type_ids=UpperCamelCase )[0] A__ = model(UpperCamelCase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def UpperCamelCase ( self: List[str] , UpperCamelCase: Optional[int] , UpperCamelCase: Optional[Any] , UpperCamelCase: Union[str, Any] , UpperCamelCase: Tuple , UpperCamelCase: Tuple , UpperCamelCase: str , UpperCamelCase: Any ): """simple docstring""" A__ = DebertaForMaskedLM(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() A__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase ( self: Union[str, Any] , UpperCamelCase: Union[str, Any] , UpperCamelCase: List[Any] , UpperCamelCase: int , UpperCamelCase: Dict , UpperCamelCase: Dict , UpperCamelCase: Tuple , UpperCamelCase: str ): """simple docstring""" A__ = self.num_labels A__ = DebertaForSequenceClassification(UpperCamelCase ) model.to(UpperCamelCase ) model.eval() A__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(UpperCamelCase ) def UpperCamelCase ( self: Optional[int] , UpperCamelCase: List[Any] , UpperCamelCase: Any , UpperCamelCase: Dict , UpperCamelCase: int , UpperCamelCase: Optional[Any] , UpperCamelCase: str , UpperCamelCase: int ): """simple docstring""" A__ = self.num_labels A__ = DebertaForTokenClassification(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() A__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase ( self: Tuple , UpperCamelCase: Tuple , UpperCamelCase: Optional[int] , UpperCamelCase: Tuple , UpperCamelCase: int , UpperCamelCase: int , UpperCamelCase: Tuple , UpperCamelCase: Any ): """simple docstring""" A__ = DebertaForQuestionAnswering(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() A__ = model( UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=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: str ): """simple docstring""" A__ = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = config_and_inputs A__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class a ( _lowerCamelCase, _lowerCamelCase, unittest.TestCase ): """simple docstring""" UpperCAmelCase = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) UpperCAmelCase = ( { "feature-extraction": DebertaModel, "fill-mask": DebertaForMaskedLM, "question-answering": DebertaForQuestionAnswering, "text-classification": DebertaForSequenceClassification, "token-classification": DebertaForTokenClassification, "zero-shot": DebertaForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = False def UpperCamelCase ( self: Union[str, Any] ): """simple docstring""" A__ = DebertaModelTester(self ) A__ = ConfigTester(self , config_class=UpperCamelCase , hidden_size=37 ) def UpperCamelCase ( self: int ): """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase ( self: List[str] ): """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*UpperCamelCase ) def UpperCamelCase ( self: str ): """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*UpperCamelCase ) def UpperCamelCase ( self: List[Any] ): """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*UpperCamelCase ) def UpperCamelCase ( self: Optional[int] ): """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*UpperCamelCase ) def UpperCamelCase ( self: Tuple ): """simple docstring""" A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*UpperCamelCase ) @slow def UpperCamelCase ( self: Union[str, Any] ): """simple docstring""" for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = DebertaModel.from_pretrained(UpperCamelCase ) self.assertIsNotNone(UpperCamelCase ) @require_torch @require_sentencepiece @require_tokenizers class a ( unittest.TestCase ): """simple docstring""" @unittest.skip(reason="""Model not available yet""" ) def UpperCamelCase ( self: Any ): """simple docstring""" pass @slow def UpperCamelCase ( self: Optional[Any] ): """simple docstring""" A__ = DebertaModel.from_pretrained("""microsoft/deberta-base""" ) A__ = torch.tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] ) A__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): A__ = model(UpperCamelCase , attention_mask=UpperCamelCase )[0] # compare the actual values for a slice. A__ = torch.tensor( [[[-0.5_986, -0.8_055, -0.8_462], [1.4_484, -0.9_348, -0.8_059], [0.3_123, 0.0_032, -1.4_131]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCamelCase , atol=1e-4 ) , f"""{output[:, 1:4, 1:4]}""" )
69
1
import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class _UpperCamelCase : """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=13 , lowerCAmelCase__=7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=99 , lowerCAmelCase__=32 , lowerCAmelCase__=5 , lowerCAmelCase__=4 , lowerCAmelCase__=37 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=1_28 , lowerCAmelCase__=32 , lowerCAmelCase__=16 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=None , ) -> str: '''simple docstring''' __lowercase = parent __lowercase = batch_size __lowercase = seq_length __lowercase = is_training __lowercase = use_input_mask __lowercase = use_token_type_ids __lowercase = use_labels __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_size __lowercase = hidden_act __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = type_vocab_size __lowercase = type_sequence_label_size __lowercase = initializer_range __lowercase = num_labels __lowercase = num_choices __lowercase = scope def _SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' __lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowercase = None if self.use_input_mask: __lowercase = random_attention_mask([self.batch_size, self.seq_length] ) __lowercase = None if self.use_token_type_ids: __lowercase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowercase = None __lowercase = None __lowercase = None if self.use_labels: __lowercase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowercase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowercase = ids_tensor([self.batch_size] , self.num_choices ) __lowercase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' return NezhaConfig( 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=lowerCAmelCase__ , initializer_range=self.initializer_range , ) def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = self.prepare_config_and_inputs() __lowercase = True __lowercase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __lowercase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' __lowercase = NezhaModel(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() __lowercase = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ ) __lowercase = model(lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ ) __lowercase = model(lowerCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> Any: '''simple docstring''' __lowercase = True __lowercase = NezhaModel(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() __lowercase = model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , encoder_hidden_states=lowerCAmelCase__ , encoder_attention_mask=lowerCAmelCase__ , ) __lowercase = model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , encoder_hidden_states=lowerCAmelCase__ , ) __lowercase = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' __lowercase = NezhaForMaskedLM(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() __lowercase = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> str: '''simple docstring''' __lowercase = NezhaForNextSentencePrediction(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() __lowercase = model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' __lowercase = NezhaForPreTraining(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() __lowercase = model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__ , next_sentence_label=lowerCAmelCase__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[Any]: '''simple docstring''' __lowercase = NezhaForQuestionAnswering(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() __lowercase = model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , start_positions=lowerCAmelCase__ , end_positions=lowerCAmelCase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' __lowercase = self.num_labels __lowercase = NezhaForSequenceClassification(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() __lowercase = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' __lowercase = self.num_labels __lowercase = NezhaForTokenClassification(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() __lowercase = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Any: '''simple docstring''' __lowercase = self.num_choices __lowercase = NezhaForMultipleChoice(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() __lowercase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowercase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowercase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowercase = model( lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' __lowercase = self.prepare_config_and_inputs() ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = config_and_inputs __lowercase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class _UpperCamelCase ( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,unittest.TestCase ): """simple docstring""" __a : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) __a : List[Any] = ( { '''feature-extraction''': NezhaModel, '''fill-mask''': NezhaForMaskedLM, '''question-answering''': NezhaForQuestionAnswering, '''text-classification''': NezhaForSequenceClassification, '''token-classification''': NezhaForTokenClassification, '''zero-shot''': NezhaForSequenceClassification, } if is_torch_available() else {} ) __a : Dict = True def _SCREAMING_SNAKE_CASE ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False ) -> List[str]: '''simple docstring''' __lowercase = super()._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ , return_labels=lowerCAmelCase__ ) if return_labels: if model_class in get_values(lowerCAmelCase__ ): __lowercase = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=lowerCAmelCase__ ) __lowercase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowerCAmelCase__ ) return inputs_dict def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = NezhaModelTester(self ) __lowercase = ConfigTester(self , config_class=lowerCAmelCase__ , hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __lowercase = None self.model_tester.create_and_check_model_as_decoder( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) def _SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> Tuple: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase__ ) @slow def _SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase = NezhaModel.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) @slow @require_torch_gpu def _SCREAMING_SNAKE_CASE ( self ) -> Any: '''simple docstring''' __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __lowercase = True __lowercase = model_class(config=lowerCAmelCase__ ) __lowercase = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ ) __lowercase = torch.jit.trace( lowerCAmelCase__ , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(lowerCAmelCase__ , os.path.join(lowerCAmelCase__ , '''bert.pt''' ) ) __lowercase = torch.jit.load(os.path.join(lowerCAmelCase__ , '''bert.pt''' ) , map_location=lowerCAmelCase__ ) loaded(inputs_dict['''input_ids'''].to(lowerCAmelCase__ ) , inputs_dict['''attention_mask'''].to(lowerCAmelCase__ ) ) @require_torch class _UpperCamelCase ( unittest.TestCase ): """simple docstring""" @slow def _SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' __lowercase = NezhaModel.from_pretrained('''sijunhe/nezha-cn-base''' ) __lowercase = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __lowercase = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowercase = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ )[0] __lowercase = torch.Size((1, 6, 7_68) ) self.assertEqual(output.shape , lowerCAmelCase__ ) __lowercase = torch.tensor([[[0.0685, 0.2441, 0.1102], [0.0600, 0.1906, 0.1349], [0.0221, 0.0819, 0.0586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowerCAmelCase__ , atol=1E-4 ) ) @slow def _SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' __lowercase = NezhaForMaskedLM.from_pretrained('''sijunhe/nezha-cn-base''' ) __lowercase = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __lowercase = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowercase = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ )[0] __lowercase = torch.Size((1, 6, 2_11_28) ) self.assertEqual(output.shape , lowerCAmelCase__ ) __lowercase = torch.tensor( [[-2.7939, -1.7902, -2.2189], [-2.8585, -1.8908, -2.3723], [-2.6499, -1.7750, -2.2558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowerCAmelCase__ , atol=1E-4 ) )
210
from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets from .splits import NamedSplit from .utils import logging from .utils.py_utils import Literal __a : Optional[Any] = logging.get_logger(__name__) __a : List[str] = TypeVar("""DatasetType""", Dataset, IterableDataset) def UpperCAmelCase ( lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = "first_exhausted" , ): """simple docstring""" from .arrow_dataset import Dataset from .iterable_dataset import IterableDataset if not datasets: raise ValueError('''Unable to interleave an empty list of datasets.''' ) for i, dataset in enumerate(lowercase ): if not isinstance(lowercase , (Dataset, IterableDataset) ): if isinstance(lowercase , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} " '''is an empty dataset dictionary.''' ) raise ValueError( F"Dataset at position {i} has at least one split: {list(lowercase )}\n" F"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(lowercase ) )}']" ) raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(lowercase ).__name__}." ) if i == 0: __lowercase , __lowercase = ( (Dataset, IterableDataset) if isinstance(lowercase , lowercase ) else (IterableDataset, Dataset) ) elif not isinstance(lowercase , lowercase ): raise ValueError( F"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects." ) if stopping_strategy not in ["first_exhausted", "all_exhausted"]: raise ValueError(F"{stopping_strategy} is not supported. Please enter a valid stopping_strategy." ) if dataset_type is Dataset: return _interleave_map_style_datasets( lowercase , lowercase , lowercase , info=lowercase , split=lowercase , stopping_strategy=lowercase ) else: return _interleave_iterable_datasets( lowercase , lowercase , lowercase , info=lowercase , split=lowercase , stopping_strategy=lowercase ) def UpperCAmelCase ( lowercase , lowercase = None , lowercase = None , lowercase = 0 , ): """simple docstring""" if not dsets: raise ValueError('''Unable to concatenate an empty list of datasets.''' ) for i, dataset in enumerate(lowercase ): if not isinstance(lowercase , (Dataset, IterableDataset) ): if isinstance(lowercase , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} " '''is an empty dataset dictionary.''' ) raise ValueError( F"Dataset at position {i} has at least one split: {list(lowercase )}\n" F"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(lowercase ) )}']" ) raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(lowercase ).__name__}." ) if i == 0: __lowercase , __lowercase = ( (Dataset, IterableDataset) if isinstance(lowercase , lowercase ) else (IterableDataset, Dataset) ) elif not isinstance(lowercase , lowercase ): raise ValueError( F"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects." ) if dataset_type is Dataset: return _concatenate_map_style_datasets(lowercase , info=lowercase , split=lowercase , axis=lowercase ) else: return _concatenate_iterable_datasets(lowercase , info=lowercase , split=lowercase , axis=lowercase )
210
1
'''simple docstring''' from torch import nn def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' 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}' )
311
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal lowercase : str = datasets.utils.logging.get_logger(__name__) lowercase : Union[str, Any] = ['names', 'prefix'] lowercase : Union[str, Any] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] lowercase : List[Any] = ['encoding_errors', 'on_bad_lines'] lowercase : Any = ['date_format'] @dataclass class A ( datasets.BuilderConfig ): __magic_name__ = "," __magic_name__ = None __magic_name__ = "infer" __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = False __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = False __magic_name__ = True __magic_name__ = None __magic_name__ = "." __magic_name__ = None __magic_name__ = '"' __magic_name__ = 0 __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = None __magic_name__ = True __magic_name__ = True __magic_name__ = 0 __magic_name__ = True __magic_name__ = False __magic_name__ = None __magic_name__ = 10000 __magic_name__ = None __magic_name__ = "strict" __magic_name__ = "error" __magic_name__ = None def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" if self.delimiter is not None: A : Optional[Any] = self.delimiter if self.column_names is not None: A : Optional[Any] = self.column_names @property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" A : str = { '''sep''': self.sep, '''header''': self.header, '''names''': self.names, '''index_col''': self.index_col, '''usecols''': self.usecols, '''prefix''': self.prefix, '''mangle_dupe_cols''': self.mangle_dupe_cols, '''engine''': self.engine, '''converters''': self.converters, '''true_values''': self.true_values, '''false_values''': self.false_values, '''skipinitialspace''': self.skipinitialspace, '''skiprows''': self.skiprows, '''nrows''': self.nrows, '''na_values''': self.na_values, '''keep_default_na''': self.keep_default_na, '''na_filter''': self.na_filter, '''verbose''': self.verbose, '''skip_blank_lines''': self.skip_blank_lines, '''thousands''': self.thousands, '''decimal''': self.decimal, '''lineterminator''': self.lineterminator, '''quotechar''': self.quotechar, '''quoting''': self.quoting, '''escapechar''': self.escapechar, '''comment''': self.comment, '''encoding''': self.encoding, '''dialect''': self.dialect, '''error_bad_lines''': self.error_bad_lines, '''warn_bad_lines''': self.warn_bad_lines, '''skipfooter''': self.skipfooter, '''doublequote''': self.doublequote, '''memory_map''': self.memory_map, '''float_precision''': self.float_precision, '''chunksize''': self.chunksize, '''encoding_errors''': self.encoding_errors, '''on_bad_lines''': self.on_bad_lines, '''date_format''': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , SCREAMING_SNAKE_CASE ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class A ( datasets.ArrowBasedBuilder ): __magic_name__ = CsvConfig def __lowerCAmelCase ( self ) -> Optional[int]: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if not self.config.data_files: raise ValueError(F'At least one data file must be specified, but got data_files={self.config.data_files}' ) A : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE , (str, list, tuple) ): A : str = data_files if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : int = [files] A : Optional[int] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] A : Tuple = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : List[str] = [files] A : List[str] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE , gen_kwargs={'''files''': files} ) ) return splits def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> pa.Table: """simple docstring""" if self.config.features is not None: A : Optional[int] = self.config.features.arrow_schema if all(not require_storage_cast(SCREAMING_SNAKE_CASE ) for feature in self.config.features.values() ): # cheaper cast A : List[Any] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=SCREAMING_SNAKE_CASE ) else: # more expensive cast; allows str <-> int/float or str to Audio for example A : int = table_cast(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return pa_table def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" A : Union[str, Any] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str A : int = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(SCREAMING_SNAKE_CASE ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE ) ): A : Union[str, Any] = pd.read_csv(SCREAMING_SNAKE_CASE , iterator=SCREAMING_SNAKE_CASE , dtype=SCREAMING_SNAKE_CASE , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(SCREAMING_SNAKE_CASE ): A : Dict = pa.Table.from_pandas(SCREAMING_SNAKE_CASE ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(SCREAMING_SNAKE_CASE ) except ValueError as e: logger.error(F'Failed to read file \'{file}\' with error {type(SCREAMING_SNAKE_CASE )}: {e}' ) raise
311
1
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def __lowerCamelCase ( UpperCAmelCase_ : ndarray ): """simple docstring""" return np.dot(UpperCAmelCase_ , UpperCAmelCase_ ) class _snake_case : def __init__( self , *, _lowerCamelCase = np.inf , _lowerCamelCase = "linear" , _lowerCamelCase = 0.0 , ): a :List[str] = regularization a :Optional[Any] = gamma if kernel == "linear": a :Optional[Any] = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError('''rbf kernel requires gamma''' ) if not isinstance(self.gamma , (float, int) ): raise ValueError('''gamma must be float or int''' ) if not self.gamma > 0: raise ValueError('''gamma must be > 0''' ) a :List[Any] = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: a :Dict = F'''Unknown kernel: {kernel}''' raise ValueError(_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase ): return np.dot(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase ): a :str = observations a :Any = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((a) , ) :Tuple = np.shape(_lowerCamelCase ) def to_minimize(_lowerCamelCase ) -> float: a :Union[str, Any] = 0 ((a) , ) :Tuple = np.shape(_lowerCamelCase ) for i in range(_lowerCamelCase ): for j in range(_lowerCamelCase ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(_lowerCamelCase ) a :str = LinearConstraint(_lowerCamelCase , 0 , 0 ) a :Tuple = Bounds(0 , self.regularization ) a :List[str] = minimize( _lowerCamelCase , np.ones(_lowerCamelCase ) , bounds=_lowerCamelCase , constraints=[ly_contraint] ).x a :str = l_star # calculating mean offset of separation plane to points a :Tuple = 0 for i in range(_lowerCamelCase ): for j in range(_lowerCamelCase ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) a :Optional[Any] = s / n def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ): a :List[str] = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , _lowerCamelCase ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
94
from math import pi def SCREAMING_SNAKE_CASE__ ( __a , __a ): return 2 * pi * radius * (angle / 3_60) if __name__ == "__main__": print(arc_length(90, 10))
327
0
from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __lowercase (_A ): """simple docstring""" _snake_case = """dandelin/vilt-b32-finetuned-vqa""" _snake_case = ( """This is a tool that answers a question about an image. It takes an input named `image` which should be the """ """image containing the information, as well as a `question` which should be the question in English. It """ """returns a text that is the answer to the question.""" ) _snake_case = """image_qa""" _snake_case = AutoProcessor _snake_case = AutoModelForVisualQuestionAnswering _snake_case = ["""image""", """text"""] _snake_case = ["""text"""] def __init__( self , *A , **A ) -> Tuple: requires_backends(self , ['''vision'''] ) super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self , A , A ) -> Optional[int]: return self.pre_processor(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_tensors='''pt''' ) def UpperCAmelCase ( self , A ) -> List[str]: with torch.no_grad(): return self.model(**__SCREAMING_SNAKE_CASE ).logits def UpperCAmelCase ( self , A ) -> Dict: snake_case : Union[str, Any] = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
363
from collections import defaultdict def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> bool: snake_case : List[str] = first_str.lower().strip() snake_case : List[str] = second_str.lower().strip() # Remove whitespace snake_case : Any = first_str.replace(""" """ ,"""""" ) snake_case : List[str] = second_str.replace(""" """ ,"""""" ) # Strings of different lengths are not anagrams if len(lowercase ) != len(lowercase ): return False # Default values for count should be 0 snake_case : defaultdict[str, int] = defaultdict(lowercase ) # For each character in input strings, # increment count in the corresponding for i in range(len(lowercase ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() lowerCamelCase : List[Any] = input('Enter the first string ').strip() lowerCamelCase : Optional[int] = input('Enter the second string ').strip() lowerCamelCase : Optional[Any] = check_anagrams(input_a, input_b) print(f"""{input_a} and {input_b} are {"" if status else "not "}anagrams.""")
176
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) _a = { "configuration_speech_to_text": ["SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Speech2TextConfig"], "processing_speech_to_text": ["Speech2TextProcessor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = ["Speech2TextTokenizer"] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = ["Speech2TextFeatureExtractor"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ "TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFSpeech2TextForConditionalGeneration", "TFSpeech2TextModel", "TFSpeech2TextPreTrainedModel", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ "SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "Speech2TextForConditionalGeneration", "Speech2TextModel", "Speech2TextPreTrainedModel", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys _a = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
209
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _a = logging.get_logger(__name__) _a = "▁" _a = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _a = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } _a = { "facebook/m2m100_418M": 1_024, } # fmt: off _a = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class __A ( lowerCAmelCase ): '''simple docstring''' lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ["""input_ids""", """attention_mask"""] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase="<s>" , __lowerCAmelCase="</s>" , __lowerCAmelCase="</s>" , __lowerCAmelCase="<pad>" , __lowerCAmelCase="<unk>" , __lowerCAmelCase="m2m100" , __lowerCAmelCase = None , __lowerCAmelCase=8 , **__lowerCAmelCase , ): '''simple docstring''' lowerCamelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs lowerCamelCase__ = language_codes lowerCamelCase__ = FAIRSEQ_LANGUAGE_CODES[language_codes] lowerCamelCase__ = {lang_code: F'__{lang_code}__' for lang_code in fairseq_language_code} lowerCamelCase__ = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__lowerCAmelCase ) for lang_code in fairseq_language_code if self.get_lang_token(__lowerCAmelCase ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__lowerCAmelCase , tgt_lang=__lowerCAmelCase , bos_token=__lowerCAmelCase , eos_token=__lowerCAmelCase , sep_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , pad_token=__lowerCAmelCase , language_codes=__lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__lowerCAmelCase , **__lowerCAmelCase , ) lowerCamelCase__ = vocab_file lowerCamelCase__ = load_json(__lowerCAmelCase ) lowerCamelCase__ = {v: k for k, v in self.encoder.items()} lowerCamelCase__ = spm_file lowerCamelCase__ = load_spm(__lowerCAmelCase , self.sp_model_kwargs ) lowerCamelCase__ = len(self.encoder ) lowerCamelCase__ = { self.get_lang_token(__lowerCAmelCase ): self.encoder_size + i for i, lang_code in enumerate(__lowerCAmelCase ) } lowerCamelCase__ = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__lowerCAmelCase )} lowerCamelCase__ = {v: k for k, v in self.lang_token_to_id.items()} lowerCamelCase__ = src_lang if src_lang is not None else '''en''' lowerCamelCase__ = tgt_lang lowerCamelCase__ = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowerCamelCase__ = num_madeup_words @property def __lowerCamelCase ( self ): '''simple docstring''' return len(self.encoder ) + len(self.lang_token_to_id ) @property def __lowerCamelCase ( self ): '''simple docstring''' return self._src_lang @src_lang.setter def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' return self.sp_model.encode(__lowerCAmelCase , out_type=__lowerCAmelCase ) def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__lowerCAmelCase , self.encoder[self.unk_token] ) def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__lowerCAmelCase , self.unk_token ) def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = [] lowerCamelCase__ = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__lowerCAmelCase ) + token lowerCamelCase__ = [] else: current_sub_tokens.append(__lowerCAmelCase ) out_string += self.sp_model.decode(__lowerCAmelCase ) return out_string.strip() def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCAmelCase , token_ids_a=__lowerCAmelCase , already_has_special_tokens=__lowerCAmelCase ) lowerCamelCase__ = [1] * len(self.prefix_tokens ) lowerCamelCase__ = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__lowerCAmelCase )) + suffix_ones return prefix_ones + ([0] * len(__lowerCAmelCase )) + ([0] * len(__lowerCAmelCase )) + suffix_ones def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = None ): '''simple docstring''' 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 __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = {self.convert_ids_to_tokens(__lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): '''simple docstring''' lowerCamelCase__ = self.__dict__.copy() lowerCamelCase__ = None return state def __setstate__( self , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowerCamelCase__ = {} lowerCamelCase__ = load_spm(self.spm_file , self.sp_model_kwargs ) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = None ): '''simple docstring''' lowerCamelCase__ = Path(__lowerCAmelCase ) if not save_dir.is_dir(): raise OSError(F'{save_directory} should be a directory' ) lowerCamelCase__ = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) lowerCamelCase__ = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __lowerCAmelCase ) if os.path.abspath(self.spm_file ) != os.path.abspath(__lowerCAmelCase ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __lowerCAmelCase ) elif not os.path.isfile(self.spm_file ): with open(__lowerCAmelCase , '''wb''' ) as fi: lowerCamelCase__ = self.sp_model.serialized_model_proto() fi.write(__lowerCAmelCase ) return (str(__lowerCAmelCase ), str(__lowerCAmelCase )) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = "en" , __lowerCAmelCase = None , __lowerCAmelCase = "ro" , **__lowerCAmelCase , ): '''simple docstring''' lowerCamelCase__ = src_lang lowerCamelCase__ = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , **__lowerCAmelCase ): '''simple docstring''' if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowerCamelCase__ = src_lang lowerCamelCase__ = self(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase , **__lowerCAmelCase ) lowerCamelCase__ = self.get_lang_id(__lowerCAmelCase ) lowerCamelCase__ = tgt_lang_id return inputs def __lowerCamelCase ( self ): '''simple docstring''' self.set_src_lang_special_tokens(self.src_lang ) def __lowerCamelCase ( self ): '''simple docstring''' self.set_tgt_lang_special_tokens(self.tgt_lang ) def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = self.get_lang_token(__lowerCAmelCase ) lowerCamelCase__ = self.lang_token_to_id[lang_token] lowerCamelCase__ = [self.cur_lang_id] lowerCamelCase__ = [self.eos_token_id] def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = self.get_lang_token(__lowerCAmelCase ) lowerCamelCase__ = self.lang_token_to_id[lang_token] lowerCamelCase__ = [self.cur_lang_id] lowerCamelCase__ = [self.eos_token_id] def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' return self.lang_code_to_token[lang] def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = self.get_lang_token(__lowerCAmelCase ) return self.lang_token_to_id[lang_token] def lowerCAmelCase__(__snake_case ,__snake_case ) -> sentencepiece.SentencePieceProcessor: '''simple docstring''' lowerCamelCase__ = sentencepiece.SentencePieceProcessor(**__snake_case ) spm.Load(str(__snake_case ) ) return spm def lowerCAmelCase__(__snake_case ) -> Union[Dict, List]: '''simple docstring''' with open(__snake_case ,'''r''' ) as f: return json.load(__snake_case ) def lowerCAmelCase__(__snake_case ,__snake_case ) -> None: '''simple docstring''' with open(__snake_case ,'''w''' ) as f: json.dump(__snake_case ,__snake_case ,indent=2 )
209
1
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def A ( a_=None ) -> int: if subparsers is not None: __UpperCamelCase : List[Any] =subparsers.add_parser('env' ) else: __UpperCamelCase : Optional[int] =argparse.ArgumentParser('Accelerate env command' ) parser.add_argument( '--config_file' ,default=a_ ,help='The config file to use for the default values in the launching script.' ) if subparsers is not None: parser.set_defaults(func=a_ ) return parser def A ( a_ ) -> Optional[Any]: __UpperCamelCase : Optional[Any] =torch.__version__ __UpperCamelCase : int =torch.cuda.is_available() __UpperCamelCase : Any =is_xpu_available() __UpperCamelCase : Any =is_npu_available() __UpperCamelCase : Optional[Any] ='Not found' # Get the default from the config file. if args.config_file is not None or os.path.isfile(a_ ): __UpperCamelCase : List[str] =load_config_from_file(args.config_file ).to_dict() __UpperCamelCase : Union[str, Any] ={ '`Accelerate` version': version, 'Platform': platform.platform(), 'Python version': platform.python_version(), 'Numpy version': np.__version__, 'PyTorch version (GPU?)': F'{pt_version} ({pt_cuda_available})', 'PyTorch XPU available': str(a_ ), 'PyTorch NPU available': str(a_ ), 'System RAM': F'{psutil.virtual_memory().total / 1_024 ** 3:.2f} GB', } if pt_cuda_available: __UpperCamelCase : Tuple =torch.cuda.get_device_name() print('\nCopy-and-paste the text below in your GitHub issue\n' ) print('\n'.join([F'- {prop}: {val}' for prop, val in info.items()] ) ) print('- `Accelerate` default config:' if args.config_file is None else '- `Accelerate` config passed:' ) __UpperCamelCase : Optional[int] =( '\n'.join([F'\t- {prop}: {val}' for prop, val in accelerate_config.items()] ) if isinstance(a_ ,a_ ) else F'\t{accelerate_config}' ) print(a_ ) __UpperCamelCase : Optional[int] =accelerate_config return info def A ( ) -> int: __UpperCamelCase : List[str] =env_command_parser() __UpperCamelCase : str =parser.parse_args() env_command(a_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
245
def A ( a_ ) -> bool: return sum(i for i in range(1 ,number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print('''Program to check whether a number is a Perfect number or not...''') A_ :List[str] = int(input('''Enter number: ''').strip()) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
245
1
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _a ( UpperCamelCase__ ): _lowercase : List[str] = ['''image_processor''', '''tokenizer'''] _lowercase : Any = '''BlipImageProcessor''' _lowercase : Dict = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self: Any , UpperCamelCase_: Optional[int] , UpperCamelCase_: Optional[Any] ) -> Optional[int]: """simple docstring""" lowercase__ = False super().__init__(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = self.image_processor def __call__( self: int , UpperCamelCase_: ImageInput = None , UpperCamelCase_: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCamelCase_: bool = True , UpperCamelCase_: Union[bool, str, PaddingStrategy] = False , UpperCamelCase_: Union[bool, str, TruncationStrategy] = None , UpperCamelCase_: Optional[int] = None , UpperCamelCase_: int = 0 , UpperCamelCase_: Optional[int] = None , UpperCamelCase_: Optional[bool] = None , UpperCamelCase_: bool = False , UpperCamelCase_: bool = False , UpperCamelCase_: bool = False , UpperCamelCase_: bool = False , UpperCamelCase_: bool = False , UpperCamelCase_: bool = True , UpperCamelCase_: Optional[Union[str, TensorType]] = None , **UpperCamelCase_: Any , ) -> BatchEncoding: """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: lowercase__ = self.tokenizer lowercase__ = self.tokenizer( text=UpperCamelCase_ , add_special_tokens=UpperCamelCase_ , padding=UpperCamelCase_ , truncation=UpperCamelCase_ , max_length=UpperCamelCase_ , stride=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , return_overflowing_tokens=UpperCamelCase_ , return_special_tokens_mask=UpperCamelCase_ , return_offsets_mapping=UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ , return_length=UpperCamelCase_ , verbose=UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ , ) return text_encoding # add pixel_values lowercase__ = self.image_processor(UpperCamelCase_ , return_tensors=UpperCamelCase_ ) if text is not None: lowercase__ = self.tokenizer( text=UpperCamelCase_ , add_special_tokens=UpperCamelCase_ , padding=UpperCamelCase_ , truncation=UpperCamelCase_ , max_length=UpperCamelCase_ , stride=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , return_overflowing_tokens=UpperCamelCase_ , return_special_tokens_mask=UpperCamelCase_ , return_offsets_mapping=UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ , return_length=UpperCamelCase_ , verbose=UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ , ) else: lowercase__ = None if text_encoding is not None: encoding_image_processor.update(UpperCamelCase_ ) return encoding_image_processor def lowerCamelCase_ ( self: Any , *UpperCamelCase_: int , **UpperCamelCase_: str ) -> int: """simple docstring""" return self.tokenizer.batch_decode(*UpperCamelCase_ , **UpperCamelCase_ ) def lowerCamelCase_ ( self: Union[str, Any] , *UpperCamelCase_: Optional[int] , **UpperCamelCase_: Union[str, Any] ) -> Dict: """simple docstring""" return self.tokenizer.decode(*UpperCamelCase_ , **UpperCamelCase_ ) @property def lowerCamelCase_ ( self: int ) -> List[Any]: """simple docstring""" lowercase__ = self.tokenizer.model_input_names lowercase__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
110
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class _a ( UpperCamelCase__ ): _lowercase : torch.FloatTensor class _a ( nn.Module ): def __init__( self: int , UpperCamelCase_: int=3 , UpperCamelCase_: Optional[Any]=3 , UpperCamelCase_: Union[str, Any]=("DownEncoderBlock2D",) , UpperCamelCase_: Optional[int]=(64,) , UpperCamelCase_: Tuple=2 , UpperCamelCase_: Dict=32 , UpperCamelCase_: Any="silu" , UpperCamelCase_: Optional[int]=True , ) -> Union[str, Any]: """simple docstring""" super().__init__() lowercase__ = layers_per_block lowercase__ = torch.nn.Convad( UpperCamelCase_ , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) lowercase__ = None lowercase__ = nn.ModuleList([] ) # down lowercase__ = block_out_channels[0] for i, down_block_type in enumerate(UpperCamelCase_ ): lowercase__ = output_channel lowercase__ = block_out_channels[i] lowercase__ = i == len(UpperCamelCase_ ) - 1 lowercase__ = get_down_block( UpperCamelCase_ , num_layers=self.layers_per_block , in_channels=UpperCamelCase_ , out_channels=UpperCamelCase_ , add_downsample=not is_final_block , resnet_eps=1E-6 , downsample_padding=0 , resnet_act_fn=UpperCamelCase_ , resnet_groups=UpperCamelCase_ , attention_head_dim=UpperCamelCase_ , temb_channels=UpperCamelCase_ , ) self.down_blocks.append(UpperCamelCase_ ) # mid lowercase__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=UpperCamelCase_ , output_scale_factor=1 , resnet_time_scale_shift='''default''' , attention_head_dim=block_out_channels[-1] , resnet_groups=UpperCamelCase_ , temb_channels=UpperCamelCase_ , ) # out lowercase__ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=UpperCamelCase_ , eps=1E-6 ) lowercase__ = nn.SiLU() lowercase__ = 2 * out_channels if double_z else out_channels lowercase__ = nn.Convad(block_out_channels[-1] , UpperCamelCase_ , 3 , padding=1 ) lowercase__ = False def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase_: str ) -> str: """simple docstring""" lowercase__ = x lowercase__ = self.conv_in(UpperCamelCase_ ) if self.training and self.gradient_checkpointing: def create_custom_forward(UpperCamelCase_: Dict ): def custom_forward(*UpperCamelCase_: List[str] ): return module(*UpperCamelCase_ ) return custom_forward # down if is_torch_version('''>=''' , '''1.11.0''' ): for down_block in self.down_blocks: lowercase__ = torch.utils.checkpoint.checkpoint( create_custom_forward(UpperCamelCase_ ) , UpperCamelCase_ , use_reentrant=UpperCamelCase_ ) # middle lowercase__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCamelCase_ , use_reentrant=UpperCamelCase_ ) else: for down_block in self.down_blocks: lowercase__ = torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCamelCase_ ) , UpperCamelCase_ ) # middle lowercase__ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , UpperCamelCase_ ) else: # down for down_block in self.down_blocks: lowercase__ = down_block(UpperCamelCase_ ) # middle lowercase__ = self.mid_block(UpperCamelCase_ ) # post-process lowercase__ = self.conv_norm_out(UpperCamelCase_ ) lowercase__ = self.conv_act(UpperCamelCase_ ) lowercase__ = self.conv_out(UpperCamelCase_ ) return sample class _a ( nn.Module ): def __init__( self: Dict , UpperCamelCase_: int=3 , UpperCamelCase_: Optional[Any]=3 , UpperCamelCase_: int=("UpDecoderBlock2D",) , UpperCamelCase_: Any=(64,) , UpperCamelCase_: Optional[Any]=2 , UpperCamelCase_: List[Any]=32 , UpperCamelCase_: Optional[Any]="silu" , UpperCamelCase_: Dict="group" , ) -> Any: """simple docstring""" super().__init__() lowercase__ = layers_per_block lowercase__ = nn.Convad( UpperCamelCase_ , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) lowercase__ = None lowercase__ = nn.ModuleList([] ) lowercase__ = in_channels if norm_type == '''spatial''' else None # mid lowercase__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=UpperCamelCase_ , output_scale_factor=1 , resnet_time_scale_shift='''default''' if norm_type == '''group''' else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=UpperCamelCase_ , temb_channels=UpperCamelCase_ , ) # up lowercase__ = list(reversed(UpperCamelCase_ ) ) lowercase__ = reversed_block_out_channels[0] for i, up_block_type in enumerate(UpperCamelCase_ ): lowercase__ = output_channel lowercase__ = reversed_block_out_channels[i] lowercase__ = i == len(UpperCamelCase_ ) - 1 lowercase__ = get_up_block( UpperCamelCase_ , num_layers=self.layers_per_block + 1 , in_channels=UpperCamelCase_ , out_channels=UpperCamelCase_ , prev_output_channel=UpperCamelCase_ , add_upsample=not is_final_block , resnet_eps=1E-6 , resnet_act_fn=UpperCamelCase_ , resnet_groups=UpperCamelCase_ , attention_head_dim=UpperCamelCase_ , temb_channels=UpperCamelCase_ , resnet_time_scale_shift=UpperCamelCase_ , ) self.up_blocks.append(UpperCamelCase_ ) lowercase__ = output_channel # out if norm_type == "spatial": lowercase__ = SpatialNorm(block_out_channels[0] , UpperCamelCase_ ) else: lowercase__ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=UpperCamelCase_ , eps=1E-6 ) lowercase__ = nn.SiLU() lowercase__ = nn.Convad(block_out_channels[0] , UpperCamelCase_ , 3 , padding=1 ) lowercase__ = False def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: List[str]=None ) -> int: """simple docstring""" lowercase__ = z lowercase__ = self.conv_in(UpperCamelCase_ ) lowercase__ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(UpperCamelCase_: List[str] ): def custom_forward(*UpperCamelCase_: int ): return module(*UpperCamelCase_ ) return custom_forward if is_torch_version('''>=''' , '''1.11.0''' ): # middle lowercase__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCamelCase_ , UpperCamelCase_ , use_reentrant=UpperCamelCase_ ) lowercase__ = sample.to(UpperCamelCase_ ) # up for up_block in self.up_blocks: lowercase__ = torch.utils.checkpoint.checkpoint( create_custom_forward(UpperCamelCase_ ) , UpperCamelCase_ , UpperCamelCase_ , use_reentrant=UpperCamelCase_ ) else: # middle lowercase__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = sample.to(UpperCamelCase_ ) # up for up_block in self.up_blocks: lowercase__ = torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCamelCase_ ) , UpperCamelCase_ , UpperCamelCase_ ) else: # middle lowercase__ = self.mid_block(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = sample.to(UpperCamelCase_ ) # up for up_block in self.up_blocks: lowercase__ = up_block(UpperCamelCase_ , UpperCamelCase_ ) # post-process if latent_embeds is None: lowercase__ = self.conv_norm_out(UpperCamelCase_ ) else: lowercase__ = self.conv_norm_out(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = self.conv_act(UpperCamelCase_ ) lowercase__ = self.conv_out(UpperCamelCase_ ) return sample class _a ( nn.Module ): def __init__( self: Tuple , UpperCamelCase_: List[str] , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Optional[int]=None , UpperCamelCase_: List[str]="random" , UpperCamelCase_: Union[str, Any]=False , UpperCamelCase_: Dict=True ) -> List[Any]: """simple docstring""" super().__init__() lowercase__ = n_e lowercase__ = vq_embed_dim lowercase__ = beta lowercase__ = legacy lowercase__ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) lowercase__ = remap if self.remap is not None: self.register_buffer('''used''' , torch.tensor(np.load(self.remap ) ) ) lowercase__ = self.used.shape[0] lowercase__ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": lowercase__ = self.re_embed lowercase__ = self.re_embed + 1 print( f'Remapping {self.n_e} indices to {self.re_embed} indices. ' f'Using {self.unknown_index} for unknown indices.' ) else: lowercase__ = n_e lowercase__ = sane_index_shape def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase_: Any ) -> Dict: """simple docstring""" lowercase__ = inds.shape assert len(UpperCamelCase_ ) > 1 lowercase__ = inds.reshape(ishape[0] , -1 ) lowercase__ = self.used.to(UpperCamelCase_ ) lowercase__ = (inds[:, :, None] == used[None, None, ...]).long() lowercase__ = match.argmax(-1 ) lowercase__ = match.sum(2 ) < 1 if self.unknown_index == "random": lowercase__ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: lowercase__ = self.unknown_index return new.reshape(UpperCamelCase_ ) def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase_: Tuple ) -> str: """simple docstring""" lowercase__ = inds.shape assert len(UpperCamelCase_ ) > 1 lowercase__ = inds.reshape(ishape[0] , -1 ) lowercase__ = self.used.to(UpperCamelCase_ ) if self.re_embed > self.used.shape[0]: # extra token lowercase__ = 0 # simply set to zero lowercase__ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , UpperCamelCase_ ) return back.reshape(UpperCamelCase_ ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase_: Any ) -> Tuple: """simple docstring""" lowercase__ = z.permute(0 , 2 , 3 , 1 ).contiguous() lowercase__ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z lowercase__ = torch.argmin(torch.cdist(UpperCamelCase_ , self.embedding.weight ) , dim=1 ) lowercase__ = self.embedding(UpperCamelCase_ ).view(z.shape ) lowercase__ = None lowercase__ = None # compute loss for embedding if not self.legacy: lowercase__ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: lowercase__ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients lowercase__ = z + (z_q - z).detach() # reshape back to match original input shape lowercase__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: lowercase__ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis lowercase__ = self.remap_to_used(UpperCamelCase_ ) lowercase__ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: lowercase__ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase_: Tuple , UpperCamelCase_: List[Any] ) -> List[str]: """simple docstring""" if self.remap is not None: lowercase__ = indices.reshape(shape[0] , -1 ) # add batch axis lowercase__ = self.unmap_to_all(UpperCamelCase_ ) lowercase__ = indices.reshape(-1 ) # flatten again # get quantized latent vectors lowercase__ = self.embedding(UpperCamelCase_ ) if shape is not None: lowercase__ = z_q.view(UpperCamelCase_ ) # reshape back to match original input shape lowercase__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class _a ( UpperCamelCase__ ): def __init__( self: Union[str, Any] , UpperCamelCase_: Any , UpperCamelCase_: List[Any]=False ) -> str: """simple docstring""" lowercase__ = parameters lowercase__ , lowercase__ = torch.chunk(UpperCamelCase_ , 2 , dim=1 ) lowercase__ = torch.clamp(self.logvar , -30.0 , 20.0 ) lowercase__ = deterministic lowercase__ = torch.exp(0.5 * self.logvar ) lowercase__ = torch.exp(self.logvar ) if self.deterministic: lowercase__ = lowercase__ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def lowerCamelCase_ ( self: Any , UpperCamelCase_: Optional[torch.Generator] = None ) -> torch.FloatTensor: """simple docstring""" lowercase__ = randn_tensor( self.mean.shape , generator=UpperCamelCase_ , device=self.parameters.device , dtype=self.parameters.dtype ) lowercase__ = self.mean + self.std * sample return x def lowerCamelCase_ ( self: List[str] , UpperCamelCase_: str=None ) -> Tuple: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def lowerCamelCase_ ( self: int , UpperCamelCase_: Any , UpperCamelCase_: Any=[1, 2, 3] ) -> Tuple: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) lowercase__ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=UpperCamelCase_ ) def lowerCamelCase_ ( self: str ) -> Any: """simple docstring""" return self.mean
110
1
"""simple docstring""" import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) def __lowercase ( lowerCamelCase : Tuple ): UpperCamelCase_ : int = MobileNetVaConfig(layer_norm_eps=0.0_0_1 ) if "_quant" in model_name: raise ValueError('Quantized models are not supported.' ) UpperCamelCase_ : List[Any] = re.match(R'^mobilenet_v1_([^_]*)_([^_]*)$' , __a ) if matches: UpperCamelCase_ : Optional[Any] = float(matches[1] ) UpperCamelCase_ : str = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". UpperCamelCase_ : List[Any] = 1001 UpperCamelCase_ : str = 'imagenet-1k-id2label.json' UpperCamelCase_ : int = 'huggingface/label-files' UpperCamelCase_ : List[str] = json.load(open(hf_hub_download(__a , __a , repo_type='dataset' ) , 'r' ) ) UpperCamelCase_ : Tuple = {int(__a ) + 1: v for k, v in idalabel.items()} UpperCamelCase_ : List[Any] = 'background' UpperCamelCase_ : Any = idalabel UpperCamelCase_ : List[Any] = {v: k for k, v in idalabel.items()} return config def __lowercase ( ): UpperCamelCase_ : Optional[int] = 'http://images.cocodataset.org/val2017/000000039769.jpg' UpperCamelCase_ : Union[str, Any] = Image.open(requests.get(__a , stream=__a ).raw ) return im @torch.no_grad() def __lowercase ( lowerCamelCase : List[Any] , lowerCamelCase : Dict , lowerCamelCase : Dict , lowerCamelCase : int=False ): UpperCamelCase_ : str = get_mobilenet_va_config(__a ) # Load 🤗 model UpperCamelCase_ : Tuple = MobileNetVaForImageClassification(__a ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(__a , __a , __a ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor UpperCamelCase_ : Tuple = MobileNetVaImageProcessor( crop_size={'width': config.image_size, 'height': config.image_size} , size={'shortest_edge': config.image_size + 32} , ) UpperCamelCase_ : int = image_processor(images=prepare_img() , return_tensors='pt' ) UpperCamelCase_ : Union[str, Any] = model(**__a ) UpperCamelCase_ : Tuple = outputs.logits assert logits.shape == (1, 1001) if model_name == "mobilenet_v1_1.0_224": UpperCamelCase_ : Optional[int] = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ) elif model_name == "mobilenet_v1_0.75_192": UpperCamelCase_ : Any = torch.tensor([-3.9_4_4_0, -2.3_1_4_1, -0.3_3_3_3] ) else: UpperCamelCase_ : Tuple = None if expected_logits is not None: assert torch.allclose(logits[0, :3] , __a , atol=1e-4 ) Path(__a ).mkdir(exist_ok=__a ) print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__a ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__a ) if push_to_hub: print('Pushing to the hub...' ) UpperCamelCase_ : List[Any] = 'google/' + model_name image_processor.push_to_hub(__a ) model.push_to_hub(__a ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) a_ = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
350
import numpy # List of input, output pairs a_ = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) a_ = (((515, 22, 13), 555), ((61, 35, 49), 150)) a_ = [2, 4, 1, 5] a_ = len(train_data) a_ = 0.009 def __lowercase ( lowerCamelCase : Optional[int] , lowerCamelCase : Any="train" ): return calculate_hypothesis_value(lowerCamelCase , lowerCamelCase ) - output( lowerCamelCase , lowerCamelCase ) def __lowercase ( lowerCamelCase : str ): UpperCamelCase_ : List[str] = 0 for i in range(len(lowerCamelCase ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def __lowercase ( lowerCamelCase : int , lowerCamelCase : Any ): if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def __lowercase ( lowerCamelCase : Union[str, Any] , lowerCamelCase : List[Any] ): if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def __lowercase ( lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict=m ): UpperCamelCase_ : str = 0 for i in range(lowerCamelCase ): if index == -1: summation_value += _error(lowerCamelCase ) else: summation_value += _error(lowerCamelCase ) * train_data[i][0][index] return summation_value def __lowercase ( lowerCamelCase : int ): UpperCamelCase_ : List[str] = summation_of_cost_derivative(lowerCamelCase , lowerCamelCase ) / m return cost_derivative_value def __lowercase ( ): global parameter_vector # Tune these values to set a tolerance value for predicted output UpperCamelCase_ : Optional[int] = 0.0_0_0_0_0_2 UpperCamelCase_ : Optional[int] = 0 UpperCamelCase_ : Union[str, Any] = 0 while True: j += 1 UpperCamelCase_ : Dict = [0, 0, 0, 0] for i in range(0 , len(lowerCamelCase ) ): UpperCamelCase_ : Any = get_cost_derivative(i - 1 ) UpperCamelCase_ : List[str] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( lowerCamelCase , lowerCamelCase , atol=lowerCamelCase , rtol=lowerCamelCase , ): break UpperCamelCase_ : Optional[Any] = temp_parameter_vector print(('Number of iterations:', j) ) def __lowercase ( ): for i in range(len(lowerCamelCase ) ): print(('Actual output value:', output(lowerCamelCase , 'test' )) ) print(('Hypothesis output:', calculate_hypothesis_value(lowerCamelCase , 'test' )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
50
0
"""simple docstring""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_codegen import CodeGenTokenizer lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} lowerCamelCase_ = { '''vocab_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json''', }, '''merges_file''': { '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''Salesforce/codegen-350M-mono''': ( '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json''' ), }, } lowerCamelCase_ = { '''Salesforce/codegen-350M-mono''': 2048, } class UpperCamelCase_ (__A ): __magic_name__ = VOCAB_FILES_NAMES __magic_name__ = PRETRAINED_VOCAB_FILES_MAP __magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ = ['''input_ids''', '''attention_mask'''] __magic_name__ = CodeGenTokenizer def __init__( self : Optional[int] , lowerCAmelCase_ : List[Any]=None , lowerCAmelCase_ : List[Any]=None , lowerCAmelCase_ : List[str]=None , lowerCAmelCase_ : List[str]="<|endoftext|>" , lowerCAmelCase_ : Dict="<|endoftext|>" , lowerCAmelCase_ : List[Any]="<|endoftext|>" , lowerCAmelCase_ : List[Any]=False , **lowerCAmelCase_ : Tuple , ) -> Any: super().__init__( lowerCAmelCase_ , lowerCAmelCase_ , tokenizer_file=lowerCAmelCase_ , unk_token=lowerCAmelCase_ , bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , add_prefix_space=lowerCAmelCase_ , **lowerCAmelCase_ , ) if kwargs.pop("add_bos_token" , lowerCAmelCase_ ): UpperCAmelCase_ : str = kwargs.pop("name_or_path" , "" ) raise ValueError( "Currenty GPT2's fast tokenizer does NOT support adding a BOS token." "Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n" f"""`CodeGenTokenizer.from_pretrained('{model_id}')`\nor\n""" f"""`AutoTokenizer.from_pretrained('{model_id}', use_fast=False)`\n""" "This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005." " so that the fast tokenizer works correctly." ) UpperCAmelCase_ : int = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCAmelCase_ ) != add_prefix_space: UpperCAmelCase_ : str = getattr(lowerCAmelCase_ , pre_tok_state.pop("type" ) ) UpperCAmelCase_ : Union[str, Any] = add_prefix_space UpperCAmelCase_ : Tuple = pre_tok_class(**lowerCAmelCase_ ) UpperCAmelCase_ : Dict = add_prefix_space def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , *lowerCAmelCase_ : Union[str, Any] , **lowerCAmelCase_ : List[str] ) -> BatchEncoding: UpperCAmelCase_ : List[str] = kwargs.get("is_split_into_words" , lowerCAmelCase_ ) assert self.add_prefix_space or not is_split_into_words, ( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCAmelCase_ , **lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple , *lowerCAmelCase_ : List[str] , **lowerCAmelCase_ : Any ) -> BatchEncoding: UpperCAmelCase_ : int = kwargs.get("is_split_into_words" , lowerCAmelCase_ ) assert self.add_prefix_space or not is_split_into_words, ( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCAmelCase_ , **lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ) -> Tuple[str]: UpperCAmelCase_ : List[Any] = self._tokenizer.model.save(lowerCAmelCase_ , name=lowerCAmelCase_ ) return tuple(lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"] , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = None , lowerCAmelCase_ : Optional[List[str]] = None , **lowerCAmelCase_ : List[str] , ) -> str: UpperCAmelCase_ : str = super().decode( token_ids=lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ , clean_up_tokenization_spaces=lowerCAmelCase_ , **lowerCAmelCase_ , ) if truncate_before_pattern is not None and len(lowerCAmelCase_ ) > 0: UpperCAmelCase_ : List[Any] = self.truncate(lowerCAmelCase_ , lowerCAmelCase_ ) return decoded_text def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : Any , lowerCAmelCase_ : int ) -> List[Any]: def find_re(lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : Tuple ): UpperCAmelCase_ : List[Any] = pattern.search(lowerCAmelCase_ , lowerCAmelCase_ ) return m.start() if m else -1 UpperCAmelCase_ : Union[str, Any] = [re.compile(lowerCAmelCase_ , re.MULTILINE ) for pattern in truncate_before_pattern] UpperCAmelCase_ : Union[str, Any] = list(re.finditer("^print" , lowerCAmelCase_ , re.MULTILINE ) ) if len(lowerCAmelCase_ ) > 1: UpperCAmelCase_ : Optional[int] = completion[: prints[1].start()] UpperCAmelCase_ : Union[str, Any] = list(re.finditer("^def" , lowerCAmelCase_ , re.MULTILINE ) ) if len(lowerCAmelCase_ ) > 1: UpperCAmelCase_ : List[str] = completion[: defs[1].start()] UpperCAmelCase_ : Tuple = 0 UpperCAmelCase_ : Tuple = [ pos for pos in [find_re(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) for terminal in terminals] if pos != -1 ] if len(lowerCAmelCase_ ) > 0: return completion[: min(lowerCAmelCase_ )] else: return completion
268
"""simple docstring""" def snake_case ( A__ ,A__ ): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + fn) UpperCAmelCase_ : Dict = (boundary[1] - boundary[0]) / steps UpperCAmelCase_ : Optional[int] = boundary[0] UpperCAmelCase_ : str = boundary[1] UpperCAmelCase_ : Tuple = make_points(A__ ,A__ ,A__ ) UpperCAmelCase_ : List[str] = 0.0 y += (h / 2.0) * f(A__ ) for i in x_i: # print(i) y += h * f(A__ ) y += (h / 2.0) * f(A__ ) return y def snake_case ( A__ ,A__ ,A__ ): UpperCAmelCase_ : Union[str, Any] = a + h while x < (b - h): yield x UpperCAmelCase_ : Optional[Any] = x + h def snake_case ( A__ ): # enter your function here UpperCAmelCase_ : Dict = (x - 0) * (x - 0) return y def snake_case ( ): UpperCAmelCase_ : Dict = 0.0 # Lower bound of integration UpperCAmelCase_ : Optional[int] = 1.0 # Upper bound of integration UpperCAmelCase_ : Dict = 10.0 # define number of steps or resolution UpperCAmelCase_ : List[Any] = [a, b] # define boundary of integration UpperCAmelCase_ : Union[str, Any] = method_a(A__ ,A__ ) print(F"""y = {y}""" ) if __name__ == "__main__": main()
268
1
"""simple docstring""" import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def _snake_case ( A_ ): lowerCAmelCase__ : Any = [] for line in lines: lowerCAmelCase__ : int = re.sub(r'''#.*''' , '''''' , A_ ) # remove comments if line: filtered_lines.append(A_ ) lowerCAmelCase__ : Optional[int] = '''\n'''.join(A_ ) # Make a hash from all this code lowerCAmelCase__ : int = full_str.encode('''utf-8''' ) return shaaaa(A_ ).hexdigest() # get importable module names and hash for caching __UpperCamelCase : Any = { '''csv''': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), '''json''': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), '''pandas''': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), '''parquet''': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), '''arrow''': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), '''text''': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), '''imagefolder''': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), '''audiofolder''': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions __UpperCamelCase : Optional[Any] = { '''.csv''': ('''csv''', {}), '''.tsv''': ('''csv''', {'''sep''': '''\t'''}), '''.json''': ('''json''', {}), '''.jsonl''': ('''json''', {}), '''.parquet''': ('''parquet''', {}), '''.arrow''': ('''arrow''', {}), '''.txt''': ('''text''', {}), } _EXTENSION_TO_MODULE.update({ext: ('''imagefolder''', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('''imagefolder''', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('''audiofolder''', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('''audiofolder''', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) __UpperCamelCase : Union[str, Any] = {'''imagefolder''', '''audiofolder'''} # Used to filter data files based on extensions given a module name __UpperCamelCase : Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('''.zip''') _MODULE_TO_EXTENSIONS["audiofolder"].append('''.zip''')
354
"""simple docstring""" import math def __SCREAMING_SNAKE_CASE ( A_ , A_ = 0 , A_ = 0 ): lowerCAmelCase__ : Tuple = end or len(A_ ) for i in range(A_ , A_ ): lowerCAmelCase__ : Dict = i lowerCAmelCase__ : List[Any] = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: lowerCAmelCase__ : str = array[temp_index - 1] temp_index -= 1 lowerCAmelCase__ : int = temp_index_value return array def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ ): # Max Heap lowerCAmelCase__ : List[str] = index lowerCAmelCase__ : Any = 2 * index + 1 # Left Node lowerCAmelCase__ : int = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: lowerCAmelCase__ : Tuple = left_index if right_index < heap_size and array[largest] < array[right_index]: lowerCAmelCase__ : int = right_index if largest != index: lowerCAmelCase__ ,lowerCAmelCase__ : Dict = array[largest], array[index] heapify(A_ , A_ , A_ ) def __SCREAMING_SNAKE_CASE ( A_ ): lowerCAmelCase__ : Any = len(A_ ) for i in range(n // 2 , -1 , -1 ): heapify(A_ , A_ , A_ ) for i in range(n - 1 , 0 , -1 ): lowerCAmelCase__ ,lowerCAmelCase__ : List[str] = array[0], array[i] heapify(A_ , 0 , A_ ) return array def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ , A_ ): if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ , A_ ): lowerCAmelCase__ : str = low lowerCAmelCase__ : Union[str, Any] = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i lowerCAmelCase__ ,lowerCAmelCase__ : Union[str, Any] = array[j], array[i] i += 1 def __SCREAMING_SNAKE_CASE ( A_ ): if len(A_ ) == 0: return array lowerCAmelCase__ : int = 2 * math.ceil(math.loga(len(A_ ) ) ) lowerCAmelCase__ : Optional[Any] = 16 return intro_sort(A_ , 0 , len(A_ ) , A_ , A_ ) def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ , A_ , A_ ): while end - start > size_threshold: if max_depth == 0: return heap_sort(A_ ) max_depth -= 1 lowerCAmelCase__ : List[str] = median_of_a(A_ , A_ , start + ((end - start) // 2) + 1 , end - 1 ) lowerCAmelCase__ : Union[str, Any] = partition(A_ , A_ , A_ , A_ ) intro_sort(A_ , A_ , A_ , A_ , A_ ) lowerCAmelCase__ : Optional[int] = p return insertion_sort(A_ , A_ , A_ ) if __name__ == "__main__": import doctest doctest.testmod() __UpperCamelCase : Optional[Any] = input('''Enter numbers separated by a comma : ''').strip() __UpperCamelCase : Tuple = [float(item) for item in user_input.split(''',''')] print(sort(unsorted))
74
0
import argparse from collections import defaultdict def a__ ( UpperCAmelCase : int , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Optional[int] , UpperCAmelCase : List[Any] , UpperCAmelCase : Dict ) -> str: UpperCAmelCase : Any = f'''{file}_{class_name}_{test_name}''' done_test[_id] += 1 with open(UpperCAmelCase , '''r''' ) as f: UpperCAmelCase : Dict = f.readlines() UpperCAmelCase : Optional[int] = f'''class {class_name}(''' UpperCAmelCase : Optional[int] = f'''{4 * " "}def {test_name}(''' UpperCAmelCase : Dict = f'''{8 * " "}{correct_line.split()[0]}''' UpperCAmelCase : Dict = f'''{16 * " "}{correct_line.split()[0]}''' UpperCAmelCase : Any = False UpperCAmelCase : Any = False UpperCAmelCase : List[str] = False UpperCAmelCase : List[Any] = False UpperCAmelCase : Dict = 0 UpperCAmelCase : Tuple = 0 UpperCAmelCase : List[str] = [] for line in lines: if line.startswith(UpperCAmelCase ): UpperCAmelCase : List[str] = True elif in_class and line.startswith(UpperCAmelCase ): UpperCAmelCase : Tuple = True elif in_class and in_func and (line.startswith(UpperCAmelCase ) or line.startswith(UpperCAmelCase )): UpperCAmelCase : Any = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: UpperCAmelCase : List[str] = True if in_class and in_func and in_line: if ")" not in line: continue else: UpperCAmelCase : Dict = True if in_class and in_func and in_line and insert_line: new_lines.append(f'''{spaces * " "}{correct_line}''' ) UpperCAmelCase : Union[str, Any] = False else: new_lines.append(UpperCAmelCase ) with open(UpperCAmelCase , '''w''' ) as f: for line in new_lines: f.write(UpperCAmelCase ) def a__ ( UpperCAmelCase : Dict , UpperCAmelCase : List[str]=None ) -> str: if fail is not None: with open(UpperCAmelCase , '''r''' ) as f: UpperCAmelCase : List[Any] = {l.strip() for l in f.readlines()} else: UpperCAmelCase : List[str] = None with open(UpperCAmelCase , '''r''' ) as f: UpperCAmelCase : Optional[int] = f.readlines() UpperCAmelCase : Tuple = defaultdict(UpperCAmelCase ) for line in correct_lines: UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Optional[Any] = line.split(''';''' ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) if __name__ == "__main__": _lowerCamelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument("--correct_filename", help="filename of tests with expected result") parser.add_argument("--fail_filename", help="filename of test failures", type=str, default=None) _lowerCamelCase : int = parser.parse_args() main(args.correct_filename, args.fail_filename)
336
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class __UpperCAmelCase ( ctypes.Structure ): # _fields is a specific attr expected by ctypes UpperCamelCase = [("""size""", ctypes.c_int), ("""visible""", ctypes.c_byte)] def a__ ( ) -> Dict: if os.name == "nt": UpperCAmelCase : List[str] = CursorInfo() UpperCAmelCase : List[Any] = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(UpperCAmelCase , ctypes.byref(UpperCAmelCase ) ) UpperCAmelCase : Dict = False ctypes.windll.kernelaa.SetConsoleCursorInfo(UpperCAmelCase , ctypes.byref(UpperCAmelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def a__ ( ) -> Optional[int]: if os.name == "nt": UpperCAmelCase : int = CursorInfo() UpperCAmelCase : int = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(UpperCAmelCase , ctypes.byref(UpperCAmelCase ) ) UpperCAmelCase : Any = True ctypes.windll.kernelaa.SetConsoleCursorInfo(UpperCAmelCase , ctypes.byref(UpperCAmelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def a__ ( ) -> Optional[Any]: try: hide_cursor() yield finally: show_cursor()
336
1
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. __UpperCAmelCase = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''} @is_pipeline_test class lowerCAmelCase_ ( unittest.TestCase ): UpperCAmelCase__ : Dict = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase__ : List[str] = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: UpperCAmelCase__ : Optional[Any] = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: UpperCAmelCase__ : Dict = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def snake_case_ ( self ) -> int: UpperCamelCase : List[str] = pipeline( task='text-classification', model='hf-internal-testing/tiny-random-distilbert', framework='pt' ) UpperCamelCase : str = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'LABEL_0', 'score': 0.5_04}] ) UpperCamelCase : Dict = text_classifier('This is great !', top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}] ) UpperCamelCase : List[Any] = text_classifier(['This is great !', 'This is bad'], top_k=2 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), [ [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}], [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}], ], ) UpperCamelCase : List[Any] = text_classifier('This is great !', top_k=1 ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'LABEL_0', 'score': 0.5_04}] ) # Legacy behavior UpperCamelCase : str = text_classifier('This is great !', return_all_scores=SCREAMING_SNAKE_CASE_ ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'LABEL_0', 'score': 0.5_04}] ) UpperCamelCase : Tuple = text_classifier('This is great !', return_all_scores=SCREAMING_SNAKE_CASE_ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), [[{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}]] ) UpperCamelCase : List[Any] = text_classifier(['This is great !', 'Something else'], return_all_scores=SCREAMING_SNAKE_CASE_ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), [ [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}], [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}], ], ) UpperCamelCase : Optional[int] = text_classifier(['This is great !', 'Something else'], return_all_scores=SCREAMING_SNAKE_CASE_ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), [ {'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_0', 'score': 0.5_04}, ], ) @require_torch def snake_case_ ( self ) -> Optional[Any]: import torch UpperCamelCase : str = pipeline( task='text-classification', model='hf-internal-testing/tiny-random-distilbert', framework='pt', device=torch.device('cpu' ), ) UpperCamelCase : List[Any] = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'LABEL_0', 'score': 0.5_04}] ) @require_tf def snake_case_ ( self ) -> Dict: UpperCamelCase : List[Any] = pipeline( task='text-classification', model='hf-internal-testing/tiny-random-distilbert', framework='tf' ) UpperCamelCase : str = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'LABEL_0', 'score': 0.5_04}] ) @slow @require_torch def snake_case_ ( self ) -> int: UpperCamelCase : str = pipeline('text-classification' ) UpperCamelCase : str = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'POSITIVE', 'score': 1.0}] ) UpperCamelCase : List[str] = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'NEGATIVE', 'score': 1.0}] ) UpperCamelCase : int = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'POSITIVE', 'score': 0.9_88}] ) @slow @require_tf def snake_case_ ( self ) -> Tuple: UpperCamelCase : int = pipeline('text-classification', framework='tf' ) UpperCamelCase : Tuple = text_classifier('This is great !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'POSITIVE', 'score': 1.0}] ) UpperCamelCase : Union[str, Any] = text_classifier('This is bad !' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'NEGATIVE', 'score': 1.0}] ) UpperCamelCase : int = text_classifier('Birds are a type of animal' ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': 'POSITIVE', 'score': 0.9_88}] ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase : str = TextClassificationPipeline(model=SCREAMING_SNAKE_CASE_, tokenizer=SCREAMING_SNAKE_CASE_ ) return text_classifier, ["HuggingFace is in", "This is another test"] def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Any: UpperCamelCase : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 UpperCamelCase : List[str] = 'HuggingFace is in' UpperCamelCase : Tuple = text_classifier(SCREAMING_SNAKE_CASE_ ) self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': ANY(SCREAMING_SNAKE_CASE_ ), 'score': ANY(SCREAMING_SNAKE_CASE_ )}] ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) UpperCamelCase : List[Any] = ['HuggingFace is in ', 'Paris is in France'] UpperCamelCase : List[str] = text_classifier(SCREAMING_SNAKE_CASE_ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': ANY(SCREAMING_SNAKE_CASE_ ), 'score': ANY(SCREAMING_SNAKE_CASE_ )}, {'label': ANY(SCREAMING_SNAKE_CASE_ ), 'score': ANY(SCREAMING_SNAKE_CASE_ )}], ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() ) self.assertTrue(outputs[1]['label'] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format UpperCamelCase : Optional[int] = text_classifier(SCREAMING_SNAKE_CASE_, top_k=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), [[{'label': ANY(SCREAMING_SNAKE_CASE_ ), 'score': ANY(SCREAMING_SNAKE_CASE_ )}] * N, [{'label': ANY(SCREAMING_SNAKE_CASE_ ), 'score': ANY(SCREAMING_SNAKE_CASE_ )}] * N], ) UpperCamelCase : str = {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'} UpperCamelCase : Union[str, Any] = text_classifier(SCREAMING_SNAKE_CASE_ ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), {'label': ANY(SCREAMING_SNAKE_CASE_ ), 'score': ANY(SCREAMING_SNAKE_CASE_ )}, ) self.assertTrue(outputs['label'] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. UpperCamelCase : List[str] = [['HuggingFace is in ', 'Paris is in France']] with self.assertRaises(SCREAMING_SNAKE_CASE_ ): text_classifier(SCREAMING_SNAKE_CASE_ ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility UpperCamelCase : List[str] = text_classifier([[['HuggingFace is in ', 'Paris is in France']]] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ), [{'label': ANY(SCREAMING_SNAKE_CASE_ ), 'score': ANY(SCREAMING_SNAKE_CASE_ )}], ) self.assertTrue(outputs[0]['label'] in model.config.idalabel.values() )
354
import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def UpperCamelCase ( snake_case__ : List[Any] , snake_case__ : Union[str, Any] , snake_case__ : Tuple , snake_case__ : Union[str, Any] , snake_case__ : List[Any] ) -> Tuple: # load base model UpperCamelCase : Tuple = StableDiffusionPipeline.from_pretrained(snake_case__ , torch_dtype=torch.floataa ) # load LoRA weight from .safetensors UpperCamelCase : Union[str, Any] = load_file(snake_case__ ) UpperCamelCase : int = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: UpperCamelCase : Optional[Any] = key.split('.' )[0].split(LORA_PREFIX_TEXT_ENCODER + '_' )[-1].split('_' ) UpperCamelCase : Optional[Any] = pipeline.text_encoder else: UpperCamelCase : Tuple = key.split('.' )[0].split(LORA_PREFIX_UNET + '_' )[-1].split('_' ) UpperCamelCase : List[str] = pipeline.unet # find the target layer UpperCamelCase : Optional[Any] = layer_infos.pop(0 ) while len(snake_case__ ) > -1: try: UpperCamelCase : Dict = curr_layer.__getattr__(snake_case__ ) if len(snake_case__ ) > 0: UpperCamelCase : Dict = layer_infos.pop(0 ) elif len(snake_case__ ) == 0: break except Exception: if len(snake_case__ ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: UpperCamelCase : Tuple = layer_infos.pop(0 ) UpperCamelCase : List[Any] = [] if "lora_down" in key: pair_keys.append(key.replace('lora_down' , 'lora_up' ) ) pair_keys.append(snake_case__ ) else: pair_keys.append(snake_case__ ) pair_keys.append(key.replace('lora_up' , 'lora_down' ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: UpperCamelCase : Dict = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) UpperCamelCase : Union[str, Any] = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(snake_case__ , snake_case__ ).unsqueeze(2 ).unsqueeze(3 ) else: UpperCamelCase : Dict = state_dict[pair_keys[0]].to(torch.floataa ) UpperCamelCase : List[Any] = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(snake_case__ , snake_case__ ) # update visited list for item in pair_keys: visited.append(snake_case__ ) return pipeline if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( '''--base_model_path''', default=None, type=str, required=True, help='''Path to the base model in diffusers format.''' ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--lora_prefix_unet''', default='''lora_unet''', type=str, help='''The prefix of UNet weight in safetensors''' ) parser.add_argument( '''--lora_prefix_text_encoder''', default='''lora_te''', type=str, help='''The prefix of text encoder weight in safetensors''', ) parser.add_argument('''--alpha''', default=0.75, type=float, help='''The merging ratio in W = W0 + alpha * deltaW''') parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''' ) parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') __UpperCAmelCase = parser.parse_args() __UpperCAmelCase = args.base_model_path __UpperCAmelCase = args.checkpoint_path __UpperCAmelCase = args.dump_path __UpperCAmelCase = args.lora_prefix_unet __UpperCAmelCase = args.lora_prefix_text_encoder __UpperCAmelCase = args.alpha __UpperCAmelCase = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) __UpperCAmelCase = pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
103
0