code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A : Any = { 'configuration_mobilevit': ['MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileViTConfig', 'MobileViTOnnxConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[Any] = ['MobileViTFeatureExtractor'] A : Any = ['MobileViTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[int] = [ 'MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MobileViTForImageClassification', 'MobileViTForSemanticSegmentation', 'MobileViTModel', 'MobileViTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[Any] = [ '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 A : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
636
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowerCamelCase : Tuple = logging.get_logger(__name__) __lowerCamelCase : Optional[Any] = {'vocab_file': 'vocab.json'} __lowerCamelCase : Optional[Any] = { 'vocab_file': { 'mgp-str': 'https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json', } } __lowerCamelCase : List[Any] = {'mgp-str': 27} class UpperCAmelCase ( lowercase_): """simple docstring""" lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : List[str]="[GO]" , UpperCamelCase__ : Optional[Any]="[GO]" , UpperCamelCase__ : int="[s]" , UpperCamelCase__ : Dict="[GO]" , **UpperCamelCase__ : List[Any] ) -> List[str]: super().__init__( unk_token=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , **UpperCamelCase__ , ) with open(UpperCamelCase__ , encoding='''utf-8''' ) as vocab_handle: _UpperCamelCase =json.load(UpperCamelCase__ ) _UpperCamelCase ={v: k for k, v in self.vocab.items()} @property def UpperCamelCase__ ( self : Union[str, Any] ) -> Tuple: return len(self.vocab ) def UpperCamelCase__ ( self : int ) -> Union[str, Any]: return dict(self.vocab , **self.added_tokens_encoder ) def UpperCamelCase__ ( self : Optional[int] , UpperCamelCase__ : str ) -> List[str]: _UpperCamelCase =[] for s in text: char_tokens.extend(UpperCamelCase__ ) return char_tokens def UpperCamelCase__ ( self : List[Any] , UpperCamelCase__ : Optional[int] ) -> Dict: return self.vocab.get(UpperCamelCase__ , self.vocab.get(self.unk_token ) ) def UpperCamelCase__ ( self : Optional[Any] , UpperCamelCase__ : Optional[int] ) -> Any: return self.decoder.get(UpperCamelCase__ ) def UpperCamelCase__ ( self : str , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(UpperCamelCase__ ): logger.error('''Vocabulary path ({}) should be a directory'''.format(UpperCamelCase__ ) ) return _UpperCamelCase =os.path.join( UpperCamelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) with open(UpperCamelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=UpperCamelCase__ , ensure_ascii=UpperCamelCase__ ) + '''\n''' ) return (vocab_file,)
404
0
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES 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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=13 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=[10, 20, 30, 40] , UpperCAmelCase_ : List[Any]=[2, 2, 3, 2] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : int=["stage2", "stage3", "stage4"] , UpperCAmelCase_ : Optional[int]=[2, 3, 4] , UpperCAmelCase_ : List[str]=None , ) ->Union[str, Any]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = num_stages snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = out_features snake_case_ = out_indices snake_case_ = scope def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = ConvNextVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = ConvNextVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __lowercase: Union[str, Any] = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Optional[Any] = False __lowercase: Any = False __lowercase: Union[str, Any] = False __lowercase: Dict = False def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = True if model_class.__name__ in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ]: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = False snake_case_ = True if ( model_class.__name__ in [*get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ )] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ): snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ConvNextVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> str: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(UpperCAmelCase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = preprocessor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
2
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
1
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' __UpperCamelCase = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __UpperCamelCase = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = TextaTextGenerationPipeline(model=lowercase_ , tokenizer=lowercase_) return generator, ["Something to write", "Something else"] def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : int , lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = generator('''Something there''') self.assertEqual(lowercase_ , [{'''generated_text''': ANY(lowercase_)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['''generated_text'''].startswith('''Something there''')) SCREAMING_SNAKE_CASE_ : Tuple = generator(['''This is great !''', '''Something else'''] , num_return_sequences=2 , do_sample=lowercase_) self.assertEqual( lowercase_ , [ [{'''generated_text''': ANY(lowercase_)}, {'''generated_text''': ANY(lowercase_)}], [{'''generated_text''': ANY(lowercase_)}, {'''generated_text''': ANY(lowercase_)}], ] , ) SCREAMING_SNAKE_CASE_ : Any = generator( ['''This is great !''', '''Something else'''] , num_return_sequences=2 , batch_size=2 , do_sample=lowercase_) self.assertEqual( lowercase_ , [ [{'''generated_text''': ANY(lowercase_)}, {'''generated_text''': ANY(lowercase_)}], [{'''generated_text''': ANY(lowercase_)}, {'''generated_text''': ANY(lowercase_)}], ] , ) with self.assertRaises(lowercase_): generator(4) @require_torch def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = pipeline('''text2text-generation''' , model='''patrickvonplaten/t5-tiny-random''' , framework='''pt''') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE_ : Union[str, Any] = generator('''Something there''' , do_sample=lowercase_) self.assertEqual(lowercase_ , [{'''generated_text''': ''''''}]) SCREAMING_SNAKE_CASE_ : Optional[Any] = 3 SCREAMING_SNAKE_CASE_ : List[Any] = generator( '''Something there''' , num_return_sequences=lowercase_ , num_beams=lowercase_ , ) SCREAMING_SNAKE_CASE_ : Any = [ {'''generated_text''': '''Beide Beide Beide Beide Beide Beide Beide Beide Beide'''}, {'''generated_text''': '''Beide Beide Beide Beide Beide Beide Beide Beide'''}, {'''generated_text''': ''''''}, ] self.assertEqual(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = generator('''This is a test''' , do_sample=lowercase_ , num_return_sequences=2 , return_tensors=lowercase_) self.assertEqual( lowercase_ , [ {'''generated_token_ids''': ANY(torch.Tensor)}, {'''generated_token_ids''': ANY(torch.Tensor)}, ] , ) SCREAMING_SNAKE_CASE_ : int = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE_ : List[Any] = '''<pad>''' SCREAMING_SNAKE_CASE_ : Dict = generator( ['''This is a test''', '''This is a second test'''] , do_sample=lowercase_ , num_return_sequences=2 , batch_size=2 , return_tensors=lowercase_ , ) self.assertEqual( lowercase_ , [ [ {'''generated_token_ids''': ANY(torch.Tensor)}, {'''generated_token_ids''': ANY(torch.Tensor)}, ], [ {'''generated_token_ids''': ANY(torch.Tensor)}, {'''generated_token_ids''': ANY(torch.Tensor)}, ], ] , ) @require_tf def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = pipeline('''text2text-generation''' , model='''patrickvonplaten/t5-tiny-random''' , framework='''tf''') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE_ : int = generator('''Something there''' , do_sample=lowercase_) self.assertEqual(lowercase_ , [{'''generated_text''': ''''''}])
512
"""simple docstring""" from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = 42 __UpperCamelCase = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
512
1
'''simple docstring''' import random def UpperCAmelCase ( lowerCamelCase_ :Any , lowerCamelCase_ :List[Any] , lowerCamelCase_ :Dict ): '''simple docstring''' snake_case_ : int = a[left_index] snake_case_ : Optional[Any] = left_index + 1 for j in range(left_index + 1 , lowerCamelCase_ ): if a[j] < pivot: snake_case_ , snake_case_ : int = a[i], a[j] i += 1 snake_case_ , snake_case_ : Optional[int] = a[i - 1], a[left_index] return i - 1 def UpperCAmelCase ( lowerCamelCase_ :List[Any] , lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :List[Any] ): '''simple docstring''' if left < right: snake_case_ : List[Any] = random.randint(lowerCamelCase_ , right - 1 ) snake_case_ , snake_case_ : int = ( a[left], a[pivot], ) # switches the pivot with the left most bound snake_case_ : List[str] = partition(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) quick_sort_random( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCamelCase_ , pivot_index + 1 , lowerCamelCase_ ) # recursive quicksort to the right of the pivot point def UpperCAmelCase ( ): '''simple docstring''' snake_case_ : Tuple = input("""Enter numbers separated by a comma:\n""" ).strip() snake_case_ : List[str] = [int(lowerCamelCase_ ) for item in user_input.split(""",""" )] quick_sort_random(lowerCamelCase_ , 0 , len(lowerCamelCase_ ) ) print(lowerCamelCase_ ) if __name__ == "__main__": main()
267
'''simple docstring''' import math def UpperCAmelCase ( lowerCamelCase_ :list , lowerCamelCase_ :int ): '''simple docstring''' snake_case_ : Union[str, Any] = len(lowerCamelCase_ ) snake_case_ : List[Any] = int(math.floor(math.sqrt(lowerCamelCase_ ) ) ) snake_case_ : str = 0 while arr[min(lowerCamelCase_ , lowerCamelCase_ ) - 1] < x: snake_case_ : Any = step step += int(math.floor(math.sqrt(lowerCamelCase_ ) ) ) if prev >= n: return -1 while arr[prev] < x: snake_case_ : Optional[Any] = prev + 1 if prev == min(lowerCamelCase_ , lowerCamelCase_ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": __A : Any = input('Enter numbers separated by a comma:\n').strip() __A : Union[str, Any] = [int(item) for item in user_input.split(',')] __A : Optional[int] = int(input('Enter the number to be searched:\n')) __A : int = jump_search(arr, x) if res == -1: print('Number not found!') else: print(F'Number {x} is at index {res}')
267
1
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch _UpperCamelCase = random.Random() def _a ( _snake_case , _snake_case=1.0 , _snake_case=None , _snake_case=None ): """simple docstring""" if rng is None: UpperCAmelCase = global_rng UpperCAmelCase = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCamelCase__ ( unittest.TestCase ): def __init__( self ,A ,A=7 ,A=400 ,A=2_000 ,A=10 ,A=160 ,A=8 ,A=0.0 ,A=4_000 ,A=False ,A=True ,): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = min_seq_length UpperCAmelCase = max_seq_length UpperCAmelCase = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCAmelCase = padding_value UpperCAmelCase = sampling_rate UpperCAmelCase = return_attention_mask UpperCAmelCase = do_normalize UpperCAmelCase = feature_size UpperCAmelCase = chunk_length UpperCAmelCase = hop_length def _UpperCamelCase ( self ): return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _UpperCamelCase ( self ,A=False ,A=False ): def _flatten(A ): return list(itertools.chain(*SCREAMING_SNAKE_CASE__ ) ) if equal_length: UpperCAmelCase = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size UpperCAmelCase = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length ,self.max_seq_length ,self.seq_length_diff ) ] if numpify: UpperCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCamelCase__ ( snake_case , unittest.TestCase ): SCREAMING_SNAKE_CASE = WhisperFeatureExtractor if is_speech_available() else None def _UpperCamelCase ( self ): UpperCAmelCase = WhisperFeatureExtractionTester(self ) def _UpperCamelCase ( self ): UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase = feat_extract_first.save_pretrained(SCREAMING_SNAKE_CASE__ )[0] check_json_file_has_correct_format(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = self.feature_extraction_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = feat_extract_first.to_dict() UpperCAmelCase = feat_extract_second.to_dict() UpperCAmelCase = feat_extract_first.mel_filters UpperCAmelCase = feat_extract_second.mel_filters self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase = os.path.join(SCREAMING_SNAKE_CASE__ ,"""feat_extract.json""" ) feat_extract_first.to_json_file(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = self.feature_extraction_class.from_json_file(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = feat_extract_first.to_dict() UpperCAmelCase = feat_extract_second.to_dict() UpperCAmelCase = feat_extract_first.mel_filters UpperCAmelCase = feat_extract_second.mel_filters self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): # Tests that all call wrap to encode_plus and batch_encode_plus UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 UpperCAmelCase = [floats_list((1, x) )[0] for x in range(800 ,1_400 ,200 )] UpperCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE__ ) for speech_input in speech_inputs] # Test feature size UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,padding="""max_length""" ,return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input UpperCAmelCase = feature_extractor(speech_inputs[0] ,return_tensors="""np""" ).input_features UpperCAmelCase = feature_extractor(np_speech_inputs[0] ,return_tensors="""np""" ).input_features self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,atol=1e-3 ) ) # Test batched UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,atol=1e-3 ) ) # Test 2-D numpy arrays are batched. UpperCAmelCase = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCAmelCase = np.asarray(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,atol=1e-3 ) ) # Test truncation required UpperCAmelCase = [floats_list((1, x) )[0] for x in range(200 ,(feature_extractor.n_samples + 500) ,200 )] UpperCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE__ ) for speech_input in speech_inputs] UpperCAmelCase = [x[: feature_extractor.n_samples] for x in speech_inputs] UpperCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE__ ) for speech_input in speech_inputs_truncated] UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,atol=1e-3 ) ) def _UpperCamelCase ( self ): import torch UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase = np.random.rand(100 ,32 ).astype(np.floataa ) UpperCAmelCase = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: UpperCAmelCase = feature_extractor.pad([{"""input_features""": inputs}] ,return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) UpperCAmelCase = feature_extractor.pad([{"""input_features""": inputs}] ,return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def _UpperCamelCase ( self ,A ): UpperCAmelCase = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" ,"""clean""" ,split="""validation""" ) # automatic decoding with librispeech UpperCAmelCase = ds.sort("""id""" ).select(range(SCREAMING_SNAKE_CASE__ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def _UpperCamelCase ( self ): # fmt: off UpperCAmelCase = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on UpperCAmelCase = self._load_datasamples(1 ) UpperCAmelCase = WhisperFeatureExtractor() UpperCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape ,(1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] ,SCREAMING_SNAKE_CASE__ ,atol=1e-4 ) ) def _UpperCamelCase ( self ): UpperCAmelCase = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) UpperCAmelCase = self._load_datasamples(1 )[0] UpperCAmelCase = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue UpperCAmelCase = feat_extract.zero_mean_unit_var_norm([audio] ,attention_mask=SCREAMING_SNAKE_CASE__ )[0] self.assertTrue(np.all(np.mean(SCREAMING_SNAKE_CASE__ ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(SCREAMING_SNAKE_CASE__ ) - 1 ) < 1e-3 ) )
341
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="""%(message)s""") def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> np.ndarray: return input_array.reshape((input_array.size, 1) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : str = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : int = features[:, labels == i] __lowerCamelCase : Optional[int] = data.mean(1 ) # Centralize the data of class i __lowerCamelCase : int = data - column_reshape(lowerCamelCase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowerCamelCase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : Union[str, Any] = np.dot(lowerCamelCase__ , centered_data.T ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: __lowerCamelCase : Optional[Any] = features.mean(1 ) __lowerCamelCase : Union[str, Any] = np.nan for i in range(lowerCamelCase__ ): __lowerCamelCase : Optional[Any] = features[:, labels == i] __lowerCamelCase : Union[str, Any] = data.shape[1] __lowerCamelCase : Union[str, Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) __lowerCamelCase : List[str] = device_data * np.dot( column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ ) , (column_reshape(lowerCamelCase__ ) - column_reshape(lowerCamelCase__ )).T , ) return covariance_sum / features.shape[1] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: # Check if the features have been loaded if features.any(): __lowerCamelCase : Tuple = features.mean(1 ) # Center the dataset __lowerCamelCase : Any = features - np.reshape(lowerCamelCase__ , (data_mean.size, 1) ) __lowerCamelCase : Optional[int] = np.dot(lowerCamelCase__ , centered_data.T ) / features.shape[1] __lowerCamelCase , __lowerCamelCase : List[Any] = np.linalg.eigh(lowerCamelCase__ ) # Take all the columns in the reverse order (-1), and then takes only the first __lowerCamelCase : Dict = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space __lowerCamelCase : int = np.dot(filtered_eigenvectors.T , lowerCamelCase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> np.ndarray: assert classes > dimensions # Check if features have been already loaded if features.any: __lowerCamelCase , __lowerCamelCase : Dict = eigh( covariance_between_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , covariance_within_classes(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) , ) __lowerCamelCase : Union[str, Any] = eigenvectors[:, ::-1][:, :dimensions] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = np.linalg.svd(lowerCamelCase__ ) __lowerCamelCase : int = svd_matrix[:, 0:dimensions] __lowerCamelCase : Optional[int] = np.dot(filtered_svd_matrix.T , lowerCamelCase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowerCamelCase__ ) logging.error('Dataset empty' ) raise AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: # Create dummy dataset with 2 classes and 3 features __lowerCamelCase : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) __lowerCamelCase : Optional[int] = np.array([0, 0, 0, 1, 1] ) __lowerCamelCase : Optional[Any] = 2 __lowerCamelCase : Tuple = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : int = linear_discriminant_analysis( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if isinstance(lowerCamelCase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def SCREAMING_SNAKE_CASE__ ( ) -> None: __lowerCamelCase : Dict = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) __lowerCamelCase : Dict = 2 __lowerCamelCase : int = np.array([[6.9282_0323, 8.6602_5404, 10.3923_0485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowerCamelCase__ ) as error_info: __lowerCamelCase : Optional[Any] = principal_component_analysis(lowerCamelCase__ , lowerCamelCase__ ) if not np.allclose(lowerCamelCase__ , lowerCamelCase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
652
0
'''simple docstring''' import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class A : def __init__( self , snake_case_ , snake_case_=1_3 , snake_case_=3_0 , snake_case_=2 , snake_case_=3 , snake_case_=True , snake_case_=True , snake_case_=3_2 , snake_case_=5 , snake_case_=4 , snake_case_=3_7 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=1_0 , snake_case_=0.02 , snake_case_=3 , snake_case_=None , snake_case_=2 , ) -> Dict: _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 = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = type_sequence_label_size _a = initializer_range _a = scope _a = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) _a = (image_size // patch_size) ** 2 _a = num_patches + 2 def __lowerCAmelCase ( self ) -> List[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.type_sequence_label_size ) _a = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self ) -> Optional[int]: return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=snake_case_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowerCAmelCase ( self , snake_case_ , snake_case_ , snake_case_ ) -> Optional[int]: _a = DeiTModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() _a = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: _a = DeiTForMaskedImageModeling(config=snake_case_ ) model.to(snake_case_ ) model.eval() _a = model(snake_case_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images _a = 1 _a = DeiTForMaskedImageModeling(snake_case_ ) model.to(snake_case_ ) model.eval() _a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _a = model(snake_case_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowerCAmelCase ( self , snake_case_ , snake_case_ , snake_case_ ) -> Any: _a = self.type_sequence_label_size _a = DeiTForImageClassification(snake_case_ ) model.to(snake_case_ ) model.eval() _a = model(snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _a = 1 _a = DeiTForImageClassification(snake_case_ ) model.to(snake_case_ ) model.eval() _a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _a = model(snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self ) -> Tuple: _a = self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ) = config_and_inputs _a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class A ( a , a , unittest.TestCase ): __UpperCAmelCase : List[str] = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) __UpperCAmelCase : Tuple = ( { """feature-extraction""": DeiTModel, """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) __UpperCAmelCase : Any = False __UpperCAmelCase : int = False __UpperCAmelCase : List[Any] = False def __lowerCAmelCase ( self ) -> int: _a = DeiTModelTester(self ) _a = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ , hidden_size=3_7 ) def __lowerCAmelCase ( self ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def __lowerCAmelCase ( self ) -> Optional[Any]: pass def __lowerCAmelCase ( self ) -> Any: _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a = model_class(snake_case_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case_ , nn.Linear ) ) def __lowerCAmelCase ( self ) -> int: _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a = model_class(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] , snake_case_ ) def __lowerCAmelCase ( self ) -> Optional[Any]: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def __lowerCAmelCase ( self ) -> int: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*snake_case_ ) def __lowerCAmelCase ( self ) -> Dict: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) def __lowerCAmelCase ( self , snake_case_ , snake_case_ , snake_case_=False ) -> Dict: _a = super()._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowerCAmelCase ( self ) -> Union[str, Any]: if not self.model_tester.is_training: return _a , _a = self.model_tester.prepare_config_and_inputs_for_common() _a = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(snake_case_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue _a = model_class(snake_case_ ) model.to(snake_case_ ) model.train() _a = self._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) _a = model(**snake_case_ ).loss loss.backward() def __lowerCAmelCase ( self ) -> List[Any]: _a , _a = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return _a = False _a = True for model_class in self.all_model_classes: if model_class in get_values(snake_case_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue _a = model_class(snake_case_ ) model.gradient_checkpointing_enable() model.to(snake_case_ ) model.train() _a = self._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) _a = model(**snake_case_ ).loss loss.backward() def __lowerCAmelCase ( self ) -> Optional[int]: _a , _a = self.model_tester.prepare_config_and_inputs_for_common() _a = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(snake_case_ ), *get_values(snake_case_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): _a = problem_type["title"] _a = problem_type["num_labels"] _a = model_class(snake_case_ ) model.to(snake_case_ ) model.train() _a = self._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) if problem_type["num_labels"] > 1: _a = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) _a = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=snake_case_ ) as warning_list: _a = model(**snake_case_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowerCAmelCase ( self ) -> str: for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a = DeiTModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) def _lowercase ( ): _a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class A ( unittest.TestCase ): @cached_property def __lowerCAmelCase ( self ) -> Union[str, Any]: return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self ) -> Dict: _a = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to( snake_case_ ) _a = self.default_image_processor _a = prepare_img() _a = image_processor(images=snake_case_ , return_tensors="pt" ).to(snake_case_ ) # forward pass with torch.no_grad(): _a = model(**snake_case_ ) # verify the logits _a = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , snake_case_ ) _a = torch.tensor([-1.0_266, 0.1_912, -1.2_861] ).to(snake_case_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case_ , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowerCAmelCase ( self ) -> Any: _a = DeiTModel.from_pretrained( "facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" ) _a = self.default_image_processor _a = prepare_img() _a = image_processor(images=snake_case_ , return_tensors="pt" ) _a = inputs.pixel_values.to(snake_case_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): _a = model(snake_case_ )
691
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings __snake_case : Optional[int] = R"\n [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and\n can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.\n\n Args:\n title_sep (`str`, *optional*, defaults to `\" / \"`):\n Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].\n doc_sep (`str`, *optional*, defaults to `\" // \"`):\n Separator inserted between the text of the retrieved document and the original input when calling\n [`RagRetriever`].\n n_docs (`int`, *optional*, defaults to 5):\n Number of documents to retrieve.\n max_combined_length (`int`, *optional*, defaults to 300):\n Max length of contextualized input returned by [`~RagRetriever.__call__`].\n retrieval_vector_size (`int`, *optional*, defaults to 768):\n Dimensionality of the document embeddings indexed by [`RagRetriever`].\n retrieval_batch_size (`int`, *optional*, defaults to 8):\n Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated\n [`RagRetriever`].\n dataset (`str`, *optional*, defaults to `\"wiki_dpr\"`):\n A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids\n using `datasets.list_datasets()`).\n dataset_split (`str`, *optional*, defaults to `\"train\"`)\n Which split of the `dataset` to load.\n index_name (`str`, *optional*, defaults to `\"compressed\"`)\n The index name of the index associated with the `dataset`. One can choose between `\"legacy\"`, `\"exact\"` and\n `\"compressed\"`.\n index_path (`str`, *optional*)\n The path to the serialized faiss index on disk.\n passages_path (`str`, *optional*):\n A path to text passages compatible with the faiss index. Required if using\n [`~models.rag.retrieval_rag.LegacyIndex`]\n use_dummy_dataset (`bool`, *optional*, defaults to `False`)\n Whether to load a \"dummy\" variant of the dataset specified by `dataset`.\n label_smoothing (`float`, *optional*, defaults to 0.0):\n Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing\n in the loss calculation. If set to 0, no label smoothing is performed.\n do_marginalize (`bool`, *optional*, defaults to `False`):\n If `True`, the logits are marginalized over all documents by making use of\n `torch.nn.functional.log_softmax`.\n reduce_loss (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.\n do_deduplication (`bool`, *optional*, defaults to `True`):\n Whether or not to deduplicate the generations from different context documents for a given input. Has to be\n set to `False` if used while training with distributed backend.\n exclude_bos_score (`bool`, *optional*, defaults to `False`):\n Whether or not to disregard the BOS token when computing the loss.\n output_retrieved(`bool`, *optional*, defaults to `False`):\n If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and\n `context_attention_mask` are returned. See returned tensors for more detail.\n use_cache (`bool`, *optional*, defaults to `True`):\n Whether or not the model should return the last key/values attentions (not used by all models).\n forced_eos_token_id (`int`, *optional*):\n The id of the token to force as the last generated token when `max_length` is reached. Usually set to\n `eos_token_id`.\n" @add_start_docstrings(a ) class A ( a ): __UpperCAmelCase : Dict = """rag""" __UpperCAmelCase : Dict = True def __init__( self , snake_case_=None , snake_case_=True , snake_case_=None , snake_case_=None , snake_case_=None , snake_case_=None , snake_case_=None , snake_case_=" / " , snake_case_=" // " , snake_case_=5 , snake_case_=3_0_0 , snake_case_=7_6_8 , snake_case_=8 , snake_case_="wiki_dpr" , snake_case_="train" , snake_case_="compressed" , snake_case_=None , snake_case_=None , snake_case_=False , snake_case_=False , snake_case_=0.0 , snake_case_=True , snake_case_=False , snake_case_=False , snake_case_=False , snake_case_=True , snake_case_=None , **snake_case_ , ) -> Optional[Any]: super().__init__( bos_token_id=snake_case_ , pad_token_id=snake_case_ , eos_token_id=snake_case_ , decoder_start_token_id=snake_case_ , forced_eos_token_id=snake_case_ , is_encoder_decoder=snake_case_ , prefix=snake_case_ , vocab_size=snake_case_ , **snake_case_ , ) assert ( "question_encoder" in kwargs and "generator" in kwargs ), "Config has to be initialized with question_encoder and generator config" _a = kwargs.pop("question_encoder" ) _a = question_encoder_config.pop("model_type" ) _a = kwargs.pop("generator" ) _a = decoder_config.pop("model_type" ) from ..auto.configuration_auto import AutoConfig _a = AutoConfig.for_model(snake_case_ , **snake_case_ ) _a = AutoConfig.for_model(snake_case_ , **snake_case_ ) _a = reduce_loss _a = label_smoothing _a = exclude_bos_score _a = do_marginalize _a = title_sep _a = doc_sep _a = n_docs _a = max_combined_length _a = dataset _a = dataset_split _a = index_name _a = retrieval_vector_size _a = retrieval_batch_size _a = passages_path _a = index_path _a = use_dummy_dataset _a = output_retrieved _a = do_deduplication _a = use_cache if self.forced_eos_token_id is None: _a = getattr(self.generator , "forced_eos_token_id" , snake_case_ ) @classmethod def __lowerCAmelCase ( cls , snake_case_ , snake_case_ , **snake_case_ ) -> PretrainedConfig: return cls(question_encoder=question_encoder_config.to_dict() , generator=generator_config.to_dict() , **snake_case_ ) def __lowerCAmelCase ( self ) -> Optional[int]: _a = copy.deepcopy(self.__dict__ ) _a = self.question_encoder.to_dict() _a = self.generator.to_dict() _a = self.__class__.model_type return output
691
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE_ : Optional[int] = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ : List[str] = [ '''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BioGptForCausalLM''', '''BioGptForTokenClassification''', '''BioGptForSequenceClassification''', '''BioGptModel''', '''BioGptPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_ : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
375
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ : Union[str, Any] = { '''RWKV/rwkv-4-169m-pile''': '''https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-430m-pile''': '''https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-1b5-pile''': '''https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json''', '''RWKV/rwkv-4-3b-pile''': '''https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-7b-pile''': '''https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-14b-pile''': '''https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json''', '''RWKV/rwkv-raven-1b5''': '''https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json''', '''RWKV/rwkv-raven-3b''': '''https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json''', '''RWKV/rwkv-raven-7b''': '''https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json''', '''RWKV/rwkv-raven-14b''': '''https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json''', } class snake_case_ ( UpperCAmelCase_ ): '''simple docstring''' __UpperCamelCase = '''rwkv''' __UpperCamelCase = {'''max_position_embeddings''': '''context_length'''} def __init__( self : List[str] , __lowerCamelCase : Tuple=50_277 , __lowerCamelCase : List[str]=1_024 , __lowerCamelCase : List[Any]=4_096 , __lowerCamelCase : Tuple=32 , __lowerCamelCase : List[str]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Optional[Any]=1E-5 , __lowerCamelCase : Tuple=0 , __lowerCamelCase : int=0 , __lowerCamelCase : Dict=6 , __lowerCamelCase : List[Any]=False , __lowerCamelCase : Tuple=True , **__lowerCamelCase : Optional[int] , ) -> List[Any]: '''simple docstring''' __lowercase = vocab_size __lowercase = context_length __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = attention_hidden_size if attention_hidden_size is not None else hidden_size __lowercase = intermediate_size if intermediate_size is not None else 4 * hidden_size __lowercase = layer_norm_epsilon __lowercase = rescale_every __lowercase = use_cache __lowercase = bos_token_id __lowercase = eos_token_id super().__init__( tie_word_embeddings=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase )
375
1
"""simple docstring""" import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )-> str: """simple docstring""" def get_masked_lm_array(UpperCAmelCase_ ): UpperCamelCase = F"masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE" UpperCamelCase = tf.train.load_variable(_lowerCamelCase , _lowerCamelCase ) if "kernel" in name: UpperCamelCase = array.transpose() return torch.from_numpy(_lowerCamelCase ) def get_encoder_array(UpperCAmelCase_ ): UpperCamelCase = F"encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE" UpperCamelCase = tf.train.load_variable(_lowerCamelCase , _lowerCamelCase ) if "kernel" in name: UpperCamelCase = array.transpose() return torch.from_numpy(_lowerCamelCase ) def get_encoder_layer_array(UpperCAmelCase_ , UpperCAmelCase_ ): UpperCamelCase = F"encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE" UpperCamelCase = tf.train.load_variable(_lowerCamelCase , _lowerCamelCase ) if "kernel" in name: UpperCamelCase = array.transpose() return torch.from_numpy(_lowerCamelCase ) def get_encoder_attention_layer_array(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): UpperCamelCase = F"encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE" UpperCamelCase = tf.train.load_variable(_lowerCamelCase , _lowerCamelCase ) UpperCamelCase = array.reshape(_lowerCamelCase ) if "kernel" in name: UpperCamelCase = array.transpose() return torch.from_numpy(_lowerCamelCase ) print(F"Loading model based on config from {config_path}..." ) UpperCamelCase = BertConfig.from_json_file(_lowerCamelCase ) UpperCamelCase = BertForMaskedLM(_lowerCamelCase ) # Layers for layer_index in range(0 , config.num_hidden_layers ): UpperCamelCase = model.bert.encoder.layer[layer_index] # Self-attention UpperCamelCase = layer.attention.self UpperCamelCase = get_encoder_attention_layer_array( _lowerCamelCase , "_query_dense/kernel" , self_attn.query.weight.data.shape ) UpperCamelCase = get_encoder_attention_layer_array( _lowerCamelCase , "_query_dense/bias" , self_attn.query.bias.data.shape ) UpperCamelCase = get_encoder_attention_layer_array( _lowerCamelCase , "_key_dense/kernel" , self_attn.key.weight.data.shape ) UpperCamelCase = get_encoder_attention_layer_array( _lowerCamelCase , "_key_dense/bias" , self_attn.key.bias.data.shape ) UpperCamelCase = get_encoder_attention_layer_array( _lowerCamelCase , "_value_dense/kernel" , self_attn.value.weight.data.shape ) UpperCamelCase = get_encoder_attention_layer_array( _lowerCamelCase , "_value_dense/bias" , self_attn.value.bias.data.shape ) # Self-attention Output UpperCamelCase = layer.attention.output UpperCamelCase = get_encoder_attention_layer_array( _lowerCamelCase , "_output_dense/kernel" , self_output.dense.weight.data.shape ) UpperCamelCase = get_encoder_attention_layer_array( _lowerCamelCase , "_output_dense/bias" , self_output.dense.bias.data.shape ) UpperCamelCase = get_encoder_layer_array(_lowerCamelCase , "_attention_layer_norm/gamma" ) UpperCamelCase = get_encoder_layer_array(_lowerCamelCase , "_attention_layer_norm/beta" ) # Intermediate UpperCamelCase = layer.intermediate UpperCamelCase = get_encoder_layer_array(_lowerCamelCase , "_intermediate_dense/kernel" ) UpperCamelCase = get_encoder_layer_array(_lowerCamelCase , "_intermediate_dense/bias" ) # Output UpperCamelCase = layer.output UpperCamelCase = get_encoder_layer_array(_lowerCamelCase , "_output_dense/kernel" ) UpperCamelCase = get_encoder_layer_array(_lowerCamelCase , "_output_dense/bias" ) UpperCamelCase = get_encoder_layer_array(_lowerCamelCase , "_output_layer_norm/gamma" ) UpperCamelCase = get_encoder_layer_array(_lowerCamelCase , "_output_layer_norm/beta" ) # Embeddings UpperCamelCase = get_encoder_array("_position_embedding_layer/embeddings" ) UpperCamelCase = get_encoder_array("_type_embedding_layer/embeddings" ) UpperCamelCase = get_encoder_array("_embedding_norm_layer/gamma" ) UpperCamelCase = get_encoder_array("_embedding_norm_layer/beta" ) # LM Head UpperCamelCase = model.cls.predictions.transform UpperCamelCase = get_masked_lm_array("dense/kernel" ) UpperCamelCase = get_masked_lm_array("dense/bias" ) UpperCamelCase = get_masked_lm_array("layer_norm/gamma" ) UpperCamelCase = get_masked_lm_array("layer_norm/beta" ) UpperCamelCase = get_masked_lm_array("embedding_table" ) # Pooling UpperCamelCase = BertPooler(config=_lowerCamelCase ) UpperCamelCase = get_encoder_array("_pooler_layer/kernel" ) UpperCamelCase = get_encoder_array("_pooler_layer/bias" ) # Export final model model.save_pretrained(_lowerCamelCase ) # Integration test - should load without any errors ;) UpperCamelCase = BertForMaskedLM.from_pretrained(_lowerCamelCase ) print(new_model.eval() ) print("Model conversion was done sucessfully!" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( """--tf_checkpoint_path""", type=str, required=True, help="""Path to the TensorFlow Token Dropping checkpoint path.""" ) parser.add_argument( """--bert_config_file""", type=str, required=True, help="""The config json file corresponding to the BERT model. This specifies the model architecture.""", ) parser.add_argument( """--pytorch_dump_path""", type=str, required=True, help="""Path to the output PyTorch model.""", ) SCREAMING_SNAKE_CASE = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
719
"""simple docstring""" def lowerCamelCase__ ( UpperCAmelCase_ )-> list: """simple docstring""" if len(UpperCAmelCase_ ) <= 1: return [tuple(UpperCAmelCase_ )] UpperCamelCase = [] def generate(UpperCAmelCase_ , UpperCAmelCase_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , UpperCAmelCase_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even UpperCamelCase , UpperCamelCase = arr[k - 1], arr[i] else: # k is odd UpperCamelCase , UpperCamelCase = arr[k - 1], arr[0] generate(k - 1 , UpperCAmelCase_ ) generate(len(UpperCAmelCase_ ) , UpperCAmelCase_ ) return res if __name__ == "__main__": SCREAMING_SNAKE_CASE = input("""Enter numbers separated by a comma:\n""").strip() SCREAMING_SNAKE_CASE = [int(item) for item in user_input.split(""",""")] print(heaps(arr))
556
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule A = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
320
'''simple docstring''' import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class __snake_case ( a__): _lowerCAmelCase = (UnCLIPScheduler,) def UpperCAmelCase_ ( self, **A ): """simple docstring""" lowerCamelCase : Tuple = { 'num_train_timesteps': 1000, 'variance_type': 'fixed_small_log', 'clip_sample': True, 'clip_sample_range': 1.0, 'prediction_type': 'epsilon', } config.update(**A ) return config def UpperCAmelCase_ ( self ): """simple docstring""" for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=A ) def UpperCAmelCase_ ( self ): """simple docstring""" for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=A ) def UpperCAmelCase_ ( self ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=A ) def UpperCAmelCase_ ( self ): """simple docstring""" for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=A ) def UpperCAmelCase_ ( self ): """simple docstring""" for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=A ) def UpperCAmelCase_ ( self ): """simple docstring""" for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=A, prev_timestep=A ) def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : List[str] = self.scheduler_classes[0] lowerCamelCase : Tuple = self.get_scheduler_config(variance_type='fixed_small_log' ) lowerCamelCase : Dict = scheduler_class(**A ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.00_00e-10 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.054_9625 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.999_4987 ) ) < 1e-5 def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Optional[int] = self.scheduler_classes[0] lowerCamelCase : Optional[Any] = self.get_scheduler_config(variance_type='learned_range' ) lowerCamelCase : Optional[Any] = scheduler_class(**A ) lowerCamelCase : List[Any] = 0.5 assert scheduler._get_variance(1, predicted_variance=A ) - -10.171_2790 < 1e-5 assert scheduler._get_variance(487, predicted_variance=A ) - -5.799_8052 < 1e-5 assert scheduler._get_variance(999, predicted_variance=A ) - -0.001_0011 < 1e-5 def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Optional[int] = self.scheduler_classes[0] lowerCamelCase : Dict = self.get_scheduler_config() lowerCamelCase : Optional[Any] = scheduler_class(**A ) lowerCamelCase : Optional[int] = scheduler.timesteps lowerCamelCase : Optional[Any] = self.dummy_model() lowerCamelCase : int = self.dummy_sample_deter lowerCamelCase : str = torch.manual_seed(0 ) for i, t in enumerate(A ): # 1. predict noise residual lowerCamelCase : List[Any] = model(A, A ) # 2. predict previous mean of sample x_t-1 lowerCamelCase : int = scheduler.step(A, A, A, generator=A ).prev_sample lowerCamelCase : List[Any] = pred_prev_sample lowerCamelCase : Tuple = torch.sum(torch.abs(A ) ) lowerCamelCase : List[str] = torch.mean(torch.abs(A ) ) assert abs(result_sum.item() - 252.268_2495 ) < 1e-2 assert abs(result_mean.item() - 0.328_4743 ) < 1e-3 def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Optional[int] = self.scheduler_classes[0] lowerCamelCase : Union[str, Any] = self.get_scheduler_config() lowerCamelCase : Optional[int] = scheduler_class(**A ) scheduler.set_timesteps(25 ) lowerCamelCase : str = scheduler.timesteps lowerCamelCase : Optional[int] = self.dummy_model() lowerCamelCase : Tuple = self.dummy_sample_deter lowerCamelCase : int = torch.manual_seed(0 ) for i, t in enumerate(A ): # 1. predict noise residual lowerCamelCase : Union[str, Any] = model(A, A ) if i + 1 == timesteps.shape[0]: lowerCamelCase : Dict = None else: lowerCamelCase : Optional[int] = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 lowerCamelCase : Optional[int] = scheduler.step( A, A, A, prev_timestep=A, generator=A ).prev_sample lowerCamelCase : str = pred_prev_sample lowerCamelCase : Any = torch.sum(torch.abs(A ) ) lowerCamelCase : Union[str, Any] = torch.mean(torch.abs(A ) ) assert abs(result_sum.item() - 258.204_4983 ) < 1e-2 assert abs(result_mean.item() - 0.336_2038 ) < 1e-3 def UpperCAmelCase_ ( self ): """simple docstring""" pass def UpperCAmelCase_ ( self ): """simple docstring""" pass
320
1
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def UpperCAmelCase_ ( ): raise RuntimeError("""CUDA out of memory.""" ) class UpperCamelCase__ ( nn.Module ): def __init__( self : str ): '''simple docstring''' super().__init__() lowercase_ = nn.Linear(3 , 4 ) lowercase_ = nn.BatchNormad(4 ) lowercase_ = nn.Linear(4 , 5 ) def UpperCAmelCase__ ( self : Dict , UpperCamelCase__ : Any ): '''simple docstring''' return self.lineara(self.batchnorm(self.lineara(UpperCamelCase__ ) ) ) class UpperCamelCase__ ( unittest.TestCase ): def UpperCAmelCase__ ( self : int ): '''simple docstring''' lowercase_ = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(UpperCamelCase__ : Optional[Any] ): nonlocal batch_sizes batch_sizes.append(UpperCamelCase__ ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(UpperCamelCase__ , [128, 64, 32, 16, 8] ) def UpperCAmelCase__ ( self : Union[str, Any] ): '''simple docstring''' lowercase_ = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(UpperCamelCase__ : int , UpperCamelCase__ : Tuple ): nonlocal batch_sizes batch_sizes.append(UpperCamelCase__ ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga lowercase_ , lowercase_ = mock_training_loop_function("""hello""" ) self.assertListEqual(UpperCamelCase__ , [128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] , [8, """hello"""] ) def UpperCAmelCase__ ( self : Any ): '''simple docstring''' @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(UpperCamelCase__ : List[str] ): pass with self.assertRaises(UpperCamelCase__ ) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0] ) def UpperCAmelCase__ ( self : Any ): '''simple docstring''' @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(UpperCamelCase__ : List[Any] ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(UpperCamelCase__ ) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0] ) def UpperCAmelCase__ ( self : int ): '''simple docstring''' @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : int ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(UpperCamelCase__ ) as cm: mock_training_loop_function(128 , """hello""" , """world""" ) self.assertIn("""Batch size was passed into `f`""" , cm.exception.args[0] ) self.assertIn("""`f(arg1='hello', arg2='world')""" , cm.exception.args[0] ) def UpperCAmelCase__ ( self : Any ): '''simple docstring''' @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(UpperCamelCase__ : Any ): raise ValueError("""Oops, we had an error!""" ) with self.assertRaises(UpperCamelCase__ ) as cm: mock_training_loop_function() self.assertIn("""Oops, we had an error!""" , cm.exception.args[0] ) @require_cuda def UpperCAmelCase__ ( self : Optional[int] ): '''simple docstring''' lowercase_ = torch.cuda.memory_allocated() lowercase_ = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , UpperCamelCase__ ) lowercase_ = release_memory(UpperCamelCase__ ) self.assertEqual(torch.cuda.memory_allocated() , UpperCamelCase__ )
650
import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: a = None a = logging.get_logger(__name__) a = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} a = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 a = { 't5-small': 5_1_2, 't5-base': 5_1_2, 't5-large': 5_1_2, 't5-3b': 5_1_2, 't5-11b': 5_1_2, } class UpperCamelCase__ ( __magic_name__ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE : int = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE : str = ['input_ids', 'attention_mask'] __SCREAMING_SNAKE_CASE : Dict = TaTokenizer __SCREAMING_SNAKE_CASE : List[int] = [] def __init__( self : int , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Any=None , UpperCamelCase__ : Dict="</s>" , UpperCamelCase__ : Tuple="<unk>" , UpperCamelCase__ : Optional[Any]="<pad>" , UpperCamelCase__ : Union[str, Any]=100 , UpperCamelCase__ : Optional[Any]=None , **UpperCamelCase__ : List[str] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: lowercase_ = [F'''<extra_id_{i}>''' for i in range(UpperCamelCase__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens lowercase_ = len(set(filter(lambda UpperCamelCase__ : bool("""extra_id_""" in str(UpperCamelCase__ ) ) , UpperCamelCase__ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) super().__init__( UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , extra_ids=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , **UpperCamelCase__ , ) lowercase_ = vocab_file lowercase_ = False if not self.vocab_file else True lowercase_ = extra_ids @staticmethod def UpperCAmelCase__ ( UpperCamelCase__ : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : int ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: lowercase_ = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" F''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" F''' {pretrained_model_name_or_path} automatically truncating your input to''' F''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' F''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , UpperCamelCase__ , ) return max_model_length def UpperCAmelCase__ ( self : int , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(UpperCamelCase__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ = os.path.join( UpperCamelCase__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ): copyfile(self.vocab_file , UpperCamelCase__ ) logger.info(F'''Copy vocab file to {out_vocab_file}''' ) return (out_vocab_file,) def UpperCAmelCase__ ( self : int , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' lowercase_ = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: lowercase_ = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def UpperCAmelCase__ ( self : str , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' lowercase_ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def UpperCAmelCase__ ( self : Dict ): '''simple docstring''' return list( set(filter(lambda UpperCamelCase__ : bool(re.search(R"""<extra_id_\d+>""" , UpperCamelCase__ ) ) is not None , self.additional_special_tokens ) ) ) def UpperCAmelCase__ ( self : str ): '''simple docstring''' return [self.convert_tokens_to_ids(UpperCamelCase__ ) for token in self.get_sentinel_tokens()]
650
1
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _UpperCAmelCase ( A__ ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = ['''image_processor''', '''tokenizer'''] SCREAMING_SNAKE_CASE_ : str = '''ViTImageProcessor''' SCREAMING_SNAKE_CASE_ : int = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self : List[str] , A : Any=None , A : Optional[Any]=None , **A : List[Any] ) -> Any: lowercase_ : int = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , lowerCAmelCase__ , ) lowercase_ : str = kwargs.pop('''feature_extractor''' ) lowercase_ : Optional[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(lowerCAmelCase__ , lowerCAmelCase__ ) def __call__( self : Tuple , A : int=None , A : Tuple=None , A : Any=None , A : str=None , **A : str ) -> Any: if text is None and visual_prompt is None and images is None: raise ValueError('''You have to specify either text, visual prompt or images.''' ) if text is not None and visual_prompt is not None: raise ValueError('''You have to specify exactly one type of prompt. Either text or visual prompt.''' ) if text is not None: lowercase_ : Tuple = self.tokenizer(lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ ) if visual_prompt is not None: lowercase_ : Any = self.image_processor(lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ ) if images is not None: lowercase_ : str = self.image_processor(lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ ) if visual_prompt is not None and images is not None: lowercase_ : Optional[Any] = { '''pixel_values''': image_features.pixel_values, '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: lowercase_ : Any = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: lowercase_ : Union[str, Any] = { '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**lowerCAmelCase__ ) , tensor_type=lowerCAmelCase__ ) def A ( self : Any , *A : Any , **A : int ) -> Any: return self.tokenizer.batch_decode(*lowerCAmelCase__ , **lowerCAmelCase__ ) def A ( self : List[str] , *A : Dict , **A : Union[str, Any] ) -> Union[str, Any]: return self.tokenizer.decode(*lowerCAmelCase__ , **lowerCAmelCase__ ) @property def A ( self : Optional[int] ) -> Optional[Any]: warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , lowerCAmelCase__ , ) return self.image_processor_class @property def A ( self : Optional[int] ) -> Union[str, Any]: warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , lowerCAmelCase__ , ) return self.image_processor
231
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=A__ ) class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = field(default='''summarization''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) SCREAMING_SNAKE_CASE__ : ClassVar[Features] = Features({'''text''': Value('''string''' )} ) SCREAMING_SNAKE_CASE__ : ClassVar[Features] = Features({'''summary''': Value('''string''' )} ) SCREAMING_SNAKE_CASE__ : str = "text" SCREAMING_SNAKE_CASE__ : str = "summary" @property def __magic_name__( self :Union[str, Any] ) -> Dict[str, str]: return {self.text_column: "text", self.summary_column: "summary"}
696
0
from numpy import exp, pi, sqrt def __a ( __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : float = 0.0 , __UpperCAmelCase : float = 1.0 ) -> int: """simple docstring""" return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
701
# Copyright (c) 2021-, NVIDIA CORPORATION. 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. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def __a ( __UpperCAmelCase : int , __UpperCAmelCase : str , __UpperCAmelCase : Optional[Any]=0 ) -> Tuple: """simple docstring""" if name is None: lowerCamelCase_ : Dict = None else: lowerCamelCase_ : Any = "." * max(0 , spaces - 2 ) + "# {:" + str(50 - spaces ) + "s}" lowerCamelCase_ : Dict = fmt.format(__UpperCAmelCase ) # Print and recurse (if needed). if isinstance(__UpperCAmelCase , __UpperCAmelCase ): if msg is not None: print(__UpperCAmelCase ) for k in val.keys(): recursive_print(__UpperCAmelCase , val[k] , spaces + 2 ) elif isinstance(__UpperCAmelCase , torch.Tensor ): print(__UpperCAmelCase , ":" , val.size() ) else: print(__UpperCAmelCase , ":" , __UpperCAmelCase ) def __a ( __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ : Tuple = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] lowerCamelCase_ : Dict = (num_heads, hidden_size, num_splits) + input_shape[1:] lowerCamelCase_ : Optional[Any] = param.view(*__UpperCAmelCase ) lowerCamelCase_ : Optional[Any] = param.transpose(0 , 2 ) lowerCamelCase_ : Any = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] lowerCamelCase_ : Optional[int] = (num_heads, num_splits, hidden_size) + input_shape[1:] lowerCamelCase_ : Optional[Any] = param.view(*__UpperCAmelCase ) lowerCamelCase_ : Optional[int] = param.transpose(0 , 1 ).contiguous() lowerCamelCase_ : Union[str, Any] = param.view(*__UpperCAmelCase ) return param def __a ( __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any] ) -> str: """simple docstring""" lowerCamelCase_ : Tuple = {} # old versions did not store training args lowerCamelCase_ : Optional[Any] = input_state_dict.get("args" , __UpperCAmelCase ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) lowerCamelCase_ : List[str] = ds_args.padded_vocab_size lowerCamelCase_ : Optional[int] = ds_args.max_position_embeddings lowerCamelCase_ : Union[str, Any] = ds_args.hidden_size lowerCamelCase_ : Tuple = ds_args.num_layers lowerCamelCase_ : List[str] = ds_args.num_attention_heads lowerCamelCase_ : List[str] = ds_args.ffn_hidden_size # pprint(config) # The number of heads. lowerCamelCase_ : List[Any] = config.n_head # The hidden_size per head. lowerCamelCase_ : Tuple = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): lowerCamelCase_ : Any = input_state_dict["checkpoint_version"] else: lowerCamelCase_ : int = 0.0 # The model. lowerCamelCase_ : int = input_state_dict["model"] # The language model. lowerCamelCase_ : Dict = model["language_model"] # The embeddings. lowerCamelCase_ : Optional[int] = lm["embedding"] # The word embeddings. lowerCamelCase_ : Union[str, Any] = embeddings["word_embeddings"]["weight"] # Truncate the embedding table to vocab_size rows. lowerCamelCase_ : int = word_embeddings[: config.vocab_size, :] lowerCamelCase_ : int = word_embeddings # The position embeddings. lowerCamelCase_ : List[str] = embeddings["position_embeddings"]["weight"] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] lowerCamelCase_ : List[Any] = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( f"pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don't match" ) # Store the position embeddings. lowerCamelCase_ : Optional[int] = pos_embeddings # The transformer. lowerCamelCase_ : List[str] = lm["transformer"] if "transformer" in lm.keys() else lm["encoder"] # The regex to extract layer names. lowerCamelCase_ : Optional[int] = re.compile(R"layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)" ) # The simple map of names for "automated" rules. lowerCamelCase_ : Optional[Any] = { "attention.dense": ".attn.c_proj.", "self_attention.dense": ".attn.c_proj.", "mlp.dense_h_to_4h": ".mlp.c_fc.", "mlp.dense_4h_to_h": ".mlp.c_proj.", } # Extract the layers. for key, val in transformer.items(): # Match the name. lowerCamelCase_ : Optional[int] = layer_re.match(__UpperCAmelCase ) # Stop if that's not a layer if m is None: break # The index of the layer. lowerCamelCase_ : str = int(m.group(1 ) ) # The name of the operation. lowerCamelCase_ : Optional[int] = m.group(2 ) # Is it a weight or a bias? lowerCamelCase_ : int = m.group(3 ) # The name of the layer. lowerCamelCase_ : Optional[Any] = f"transformer.h.{layer_idx}" # For layernorm(s), simply store the layer norm. if op_name.endswith("layernorm" ): lowerCamelCase_ : Optional[int] = "ln_1" if op_name.startswith("input" ) else "ln_2" lowerCamelCase_ : int = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. lowerCamelCase_ : Union[str, Any] = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , __UpperCAmelCase , __UpperCAmelCase ) lowerCamelCase_ : str = causal_mask # Insert a "dummy" tensor for masked_bias. lowerCamelCase_ : Any = torch.tensor(-1e4 , dtype=torch.floataa ) lowerCamelCase_ : Union[str, Any] = masked_bias lowerCamelCase_ : Union[str, Any] = fix_query_key_value_ordering(__UpperCAmelCase , __UpperCAmelCase , 3 , __UpperCAmelCase , __UpperCAmelCase ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. lowerCamelCase_ : Dict = out_val.transpose(0 , 1 ).contiguous() # Store. lowerCamelCase_ : Tuple = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": lowerCamelCase_ : Union[str, Any] = fix_query_key_value_ordering(__UpperCAmelCase , __UpperCAmelCase , 3 , __UpperCAmelCase , __UpperCAmelCase ) # Store. No change of shape. lowerCamelCase_ : Dict = out_val # Transpose the weights. elif weight_or_bias == "weight": lowerCamelCase_ : Union[str, Any] = megatron_to_transformers[op_name] lowerCamelCase_ : int = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": lowerCamelCase_ : Optional[int] = megatron_to_transformers[op_name] lowerCamelCase_ : Dict = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. lowerCamelCase_ : List[Any] = transformer["final_layernorm.weight"] lowerCamelCase_ : List[Any] = transformer["final_layernorm.bias"] # For LM head, transformers' wants the matrix to weight embeddings. lowerCamelCase_ : Union[str, Any] = word_embeddings # It should be done! return output_state_dict def __a ( ) -> int: """simple docstring""" lowerCamelCase_ : Optional[int] = argparse.ArgumentParser() parser.add_argument("--print-checkpoint-structure" , action="store_true" ) parser.add_argument( "path_to_checkpoint" , type=__UpperCAmelCase , help="Path to the checkpoint file (.zip archive or direct .pt file)" , ) parser.add_argument( "--config_file" , default="" , type=__UpperCAmelCase , help="An optional config json file describing the pre-trained model." , ) lowerCamelCase_ : str = parser.parse_args() # Extract the basename. lowerCamelCase_ : Tuple = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(f"Extracting PyTorch state dictionary from {args.path_to_checkpoint}" ) if args.path_to_checkpoint.endswith(".zip" ): with zipfile.ZipFile(args.path_to_checkpoint , "r" ) as checkpoint: with checkpoint.open("release/mp_rank_00/model_optim_rng.pt" ) as pytorch_dict: lowerCamelCase_ : int = torch.load(__UpperCAmelCase , map_location="cpu" ) else: lowerCamelCase_ : int = torch.load(args.path_to_checkpoint , map_location="cpu" ) lowerCamelCase_ : Any = input_state_dict.get("args" , __UpperCAmelCase ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: lowerCamelCase_ : Optional[int] = "gelu_fast" elif ds_args.openai_gelu: lowerCamelCase_ : List[str] = "gelu_new" else: lowerCamelCase_ : int = "gelu" else: # in the very early days this used to be "gelu_new" lowerCamelCase_ : Any = "gelu_new" # Spell out all parameters in case the defaults change. lowerCamelCase_ : int = GPTaConfig( vocab_size=50257 , n_positions=1024 , n_embd=1024 , n_layer=24 , n_head=16 , n_inner=4096 , activation_function=__UpperCAmelCase , resid_pdrop=0.1 , embd_pdrop=0.1 , attn_pdrop=0.1 , layer_norm_epsilon=1e-5 , initializer_range=0.0_2 , summary_type="cls_index" , summary_use_proj=__UpperCAmelCase , summary_activation=__UpperCAmelCase , summary_proj_to_labels=__UpperCAmelCase , summary_first_dropout=0.1 , scale_attn_weights=__UpperCAmelCase , use_cache=__UpperCAmelCase , bos_token_id=50256 , eos_token_id=50256 , ) else: lowerCamelCase_ : Dict = GPTaConfig.from_json_file(args.config_file ) lowerCamelCase_ : Tuple = ["GPT2LMHeadModel"] # Convert. print("Converting" ) lowerCamelCase_ : Dict = convert_megatron_checkpoint(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(__UpperCAmelCase , __UpperCAmelCase ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: lowerCamelCase_ : List[Any] = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": lowerCamelCase_ : Union[str, Any] = "gpt2" elif tokenizer_type == "PretrainedFromHF": lowerCamelCase_ : Union[str, Any] = ds_args.tokenizer_name_or_path else: raise ValueError(f"Unrecognized tokenizer_type {tokenizer_type}" ) else: lowerCamelCase_ : List[Any] = "gpt2" lowerCamelCase_ : Optional[Any] = AutoTokenizer.from_pretrained(__UpperCAmelCase ) lowerCamelCase_ : Union[str, Any] = type(__UpperCAmelCase ).__name__ lowerCamelCase_ : Dict = tokenizer_class # Store the config to file. print("Saving config" ) config.save_pretrained(__UpperCAmelCase ) # Save tokenizer based on args print(f"Adding {tokenizer_class} tokenizer files" ) tokenizer.save_pretrained(__UpperCAmelCase ) # Store the state_dict to file. lowerCamelCase_ : List[str] = os.path.join(__UpperCAmelCase , "pytorch_model.bin" ) print(f"Saving checkpoint to \"{output_checkpoint_file}\"" ) torch.save(__UpperCAmelCase , __UpperCAmelCase ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
253
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE ( metaclass=_a ): """simple docstring""" _SCREAMING_SNAKE_CASE = ["""transformers""", """torch""", """note_seq"""] def __init__( self : Dict , *UpperCamelCase__ : str , **UpperCamelCase__ : Dict ): """simple docstring""" requires_backends(self , ['transformers', 'torch', 'note_seq'] ) @classmethod def A ( cls : Tuple , *UpperCamelCase__ : Optional[int] , **UpperCamelCase__ : Union[str, Any] ): """simple docstring""" requires_backends(cls , ['transformers', 'torch', 'note_seq'] ) @classmethod def A ( cls : Dict , *UpperCamelCase__ : Dict , **UpperCamelCase__ : str ): """simple docstring""" requires_backends(cls , ['transformers', 'torch', 'note_seq'] )
430
'''simple docstring''' from math import factorial def __lowerCamelCase ( A__ , A__ , A__ ) -> float: """simple docstring""" if successes > trials: raise ValueError('successes must be lower or equal to trials' ) if trials < 0 or successes < 0: raise ValueError('the function is defined for non-negative integers' ) if not isinstance(A__ , A__ ) or not isinstance(A__ , A__ ): raise ValueError('the function is defined for non-negative integers' ) if not 0 < prob < 1: raise ValueError('prob has to be in range of 1 - 0' ) UpperCamelCase = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! UpperCamelCase = float(factorial(A__ ) ) coefficient /= factorial(A__ ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print("Probability of 2 successes out of 4 trails") print("with probability of 0.75 is:", end=" ") print(binomial_distribution(2, 4, 0.75))
430
1
from itertools import count def lowerCamelCase__ ( _lowerCamelCase = 50 ) ->int: _UpperCAmelCase =[1] * min_block_length for n in count(_lowerCamelCase ): fill_count_functions.append(1 ) for block_length in range(_lowerCamelCase , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 100_0000: break return n if __name__ == "__main__": print(F"""{solution() = }""")
592
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _a ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ): _UpperCAmelCase ="ylacombe/bark-small" _UpperCAmelCase =tempfile.mkdtemp() _UpperCAmelCase ="en_speaker_1" _UpperCAmelCase ="This is a test string" _UpperCAmelCase ="speaker_embeddings_path.json" _UpperCAmelCase ="speaker_embeddings" def SCREAMING_SNAKE_CASE ( self , **_snake_case ): return AutoTokenizer.from_pretrained(self.checkpoint , **_snake_case ) def SCREAMING_SNAKE_CASE ( self ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self ): _UpperCAmelCase =self.get_tokenizer() _UpperCAmelCase =BarkProcessor(tokenizer=_snake_case ) processor.save_pretrained(self.tmpdirname ) _UpperCAmelCase =BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def SCREAMING_SNAKE_CASE ( self ): _UpperCAmelCase =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) _UpperCAmelCase =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) _UpperCAmelCase =BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def SCREAMING_SNAKE_CASE ( self ): _UpperCAmelCase =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) _UpperCAmelCase =35 _UpperCAmelCase =2 _UpperCAmelCase =8 _UpperCAmelCase ={ "semantic_prompt": np.ones(_snake_case ), "coarse_prompt": np.ones((nb_codebooks_coarse, seq_len) ), "fine_prompt": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset _UpperCAmelCase =processor(text=self.input_string , voice_preset=_snake_case ) _UpperCAmelCase =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_snake_case , np.array([] ) ).tolist() ) # test loading voice preset from npz file _UpperCAmelCase =os.path.join(self.tmpdirname , "file.npz" ) np.savez(_snake_case , **_snake_case ) _UpperCAmelCase =processor(text=self.input_string , voice_preset=_snake_case ) _UpperCAmelCase =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_snake_case , np.array([] ) ).tolist() ) # test loading voice preset from the hub _UpperCAmelCase =processor(text=self.input_string , voice_preset=self.voice_preset ) def SCREAMING_SNAKE_CASE ( self ): _UpperCAmelCase =self.get_tokenizer() _UpperCAmelCase =BarkProcessor(tokenizer=_snake_case ) _UpperCAmelCase =processor(text=self.input_string ) _UpperCAmelCase =tokenizer( self.input_string , padding="max_length" , max_length=256 , add_special_tokens=_snake_case , return_attention_mask=_snake_case , return_token_type_ids=_snake_case , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
592
1
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class __lowercase ( __snake_case ): UpperCamelCase = 42 @flax_register_to_config class __lowercase ( nn.Module , __snake_case , __snake_case ): UpperCamelCase = 32 UpperCamelCase = 4 UpperCamelCase = 4 UpperCamelCase = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) UpperCamelCase = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") UpperCamelCase = False UpperCamelCase = (3_20, 6_40, 12_80, 12_80) UpperCamelCase = 2 UpperCamelCase = 8 UpperCamelCase = None UpperCamelCase = 12_80 UpperCamelCase = 0.0 UpperCamelCase = False UpperCamelCase = jnp.floataa UpperCamelCase = True UpperCamelCase = 0 UpperCamelCase = False def _lowercase ( self : Dict , __lowerCamelCase : jax.random.KeyArray ) -> FrozenDict: """simple docstring""" UpperCAmelCase = (1, self.in_channels, self.sample_size, self.sample_size) UpperCAmelCase = jnp.zeros(__lowerCamelCase , dtype=jnp.floataa ) UpperCAmelCase = jnp.ones((1,) , dtype=jnp.intaa ) UpperCAmelCase = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) UpperCAmelCase , UpperCAmelCase = jax.random.split(__lowerCamelCase ) UpperCAmelCase = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )["params"] def _lowercase ( self : str ) -> Tuple: """simple docstring""" UpperCAmelCase = self.block_out_channels UpperCAmelCase = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( """At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.""" ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. UpperCAmelCase = self.num_attention_heads or self.attention_head_dim # input UpperCAmelCase = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time UpperCAmelCase = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) UpperCAmelCase = FlaxTimestepEmbedding(__lowerCamelCase , dtype=self.dtype ) UpperCAmelCase = self.only_cross_attention if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCAmelCase = (only_cross_attention,) * len(self.down_block_types ) if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCAmelCase = (num_attention_heads,) * len(self.down_block_types ) # down UpperCAmelCase = [] UpperCAmelCase = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): UpperCAmelCase = output_channel UpperCAmelCase = block_out_channels[i] UpperCAmelCase = i == len(__lowerCamelCase ) - 1 if down_block_type == "CrossAttnDownBlock2D": UpperCAmelCase = FlaxCrossAttnDownBlockaD( in_channels=__lowerCamelCase , out_channels=__lowerCamelCase , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: UpperCAmelCase = FlaxDownBlockaD( in_channels=__lowerCamelCase , out_channels=__lowerCamelCase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(__lowerCamelCase ) UpperCAmelCase = down_blocks # mid UpperCAmelCase = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up UpperCAmelCase = [] UpperCAmelCase = list(reversed(__lowerCamelCase ) ) UpperCAmelCase = list(reversed(__lowerCamelCase ) ) UpperCAmelCase = list(reversed(__lowerCamelCase ) ) UpperCAmelCase = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): UpperCAmelCase = output_channel UpperCAmelCase = reversed_block_out_channels[i] UpperCAmelCase = reversed_block_out_channels[min(i + 1 , len(__lowerCamelCase ) - 1 )] UpperCAmelCase = i == len(__lowerCamelCase ) - 1 if up_block_type == "CrossAttnUpBlock2D": UpperCAmelCase = FlaxCrossAttnUpBlockaD( in_channels=__lowerCamelCase , out_channels=__lowerCamelCase , prev_output_channel=__lowerCamelCase , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: UpperCAmelCase = FlaxUpBlockaD( in_channels=__lowerCamelCase , out_channels=__lowerCamelCase , prev_output_channel=__lowerCamelCase , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(__lowerCamelCase ) UpperCAmelCase = output_channel UpperCAmelCase = up_blocks # out UpperCAmelCase = nn.GroupNorm(num_groups=3_2 , epsilon=1e-5 ) UpperCAmelCase = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Optional[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : bool = True , __lowerCamelCase : bool = False , ) -> Union[FlaxUNetaDConditionOutput, Tuple]: """simple docstring""" if not isinstance(__lowerCamelCase , jnp.ndarray ): UpperCAmelCase = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(__lowerCamelCase , jnp.ndarray ) and len(timesteps.shape ) == 0: UpperCAmelCase = timesteps.astype(dtype=jnp.floataa ) UpperCAmelCase = jnp.expand_dims(__lowerCamelCase , 0 ) UpperCAmelCase = self.time_proj(__lowerCamelCase ) UpperCAmelCase = self.time_embedding(__lowerCamelCase ) # 2. pre-process UpperCAmelCase = jnp.transpose(__lowerCamelCase , (0, 2, 3, 1) ) UpperCAmelCase = self.conv_in(__lowerCamelCase ) # 3. down UpperCAmelCase = (sample,) for down_block in self.down_blocks: if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCAmelCase , UpperCAmelCase = down_block(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , deterministic=not train ) else: UpperCAmelCase , UpperCAmelCase = down_block(__lowerCamelCase , __lowerCamelCase , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: UpperCAmelCase = () for down_block_res_sample, down_block_additional_residual in zip( __lowerCamelCase , __lowerCamelCase ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) UpperCAmelCase = new_down_block_res_samples # 4. mid UpperCAmelCase = self.mid_block(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: UpperCAmelCase = down_block_res_samples[-(self.layers_per_block + 1) :] UpperCAmelCase = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCAmelCase = up_block( __lowerCamelCase , temb=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , res_hidden_states_tuple=__lowerCamelCase , deterministic=not train , ) else: UpperCAmelCase = up_block(__lowerCamelCase , temb=__lowerCamelCase , res_hidden_states_tuple=__lowerCamelCase , deterministic=not train ) # 6. post-process UpperCAmelCase = self.conv_norm_out(__lowerCamelCase ) UpperCAmelCase = nn.silu(__lowerCamelCase ) UpperCAmelCase = self.conv_out(__lowerCamelCase ) UpperCAmelCase = jnp.transpose(__lowerCamelCase , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=__lowerCamelCase )
377
import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class __lowercase ( __snake_case ): def __init__( self : Dict , *__lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : str=None , **__lowerCamelCase : Optional[int] ) -> Optional[int]: """simple docstring""" super().__init__(*__lowerCamelCase , **__lowerCamelCase ) UpperCAmelCase = eval_examples UpperCAmelCase = post_process_function def _lowercase ( self : Any , __lowerCamelCase : int=None , __lowerCamelCase : int=None , __lowerCamelCase : Tuple=None , __lowerCamelCase : str = "eval" ) -> List[str]: """simple docstring""" UpperCAmelCase = self.eval_dataset if eval_dataset is None else eval_dataset UpperCAmelCase = self.get_eval_dataloader(__lowerCamelCase ) UpperCAmelCase = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. UpperCAmelCase = self.compute_metrics UpperCAmelCase = None UpperCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop UpperCAmelCase = time.time() try: UpperCAmelCase = eval_loop( __lowerCamelCase , description="""Evaluation""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__lowerCamelCase , metric_key_prefix=__lowerCamelCase , ) finally: UpperCAmelCase = compute_metrics UpperCAmelCase = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( __lowerCamelCase , __lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default UpperCAmelCase = self.post_process_function(__lowerCamelCase , __lowerCamelCase , output.predictions ) UpperCAmelCase = self.compute_metrics(__lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): UpperCAmelCase = metrics.pop(__lowerCamelCase ) metrics.update(output.metrics ) else: UpperCAmelCase = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(__lowerCamelCase ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) UpperCAmelCase = self.callback_handler.on_evaluate(self.args , self.state , self.control , __lowerCamelCase ) return metrics def _lowercase ( self : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict=None , __lowerCamelCase : str = "test" ) -> Dict: """simple docstring""" UpperCAmelCase = self.get_test_dataloader(__lowerCamelCase ) # Temporarily disable metric computation, we will do it in the loop here. UpperCAmelCase = self.compute_metrics UpperCAmelCase = None UpperCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop UpperCAmelCase = time.time() try: UpperCAmelCase = eval_loop( __lowerCamelCase , description="""Prediction""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__lowerCamelCase , metric_key_prefix=__lowerCamelCase , ) finally: UpperCAmelCase = compute_metrics UpperCAmelCase = self.args.eval_batch_size * self.args.world_size if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( __lowerCamelCase , __lowerCamelCase , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output UpperCAmelCase = self.post_process_function(__lowerCamelCase , __lowerCamelCase , output.predictions , """predict""" ) UpperCAmelCase = self.compute_metrics(__lowerCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"""{metric_key_prefix}_""" ): UpperCAmelCase = metrics.pop(__lowerCamelCase ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__lowerCamelCase )
377
1
import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class SCREAMING_SNAKE_CASE (UpperCAmelCase , unittest.TestCase ): _UpperCamelCase : Tuple = BertTokenizer _UpperCamelCase : Tuple = BertTokenizerFast _UpperCamelCase : Dict = True _UpperCamelCase : List[Any] = True _UpperCamelCase : List[Any] = filter_non_english def SCREAMING_SNAKE_CASE_ ( self : Optional[int] )-> Union[str, Any]: """simple docstring""" super().setUp() lowercase__ = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] lowercase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE_ ( self : str , a : List[str] )-> Union[str, Any]: """simple docstring""" lowercase__ = 'UNwant\u00E9d,running' lowercase__ = 'unwanted, running' return input_text, output_text def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] )-> Optional[int]: """simple docstring""" lowercase__ = self.tokenizer_class(self.vocab_file ) lowercase__ = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE_ ( self : Any )-> Optional[int]: """simple docstring""" if not self.test_rust_tokenizer: return lowercase__ = self.get_tokenizer() lowercase__ = self.get_rust_tokenizer() lowercase__ = 'UNwant\u00E9d,running' lowercase__ = tokenizer.tokenize(a ) lowercase__ = rust_tokenizer.tokenize(a ) self.assertListEqual(a , a ) lowercase__ = tokenizer.encode(a , add_special_tokens=a ) lowercase__ = rust_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) lowercase__ = self.get_rust_tokenizer() lowercase__ = tokenizer.encode(a ) lowercase__ = rust_tokenizer.encode(a ) self.assertListEqual(a , a ) # With lower casing lowercase__ = self.get_tokenizer(do_lower_case=a ) lowercase__ = self.get_rust_tokenizer(do_lower_case=a ) lowercase__ = 'UNwant\u00E9d,running' lowercase__ = tokenizer.tokenize(a ) lowercase__ = rust_tokenizer.tokenize(a ) self.assertListEqual(a , a ) lowercase__ = tokenizer.encode(a , add_special_tokens=a ) lowercase__ = rust_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) lowercase__ = self.get_rust_tokenizer() lowercase__ = tokenizer.encode(a ) lowercase__ = rust_tokenizer.encode(a ) self.assertListEqual(a , a ) def SCREAMING_SNAKE_CASE_ ( self : int )-> Optional[int]: """simple docstring""" lowercase__ = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def SCREAMING_SNAKE_CASE_ ( self : Any )-> Union[str, Any]: """simple docstring""" lowercase__ = BasicTokenizer(do_lower_case=a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] )-> Optional[Any]: """simple docstring""" lowercase__ = BasicTokenizer(do_lower_case=a , strip_accents=a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> Optional[Any]: """simple docstring""" lowercase__ = BasicTokenizer(do_lower_case=a , strip_accents=a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] )-> Tuple: """simple docstring""" lowercase__ = BasicTokenizer(do_lower_case=a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def SCREAMING_SNAKE_CASE_ ( self : str )-> Optional[Any]: """simple docstring""" lowercase__ = BasicTokenizer(do_lower_case=a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] )-> List[Any]: """simple docstring""" lowercase__ = BasicTokenizer(do_lower_case=a , strip_accents=a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def SCREAMING_SNAKE_CASE_ ( self : List[str] )-> List[str]: """simple docstring""" lowercase__ = BasicTokenizer(do_lower_case=a , strip_accents=a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def SCREAMING_SNAKE_CASE_ ( self : int )-> Dict: """simple docstring""" lowercase__ = BasicTokenizer(do_lower_case=a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def SCREAMING_SNAKE_CASE_ ( self : Any )-> Optional[Any]: """simple docstring""" lowercase__ = BasicTokenizer() lowercase__ = 'a\n\'ll !!to?\'d of, can\'t.' lowercase__ = ['a', '\'', 'll', '!', '!', 'to', '?', '\'', 'd', 'of', ',', 'can', '\'', 't', '.'] self.assertListEqual(tokenizer.tokenize(a ) , a ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] )-> Tuple: """simple docstring""" lowercase__ = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] lowercase__ = {} for i, token in enumerate(a ): lowercase__ = i lowercase__ = WordpieceTokenizer(vocab=a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) def SCREAMING_SNAKE_CASE_ ( self : Any )-> int: """simple docstring""" self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def SCREAMING_SNAKE_CASE_ ( self : Any )-> Dict: """simple docstring""" self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def SCREAMING_SNAKE_CASE_ ( self : Dict )-> Union[str, Any]: """simple docstring""" self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] )-> Union[str, Any]: """simple docstring""" lowercase__ = self.get_tokenizer() lowercase__ = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(a ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) self.assertListEqual( [rust_tokenizer.tokenize(a ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] )-> Optional[Any]: """simple docstring""" lowercase__ = self.tokenizer_class.from_pretrained('bert-base-uncased' ) lowercase__ = tokenizer.encode('sequence builders' , add_special_tokens=a ) lowercase__ = tokenizer.encode('multi-sequence build' , add_special_tokens=a ) lowercase__ = tokenizer.build_inputs_with_special_tokens(a ) lowercase__ = tokenizer.build_inputs_with_special_tokens(a , a ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowercase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) lowercase__ = f"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" lowercase__ = tokenizer_r.encode_plus( a , return_attention_mask=a , return_token_type_ids=a , return_offsets_mapping=a , add_special_tokens=a , ) lowercase__ = tokenizer_r.do_lower_case if hasattr(a , 'do_lower_case' ) else False lowercase__ = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'Allen'), ((21, 23), '##NL'), ((23, 24), '##P'), ((25, 33), 'sentence'), ((33, 34), '.'), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'a'), ((1, 2), ','), ((3, 8), 'naive'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'allen'), ((21, 23), '##nl'), ((23, 24), '##p'), ((25, 33), 'sentence'), ((33, 34), '.'), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['input_ids'] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['offset_mapping'] ) def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> Dict: """simple docstring""" lowercase__ = ['的', '人', '有'] lowercase__ = ''.join(a ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowercase__ = True lowercase__ = self.tokenizer_class.from_pretrained(a , **a ) lowercase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) lowercase__ = tokenizer_p.encode(a , add_special_tokens=a ) lowercase__ = tokenizer_r.encode(a , add_special_tokens=a ) lowercase__ = tokenizer_r.convert_ids_to_tokens(a ) lowercase__ = tokenizer_p.convert_ids_to_tokens(a ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(a , a ) self.assertListEqual(a , a ) lowercase__ = False lowercase__ = self.rust_tokenizer_class.from_pretrained(a , **a ) lowercase__ = self.tokenizer_class.from_pretrained(a , **a ) lowercase__ = tokenizer_r.encode(a , add_special_tokens=a ) lowercase__ = tokenizer_p.encode(a , add_special_tokens=a ) lowercase__ = tokenizer_r.convert_ids_to_tokens(a ) lowercase__ = tokenizer_p.convert_ids_to_tokens(a ) # it is expected that only the first Chinese character is not preceded by "##". lowercase__ = [ f"""##{token}""" if idx != 0 else token for idx, token in enumerate(a ) ] self.assertListEqual(a , a ) self.assertListEqual(a , a )
45
def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> List[Any]: stooge(_SCREAMING_SNAKE_CASE , 0 , len(_SCREAMING_SNAKE_CASE ) - 1 ) return arr def __UpperCamelCase (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: lowercase__ , lowercase__ = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: lowercase__ = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (h - t) ) # Recursively sort last 2/3 elements stooge(_SCREAMING_SNAKE_CASE , i + t , (_SCREAMING_SNAKE_CASE) ) # Recursively sort first 2/3 elements stooge(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (h - t) ) if __name__ == "__main__": lowercase_ = input("""Enter numbers separated by a comma:\n""").strip() lowercase_ = [int(item) for item in user_input.split(""",""")] print(stooge_sort(unsorted))
45
1
# Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase__ = { '''configuration_cpmant''': ['''CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CpmAntConfig'''], '''tokenization_cpmant''': ['''CpmAntTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ '''CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CpmAntForCausalLM''', '''CpmAntModel''', '''CpmAntPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
547
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed lowerCamelCase__ = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def lowerCAmelCase__ ( a__ ) ->Optional[Any]: '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def lowerCAmelCase__ ( a__ , a__ ) ->List[Any]: '''simple docstring''' if args.student_type == "roberta": _UpperCamelCase = False elif args.student_type == "gpt2": _UpperCamelCase = False def lowerCAmelCase__ ( a__ , a__ ) ->List[str]: '''simple docstring''' if args.student_type == "roberta": _UpperCamelCase = False def lowerCAmelCase__ ( ) ->Any: '''simple docstring''' _UpperCamelCase = argparse.ArgumentParser(description="Training" ) parser.add_argument("--force" , action="store_true" , help="Overwrite dump_path if it already exists." ) parser.add_argument( "--dump_path" , type=a__ , required=a__ , help="The output directory (log, checkpoints, parameters, etc.)" ) parser.add_argument( "--data_file" , type=a__ , required=a__ , help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence." , ) parser.add_argument( "--student_type" , type=a__ , choices=["distilbert", "roberta", "gpt2"] , required=a__ , help="The student type (DistilBERT, RoBERTa)." , ) parser.add_argument("--student_config" , type=a__ , required=a__ , help="Path to the student configuration." ) parser.add_argument( "--student_pretrained_weights" , default=a__ , type=a__ , help="Load student initialization checkpoint." ) parser.add_argument( "--teacher_type" , choices=["bert", "roberta", "gpt2"] , required=a__ , help="Teacher type (BERT, RoBERTa)." ) parser.add_argument("--teacher_name" , type=a__ , required=a__ , help="The teacher model." ) parser.add_argument("--temperature" , default=2.0 , type=a__ , help="Temperature for the softmax temperature." ) parser.add_argument( "--alpha_ce" , default=0.5 , type=a__ , help="Linear weight for the distillation loss. Must be >=0." ) parser.add_argument( "--alpha_mlm" , default=0.0 , type=a__ , help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag." , ) parser.add_argument("--alpha_clm" , default=0.5 , type=a__ , help="Linear weight for the CLM loss. Must be >=0." ) parser.add_argument("--alpha_mse" , default=0.0 , type=a__ , help="Linear weight of the MSE loss. Must be >=0." ) parser.add_argument( "--alpha_cos" , default=0.0 , type=a__ , help="Linear weight of the cosine embedding loss. Must be >=0." ) parser.add_argument( "--mlm" , action="store_true" , help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM." ) parser.add_argument( "--mlm_mask_prop" , default=0.15 , type=a__ , help="Proportion of tokens for which we need to make a prediction." , ) parser.add_argument("--word_mask" , default=0.8 , type=a__ , help="Proportion of tokens to mask out." ) parser.add_argument("--word_keep" , default=0.1 , type=a__ , help="Proportion of tokens to keep." ) parser.add_argument("--word_rand" , default=0.1 , type=a__ , help="Proportion of tokens to randomly replace." ) parser.add_argument( "--mlm_smoothing" , default=0.7 , type=a__ , help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec)." , ) parser.add_argument("--token_counts" , type=a__ , help="The token counts in the data_file for MLM." ) parser.add_argument( "--restrict_ce_to_mask" , action="store_true" , help="If true, compute the distillation loss only the [MLM] prediction distribution." , ) parser.add_argument( "--freeze_pos_embs" , action="store_true" , help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only." , ) parser.add_argument( "--freeze_token_type_embds" , action="store_true" , help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only." , ) parser.add_argument("--n_epoch" , type=a__ , default=3 , help="Number of pass on the whole dataset." ) parser.add_argument("--batch_size" , type=a__ , default=5 , help="Batch size (for each process)." ) parser.add_argument( "--group_by_size" , action="store_false" , help="If true, group sequences that have similar length into the same batch. Default is true." , ) parser.add_argument( "--gradient_accumulation_steps" , type=a__ , default=50 , help="Gradient accumulation for larger training batches." , ) parser.add_argument("--warmup_prop" , default=0.05 , type=a__ , help="Linear warmup proportion." ) parser.add_argument("--weight_decay" , default=0.0 , type=a__ , help="Weight decay if we apply some." ) parser.add_argument("--learning_rate" , default=5e-4 , type=a__ , help="The initial learning rate for Adam." ) parser.add_argument("--adam_epsilon" , default=1e-6 , type=a__ , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , default=5.0 , type=a__ , help="Max gradient norm." ) parser.add_argument("--initializer_range" , default=0.02 , type=a__ , help="Random initialization range." ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=a__ , default="O1" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_gpu" , type=a__ , default=1 , help="Number of GPUs in the node." ) parser.add_argument("--local_rank" , type=a__ , default=-1 , help="Distributed training - Local rank" ) parser.add_argument("--seed" , type=a__ , default=56 , help="Random seed" ) parser.add_argument("--log_interval" , type=a__ , default=500 , help="Tensorboard logging interval." ) parser.add_argument("--checkpoint_interval" , type=a__ , default=4_000 , help="Checkpoint interval." ) _UpperCamelCase = parser.parse_args() sanity_checks(a__ ) # ARGS # init_gpu_params(a__ ) set_seed(a__ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f'Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite' " itUse `--force` if you want to overwrite it" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f'Experiment will be dumped and logged in {args.dump_path}' ) # SAVE PARAMS # logger.info(f'Param: {args}' ) with open(os.path.join(args.dump_path , "parameters.json" ) , "w" ) as f: json.dump(vars(a__ ) , a__ , indent=4 ) git_log(args.dump_path ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = MODEL_CLASSES[args.student_type] _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = MODEL_CLASSES[args.teacher_type] # TOKENIZER # _UpperCamelCase = teacher_tokenizer_class.from_pretrained(args.teacher_name ) _UpperCamelCase = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): _UpperCamelCase = tokenizer.all_special_tokens.index(a__ ) _UpperCamelCase = tokenizer.all_special_ids[idx] logger.info(f'Special tokens {special_tok_ids}' ) _UpperCamelCase = special_tok_ids _UpperCamelCase = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f'Loading data from {args.data_file}' ) with open(args.data_file , "rb" ) as fp: _UpperCamelCase = pickle.load(a__ ) if args.mlm: logger.info(f'Loading token counts from {args.token_counts} (already pre-computed)' ) with open(args.token_counts , "rb" ) as fp: _UpperCamelCase = pickle.load(a__ ) _UpperCamelCase = np.maximum(a__ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): _UpperCamelCase = 0.0 # do not predict special tokens _UpperCamelCase = torch.from_numpy(a__ ) else: _UpperCamelCase = None _UpperCamelCase = LmSeqsDataset(params=a__ , data=a__ ) logger.info("Data loader created." ) # STUDENT # logger.info(f'Loading student config from {args.student_config}' ) _UpperCamelCase = student_config_class.from_pretrained(args.student_config ) _UpperCamelCase = True if args.student_pretrained_weights is not None: logger.info(f'Loading pretrained weights from {args.student_pretrained_weights}' ) _UpperCamelCase = student_model_class.from_pretrained(args.student_pretrained_weights , config=a__ ) else: _UpperCamelCase = student_model_class(a__ ) if args.n_gpu > 0: student.to(f'cuda:{args.local_rank}' ) logger.info("Student loaded." ) # TEACHER # _UpperCamelCase = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=a__ ) if args.n_gpu > 0: teacher.to(f'cuda:{args.local_rank}' ) logger.info(f'Teacher loaded from {args.teacher_name}.' ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(a__ , a__ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(a__ , a__ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() _UpperCamelCase = Distiller( params=a__ , dataset=a__ , token_probs=a__ , student=a__ , teacher=a__ ) distiller.train() logger.info("Let's go get some drinks." ) if __name__ == "__main__": main()
547
1
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import LayoutLMConfig, 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.models.layoutlm.modeling_tf_layoutlm import ( TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMForMaskedLM, TFLayoutLMForQuestionAnswering, TFLayoutLMForSequenceClassification, TFLayoutLMForTokenClassification, TFLayoutLMModel, ) class __a : def __init__( self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any]=13 , UpperCAmelCase_ : Optional[Any]=7 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[Any]=99 , UpperCAmelCase_ : Tuple=32 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : List[str]=4 , UpperCAmelCase_ : Dict=37 , UpperCAmelCase_ : List[str]="gelu" , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Optional[int]=512 , UpperCAmelCase_ : List[Any]=16 , UpperCAmelCase_ : Tuple=2 , UpperCAmelCase_ : List[str]=0.02 , UpperCAmelCase_ : int=3 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[int]=1_000 , )-> List[Any]: """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = seq_length UpperCamelCase = is_training UpperCamelCase = use_input_mask UpperCamelCase = use_token_type_ids UpperCamelCase = use_labels UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = type_sequence_label_size UpperCamelCase = initializer_range UpperCamelCase = num_labels UpperCamelCase = num_choices UpperCamelCase = scope UpperCamelCase = range_bbox def _SCREAMING_SNAKE_CASE ( self : Any )-> List[Any]: """simple docstring""" UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) # convert bbox to numpy since TF does not support item assignment UpperCamelCase = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ).numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCamelCase = bbox[i, j, 3] UpperCamelCase = bbox[i, j, 1] UpperCamelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCamelCase = bbox[i, j, 2] UpperCamelCase = bbox[i, j, 0] UpperCamelCase = t UpperCamelCase = tf.convert_to_tensor(UpperCAmelCase_ ) UpperCamelCase = None if self.use_input_mask: UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase = None if self.use_token_type_ids: UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase = LayoutLMConfig( 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 config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[Any] )-> Union[str, Any]: """simple docstring""" UpperCamelCase = TFLayoutLMModel(config=UpperCAmelCase_ ) UpperCamelCase = model(UpperCAmelCase_ , UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) UpperCamelCase = model(UpperCAmelCase_ , UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) UpperCamelCase = model(UpperCAmelCase_ , UpperCAmelCase_ ) 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 : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any] )-> str: """simple docstring""" UpperCamelCase = TFLayoutLMForMaskedLM(config=UpperCAmelCase_ ) UpperCamelCase = model(UpperCAmelCase_ , 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 _SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict )-> str: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = TFLayoutLMForSequenceClassification(config=UpperCAmelCase_ ) UpperCamelCase = model(UpperCAmelCase_ , UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict )-> Union[str, Any]: """simple docstring""" UpperCamelCase = self.num_labels UpperCamelCase = TFLayoutLMForTokenClassification(config=UpperCAmelCase_ ) UpperCamelCase = model(UpperCAmelCase_ , 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 _SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int )-> Optional[Any]: """simple docstring""" UpperCamelCase = TFLayoutLMForQuestionAnswering(config=UpperCAmelCase_ ) UpperCamelCase = model(UpperCAmelCase_ , UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=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 _SCREAMING_SNAKE_CASE ( self : Optional[Any] )-> List[Any]: """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) = config_and_inputs UpperCamelCase = { "input_ids": input_ids, "bbox": bbox, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_tf class __a ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): UpperCamelCase_ : Union[str, Any] = ( ( TFLayoutLMModel, TFLayoutLMForMaskedLM, TFLayoutLMForTokenClassification, TFLayoutLMForSequenceClassification, TFLayoutLMForQuestionAnswering, ) if is_tf_available() else () ) UpperCamelCase_ : str = ( { '''feature-extraction''': TFLayoutLMModel, '''fill-mask''': TFLayoutLMForMaskedLM, '''text-classification''': TFLayoutLMForSequenceClassification, '''token-classification''': TFLayoutLMForTokenClassification, '''zero-shot''': TFLayoutLMForSequenceClassification, } if is_tf_available() else {} ) UpperCamelCase_ : Union[str, Any] = False UpperCamelCase_ : List[Any] = True UpperCamelCase_ : str = 10 def _SCREAMING_SNAKE_CASE ( self : List[str] )-> int: """simple docstring""" UpperCamelCase = TFLayoutLMModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def _SCREAMING_SNAKE_CASE ( self : int )-> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Dict )-> int: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] )-> Any: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] )-> Any: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] )-> Dict: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Any )-> Dict: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def _SCREAMING_SNAKE_CASE ( self : str )-> List[Any]: """simple docstring""" for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = TFLayoutLMModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @unittest.skip("Onnx compliancy broke with TF 2.10" ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] )-> str: """simple docstring""" pass def lowerCamelCase__ ( )-> Tuple: """simple docstring""" # Here we prepare a batch of 2 sequences to test a LayoutLM forward pass on: # fmt: off UpperCamelCase = tf.convert_to_tensor([[1_01,10_19,10_14,10_16,10_37,1_28_49,47_47,10_04,1_42_46,22_78,54_39,45_24,50_02,29_30,21_93,29_30,43_41,32_08,10_05,10_55,21_71,28_48,1_13_00,35_31,1_02],[1_01,40_70,40_34,70_20,10_24,30_58,10_15,10_13,28_61,10_13,60_70,1_92_74,27_72,62_05,2_78_14,1_61_47,1_61_47,43_43,20_47,1_02_83,1_09_69,1_43_89,10_12,23_38,1_02]] ) # noqa: E231 UpperCamelCase = tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],] ) # noqa: E231 UpperCamelCase = tf.convert_to_tensor([[[0,0,0,0],[4_23,2_37,4_40,2_51],[4_27,2_72,4_41,2_87],[4_19,1_15,4_37,1_29],[9_61,8_85,9_92,9_12],[2_56,38,3_30,58],[2_56,38,3_30,58],[3_36,42,3_53,57],[3_60,39,4_01,56],[3_60,39,4_01,56],[4_11,39,4_71,59],[4_79,41,5_28,59],[5_33,39,6_30,60],[67,1_13,1_34,1_31],[1_41,1_15,2_09,1_32],[68,1_49,1_33,1_66],[1_41,1_49,1_87,1_64],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[2_95,1_48,3_49,1_65],[4_41,1_49,4_92,1_66],[4_97,1_49,5_46,1_64],[64,2_01,1_25,2_18],[10_00,10_00,10_00,10_00]],[[0,0,0,0],[6_62,1_50,7_54,1_66],[6_65,1_99,7_42,2_11],[5_19,2_13,5_54,2_28],[5_19,2_13,5_54,2_28],[1_34,4_33,1_87,4_54],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[3_14,4_69,3_76,4_82],[5_04,6_84,5_82,7_06],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[6_10,7_49,6_52,7_65],[1_30,6_59,1_68,6_72],[1_76,6_57,2_37,6_72],[2_38,6_57,3_12,6_72],[4_43,6_53,6_28,6_72],[4_43,6_53,6_28,6_72],[7_16,3_01,8_25,3_17],[10_00,10_00,10_00,10_00]]] ) # noqa: E231 UpperCamelCase = tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,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: E231 # these are sequence labels (i.e. at the token level) UpperCamelCase = tf.convert_to_tensor([[-1_00,10,10,10,9,1,-1_00,7,7,-1_00,7,7,4,2,5,2,8,8,-1_00,-1_00,5,0,3,2,-1_00],[-1_00,12,12,12,-1_00,12,10,-1_00,-1_00,-1_00,-1_00,10,12,9,-1_00,-1_00,-1_00,10,10,10,9,12,-1_00,10,-1_00]] ) # noqa: E231 # fmt: on return input_ids, attention_mask, bbox, token_type_ids, labels @require_tf class __a ( unittest.TestCase ): @slow def _SCREAMING_SNAKE_CASE ( self : str )-> Optional[int]: """simple docstring""" UpperCamelCase = TFLayoutLMModel.from_pretrained("microsoft/layoutlm-base-uncased" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) # test the sequence output on [0, :3, :3] UpperCamelCase = tf.convert_to_tensor( [[0.1785, -0.1947, -0.0425], [-0.3254, -0.2807, 0.2553], [-0.5391, -0.3322, 0.3364]] , ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCAmelCase_ , atol=1e-3 ) ) # test the pooled output on [1, :3] UpperCamelCase = tf.convert_to_tensor([-0.6580, -0.0214, 0.8552] ) self.assertTrue(np.allclose(outputs.pooler_output[1, :3] , UpperCAmelCase_ , atol=1e-3 ) ) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple )-> Any: """simple docstring""" # initialize model with randomly initialized sequence classification head UpperCamelCase = TFLayoutLMForSequenceClassification.from_pretrained("microsoft/layoutlm-base-uncased" , num_labels=2 ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase = model( input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=tf.convert_to_tensor([1, 1] ) , ) # test whether we get a loss as a scalar UpperCamelCase = outputs.loss UpperCamelCase = (2,) self.assertEqual(loss.shape , UpperCAmelCase_ ) # test the shape of the logits UpperCamelCase = outputs.logits UpperCamelCase = (2, 2) self.assertEqual(logits.shape , UpperCAmelCase_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" # initialize model with randomly initialized token classification head UpperCamelCase = TFLayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased" , num_labels=13 ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase = model( input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) # test the shape of the logits UpperCamelCase = outputs.logits UpperCamelCase = tf.convert_to_tensor((2, 25, 13) ) self.assertEqual(logits.shape , UpperCAmelCase_ ) @slow def _SCREAMING_SNAKE_CASE ( self : Dict )-> Optional[Any]: """simple docstring""" # initialize model with randomly initialized token classification head UpperCamelCase = TFLayoutLMForQuestionAnswering.from_pretrained("microsoft/layoutlm-base-uncased" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) # test the shape of the logits UpperCamelCase = tf.convert_to_tensor((2, 25) ) self.assertEqual(outputs.start_logits.shape , UpperCAmelCase_ ) self.assertEqual(outputs.end_logits.shape , UpperCAmelCase_ )
556
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __a ( _lowerCAmelCase ): UpperCamelCase_ : Union[List[PIL.Image.Image], np.ndarray] UpperCamelCase_ : Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.26.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version(""">=""", """0.0.12""") ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __a ( _lowerCAmelCase ): UpperCamelCase_ : np.ndarray UpperCamelCase_ : List[bool] from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
556
1
from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class lowerCamelCase__ : """simple docstring""" _A = 42 _A = None # Automatically constructed _A = "dict" _A = None _A = field(default='Translation' , init=UpperCAmelCase_ , repr=UpperCAmelCase_) def __call__(self ): '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def _a (self ): '''simple docstring''' from .features import Value return {k: Value("string" ) for k in sorted(self.languages )} @dataclass class lowerCamelCase__ : """simple docstring""" _A = None _A = None _A = None # Automatically constructed _A = "dict" _A = None _A = field(default='TranslationVariableLanguages' , init=UpperCAmelCase_ , repr=UpperCAmelCase_) def _a (self ): '''simple docstring''' lowerCamelCase = sorted(set(self.languages ) ) if self.languages else None lowerCamelCase = len(self.languages ) if self.languages else None def __call__(self ): '''simple docstring''' return pa.struct({"language": pa.list_(pa.string() ), "translation": pa.list_(pa.string() )} ) def _a (self , __a ): '''simple docstring''' lowerCamelCase = set(self.languages ) if self.languages and set(__a ) - lang_set: raise ValueError( F"""Some languages in example ({", ".join(sorted(set(__a ) - lang_set ) )}) are not in valid set ({", ".join(__a )}).""" ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. lowerCamelCase = [] for lang, text in translation_dict.items(): if isinstance(__a , __a ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. lowerCamelCase , lowerCamelCase = zip(*sorted(__a ) ) return {"language": languages, "translation": translations} def _a (self ): '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value("string" ) ), "translation": Sequence(Value("string" ) ), }
623
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin a_ : Tuple = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right a_ : Union[str, Any] = 2_5_0_0_0_4 a_ : int = 2_5_0_0_2_0 @require_sentencepiece @require_tokenizers class lowerCamelCase__ ( UpperCAmelCase_ , unittest.TestCase): """simple docstring""" _A = MBartaaTokenizer _A = MBartaaTokenizerFast _A = True _A = True def _a (self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase = MBartaaTokenizer(__a , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=__a ) tokenizer.save_pretrained(self.tmpdirname ) def _a (self ): '''simple docstring''' lowerCamelCase = "<s>" lowerCamelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def _a (self ): '''simple docstring''' lowerCamelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "<mask>" ) self.assertEqual(len(__a ) , 10_54 ) def _a (self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 10_54 ) def _a (self ): '''simple docstring''' lowerCamelCase = MBartaaTokenizer(__a , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=__a ) lowerCamelCase = tokenizer.tokenize("This is a test" ) self.assertListEqual(__a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__a ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) lowerCamelCase = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __a , [SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", "."] , ) lowerCamelCase = tokenizer.convert_tokens_to_ids(__a ) self.assertListEqual( __a , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) lowerCamelCase = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual( __a , [SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", "."] , ) @slow def _a (self ): '''simple docstring''' lowerCamelCase = {"input_ids": [[25_00_04, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [25_00_04, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [25_00_04, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=__a , model_name="facebook/mbart-large-50" , revision="d3913889c59cd5c9e456b269c376325eabad57e2" , ) def _a (self ): '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCamelCase = (self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart50", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowerCamelCase = self.rust_tokenizer_class.from_pretrained(__a , **__a ) lowerCamelCase = self.tokenizer_class.from_pretrained(__a , **__a ) lowerCamelCase = tempfile.mkdtemp() lowerCamelCase = tokenizer_r.save_pretrained(__a ) lowerCamelCase = tokenizer_p.save_pretrained(__a ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) lowerCamelCase = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(__a , __a ) # Checks everything loads correctly in the same way lowerCamelCase = tokenizer_r.from_pretrained(__a ) lowerCamelCase = tokenizer_p.from_pretrained(__a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__a , __a ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__a ) # Save tokenizer rust, legacy_format=True lowerCamelCase = tempfile.mkdtemp() lowerCamelCase = tokenizer_r.save_pretrained(__a , legacy_format=__a ) lowerCamelCase = tokenizer_p.save_pretrained(__a ) # Checks it save with the same files self.assertSequenceEqual(__a , __a ) # Checks everything loads correctly in the same way lowerCamelCase = tokenizer_r.from_pretrained(__a ) lowerCamelCase = tokenizer_p.from_pretrained(__a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__a , __a ) ) shutil.rmtree(__a ) # Save tokenizer rust, legacy_format=False lowerCamelCase = tempfile.mkdtemp() lowerCamelCase = tokenizer_r.save_pretrained(__a , legacy_format=__a ) lowerCamelCase = tokenizer_p.save_pretrained(__a ) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCamelCase = tokenizer_r.from_pretrained(__a ) lowerCamelCase = tokenizer_p.from_pretrained(__a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__a , __a ) ) shutil.rmtree(__a ) @require_torch @require_sentencepiece @require_tokenizers class lowerCamelCase__ ( unittest.TestCase): """simple docstring""" _A = 'facebook/mbart-large-50-one-to-many-mmt' _A = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] _A = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] _A = [EN_CODE, 82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2] @classmethod def _a (cls ): '''simple docstring''' lowerCamelCase = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en_XX" , tgt_lang="ro_RO" ) lowerCamelCase = 1 return cls def _a (self ): '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] , 25_00_01 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] , 25_00_04 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] , 25_00_20 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["mr_IN"] , 25_00_38 ) def _a (self ): '''simple docstring''' lowerCamelCase = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __a ) def _a (self ): '''simple docstring''' self.assertIn(__a , self.tokenizer.all_special_ids ) lowerCamelCase = [RO_CODE, 8_84, 90_19, 96, 9, 9_16, 8_67_92, 36, 1_87_43, 1_55_96, 5, 2] lowerCamelCase = self.tokenizer.decode(__a , skip_special_tokens=__a ) lowerCamelCase = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__a ) self.assertEqual(__a , __a ) self.assertNotIn(self.tokenizer.eos_token , __a ) def _a (self ): '''simple docstring''' lowerCamelCase = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] , __a ) lowerCamelCase = 10 lowerCamelCase = self.tokenizer(__a , max_length=__a , truncation=__a ).input_ids[0] self.assertEqual(ids[0] , __a ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(__a ) , __a ) def _a (self ): '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) , [25_00_53, 25_00_01] ) def _a (self ): '''simple docstring''' lowerCamelCase = tempfile.mkdtemp() lowerCamelCase = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__a ) lowerCamelCase = MBartaaTokenizer.from_pretrained(__a ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __a ) @require_torch def _a (self ): '''simple docstring''' lowerCamelCase = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__a , return_tensors="pt" ) lowerCamelCase = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def _a (self ): '''simple docstring''' lowerCamelCase = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__a , truncation=__a , max_length=len(self.expected_src_tokens ) , return_tensors="pt" , ) lowerCamelCase = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) self.assertIsInstance(__a , __a ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) lowerCamelCase = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __a ) self.assertEqual(2 , batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def _a (self ): '''simple docstring''' lowerCamelCase = self.tokenizer(self.src_text , padding=__a , truncation=__a , max_length=3 , return_tensors="pt" ) lowerCamelCase = self.tokenizer( text_target=self.tgt_text , padding=__a , truncation=__a , max_length=10 , return_tensors="pt" ) lowerCamelCase = targets["input_ids"] lowerCamelCase = shift_tokens_right(__a , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def _a (self ): '''simple docstring''' lowerCamelCase = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(__a ) , { # en_XX, A, test, EOS "input_ids": [[25_00_04, 62, 30_34, 2]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 25_00_01, } , )
623
1
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _lowerCAmelCase ( A__: np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _lowerCAmelCase ( A__: np.ndarray , A__: np.ndarray , A__: int ): '''simple docstring''' UpperCAmelCase = np.nan for i in range(A__ ): UpperCAmelCase = features[:, labels == i] UpperCAmelCase = data.mean(1 ) # Centralize the data of class i UpperCAmelCase = data - column_reshape(A__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(A__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) UpperCAmelCase = np.dot(A__ , centered_data.T ) return covariance_sum / features.shape[1] def _lowerCAmelCase ( A__: np.ndarray , A__: np.ndarray , A__: int ): '''simple docstring''' UpperCAmelCase = features.mean(1 ) UpperCAmelCase = np.nan for i in range(A__ ): UpperCAmelCase = features[:, labels == i] UpperCAmelCase = data.shape[1] UpperCAmelCase = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(A__ ) - column_reshape(A__ ) , (column_reshape(A__ ) - column_reshape(A__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) UpperCAmelCase = device_data * np.dot( column_reshape(A__ ) - column_reshape(A__ ) , (column_reshape(A__ ) - column_reshape(A__ )).T , ) return covariance_sum / features.shape[1] def _lowerCAmelCase ( A__: np.ndarray , A__: int ): '''simple docstring''' if features.any(): UpperCAmelCase = features.mean(1 ) # Center the dataset UpperCAmelCase = features - np.reshape(A__ , (data_mean.size, 1) ) UpperCAmelCase = np.dot(A__ , centered_data.T ) / features.shape[1] UpperCAmelCase , UpperCAmelCase = np.linalg.eigh(A__ ) # Take all the columns in the reverse order (-1), and then takes only the first UpperCAmelCase = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space UpperCAmelCase = np.dot(filtered_eigenvectors.T , A__ ) logging.info('''Principal Component Analysis computed''' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='''%(message)s''' , force=A__ ) logging.error('''Dataset empty''' ) raise AssertionError def _lowerCAmelCase ( A__: np.ndarray , A__: np.ndarray , A__: int , A__: int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: UpperCAmelCase , UpperCAmelCase = eigh( covariance_between_classes(A__ , A__ , A__ ) , covariance_within_classes(A__ , A__ , A__ ) , ) UpperCAmelCase = eigenvectors[:, ::-1][:, :dimensions] UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = np.linalg.svd(A__ ) UpperCAmelCase = svd_matrix[:, 0:dimensions] UpperCAmelCase = np.dot(filtered_svd_matrix.T , A__ ) logging.info('''Linear Discriminant Analysis computed''' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='''%(message)s''' , force=A__ ) logging.error('''Dataset empty''' ) raise AssertionError def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) UpperCAmelCase = np.array([0, 0, 0, 1, 1] ) UpperCAmelCase = 2 UpperCAmelCase = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(A__ ) as error_info: UpperCAmelCase = linear_discriminant_analysis( A__ , A__ , A__ , A__ ) if isinstance(A__ , np.ndarray ): raise AssertionError( '''Did not raise AssertionError for dimensions > classes''' ) assert error_info.type is AssertionError def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) UpperCAmelCase = 2 UpperCAmelCase = np.array([[6.9282_0323, 8.6602_5404, 10.3923_0485], [3.0, 3.0, 3.0]] ) with pytest.raises(A__ ) as error_info: UpperCAmelCase = principal_component_analysis(A__ , A__ ) if not np.allclose(A__ , A__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
707
def _lowerCAmelCase ( A__: int , A__: int ): '''simple docstring''' if number < 0 or shift_amount < 0: raise ValueError('''both inputs must be positive integers''' ) UpperCAmelCase = str(bin(A__ ) ) binary_number += "0" * shift_amount return binary_number def _lowerCAmelCase ( A__: int , A__: int ): '''simple docstring''' if number < 0 or shift_amount < 0: raise ValueError('''both inputs must be positive integers''' ) UpperCAmelCase = str(bin(A__ ) )[2:] if shift_amount >= len(A__ ): return "0b0" UpperCAmelCase = binary_number[: len(A__ ) - shift_amount] return "0b" + shifted_binary_number def _lowerCAmelCase ( A__: int , A__: int ): '''simple docstring''' if number >= 0: # Get binary representation of positive number UpperCAmelCase = '''0''' + str(bin(A__ ) ).strip('''-''' )[2:] else: # Get binary (2's complement) representation of negative number UpperCAmelCase = len(bin(A__ )[3:] ) # Find 2's complement of number UpperCAmelCase = bin(abs(A__ ) - (1 << binary_number_length) )[3:] UpperCAmelCase = ( '''1''' + '''0''' * (binary_number_length - len(A__ )) + binary_number ) if shift_amount >= len(A__ ): return "0b" + binary_number[0] * len(A__ ) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(A__ ) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
391
0
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_barthez import BarthezTokenizer else: lowerCAmelCase__ : Any = None lowerCAmelCase__ : str = logging.get_logger(__name__) lowerCAmelCase__ : int = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} lowerCAmelCase__ : Union[str, Any] = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, """tokenizer_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json""" ), }, } lowerCAmelCase__ : int = { """moussaKam/mbarthez""": 1024, """moussaKam/barthez""": 1024, """moussaKam/barthez-orangesum-title""": 1024, } lowerCAmelCase__ : int = """▁""" class a ( SCREAMING_SNAKE_CASE ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ["""input_ids""", """attention_mask"""] __UpperCAmelCase = BarthezTokenizer def __init__( self : Optional[int] , snake_case_ : Any=None , snake_case_ : Union[str, Any]=None , snake_case_ : List[Any]="<s>" , snake_case_ : Tuple="</s>" , snake_case_ : List[Any]="</s>" , snake_case_ : List[Any]="<s>" , snake_case_ : str="<unk>" , snake_case_ : List[Any]="<pad>" , snake_case_ : Any="<mask>" , **snake_case_ : Dict , ): '''simple docstring''' snake_case__ : str = AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else mask_token super().__init__( snake_case_ , tokenizer_file=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , unk_token=snake_case_ , sep_token=snake_case_ , cls_token=snake_case_ , pad_token=snake_case_ , mask_token=snake_case_ , **snake_case_ , ) snake_case__ : str = vocab_file snake_case__ : Dict = False if not self.vocab_file else True def __magic_name__ ( self : List[str] , snake_case_ : List[int] , snake_case_ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case__ : Any = [self.cls_token_id] snake_case__ : Tuple = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __magic_name__ ( self : Dict , snake_case_ : List[int] , snake_case_ : Optional[List[int]] = None ): '''simple docstring''' snake_case__ : List[str] = [self.sep_token_id] snake_case__ : Optional[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 __magic_name__ ( self : int , snake_case_ : str , snake_case_ : Optional[str] = None ): '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(snake_case_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case__ : Optional[int] = os.path.join( snake_case_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ): copyfile(self.vocab_file , snake_case_ ) return (out_vocab_file,)
347
'''simple docstring''' from ..utils import DummyObject, requires_backends class a ( metaclass=SCREAMING_SNAKE_CASE ): """simple docstring""" __UpperCAmelCase = ["""transformers""", """torch""", """note_seq"""] def __init__( self : Dict , *snake_case_ : Any , **snake_case_ : List[Any] ): '''simple docstring''' requires_backends(self , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def __magic_name__ ( cls : Optional[int] , *snake_case_ : Union[str, Any] , **snake_case_ : List[Any] ): '''simple docstring''' requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def __magic_name__ ( cls : List[Any] , *snake_case_ : Any , **snake_case_ : int ): '''simple docstring''' requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] )
347
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor UpperCAmelCase__ =logging.get_logger(__name__) class lowerCamelCase__ ( lowercase__ ): def __init__( self : Tuple , *A_ : List[Any] , **A_ : Union[str, Any] ): '''simple docstring''' warnings.warn( """The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use DeiTImageProcessor instead.""" , UpperCAmelCase__ , ) super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ )
700
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) UpperCAmelCase__ =logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase__ =argparse.ArgumentParser( description="Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)" ) parser.add_argument( "--data_file", type=str, default="data/dump.bert-base-uncased.pickle", help="The binarized dataset." ) parser.add_argument( "--token_counts_dump", type=str, default="data/token_counts.bert-base-uncased.pickle", help="The dump file." ) parser.add_argument("--vocab_size", default=3_0522, type=int) UpperCAmelCase__ =parser.parse_args() logger.info(f"""Loading data from {args.data_file}""") with open(args.data_file, "rb") as fp: UpperCAmelCase__ =pickle.load(fp) logger.info("Counting occurrences for MLM.") UpperCAmelCase__ =Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase__ =[0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase__ =v logger.info(f"""Dump to {args.token_counts_dump}""") with open(args.token_counts_dump, "wb") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
442
0
from __future__ import annotations def lowerCamelCase__ ( _lowercase , _lowercase = None ): '''simple docstring''' UpperCAmelCase_ : int = word_bank or [] # create a table UpperCAmelCase_ : int = len(SCREAMING_SNAKE_CASE_ ) + 1 UpperCAmelCase_ : List[str] = [] for _ in range(SCREAMING_SNAKE_CASE_ ): table.append([] ) # seed value UpperCAmelCase_ : List[str] = [[]] # because empty string has empty combination # iterate through the indices for i in range(SCREAMING_SNAKE_CASE_ ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(SCREAMING_SNAKE_CASE_ )] == word: UpperCAmelCase_ : Tuple = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(SCREAMING_SNAKE_CASE_ )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(SCREAMING_SNAKE_CASE_ )]: combination.reverse() return table[len(SCREAMING_SNAKE_CASE_ )] if __name__ == "__main__": print(all_construct('jwajalapa', ['jwa', 'j', 'w', 'a', 'la', 'lapa'])) print(all_construct('rajamati', ['s', 'raj', 'amat', 'raja', 'ma', 'i', 't'])) print( all_construct( 'hexagonosaurus', ['h', 'ex', 'hex', 'ag', 'ago', 'ru', 'auru', 'rus', 'go', 'no', 'o', 's'], ) )
30
import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class UpperCAmelCase : @staticmethod def lowerCamelCase_ ( *__magic_name__ : Optional[Any] , **__magic_name__ : List[Any] ): """simple docstring""" pass def _lowercase ( SCREAMING_SNAKE_CASE_ : Image ): """simple docstring""" UpperCamelCase = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class UpperCAmelCase ( unittest.TestCase ): lowercase = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def lowerCamelCase_ ( self : Tuple , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : Any ): """simple docstring""" UpperCamelCase = DepthEstimationPipeline(model=__magic_name__ , image_processor=__magic_name__ ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def lowerCamelCase_ ( self : Optional[int] , __magic_name__ : List[Any] , __magic_name__ : Optional[int] ): """simple docstring""" UpperCamelCase = depth_estimator("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) self.assertEqual({"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )} , __magic_name__ ) import datasets UpperCamelCase = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) UpperCamelCase = depth_estimator( [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] ) self.assertEqual( [ {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, ] , __magic_name__ , ) @require_tf @unittest.skip("""Depth estimation is not implemented in TF""" ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" pass @slow @require_torch def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = """Intel/dpt-large""" UpperCamelCase = pipeline("""depth-estimation""" , model=__magic_name__ ) UpperCamelCase = depth_estimator("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) UpperCamelCase = hashimage(outputs["""depth"""] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs["""predicted_depth"""].max().item() ) , 29.304 ) self.assertEqual(nested_simplify(outputs["""predicted_depth"""].min().item() ) , 2.662 ) @require_torch def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" self.skipTest("""There is not hf-internal-testing tiny model for either GLPN nor DPT""" )
386
0
# flake8: noqa # Lint as: python3 from typing import Dict, List, Optional, Type from .. import config from ..utils import logging from .formatting import ( ArrowFormatter, CustomFormatter, Formatter, PandasFormatter, PythonFormatter, TensorFormatter, format_table, query_table, ) from .np_formatter import NumpyFormatter _a = logging.get_logger(__name__) _a = {} _a = {} _a = {} def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case = None ,) -> Union[str, Any]: '''simple docstring''' lowerCamelCase__ = aliases if aliases is not None else [] if format_type in _FORMAT_TYPES: logger.warning( F'Overwriting format type \'{format_type}\' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})' ) lowerCamelCase__ = formatter_cls for alias in set(aliases + [format_type] ): if alias in _FORMAT_TYPES_ALIASES: logger.warning( F'Overwriting format type alias \'{alias}\' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})' ) lowerCamelCase__ = format_type def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case = None ) -> List[str]: '''simple docstring''' lowerCamelCase__ = aliases if aliases is not None else [] for alias in set(aliases + [format_type] ): lowerCamelCase__ = unavailable_error # Here we define all the available formatting functions that can be used by `Dataset.set_format` _register_formatter(PythonFormatter, None, aliases=["python"]) _register_formatter(ArrowFormatter, "arrow", aliases=["pa", "pyarrow"]) _register_formatter(NumpyFormatter, "numpy", aliases=["np"]) _register_formatter(PandasFormatter, "pandas", aliases=["pd"]) _register_formatter(CustomFormatter, "custom") if config.TORCH_AVAILABLE: from .torch_formatter import TorchFormatter _register_formatter(TorchFormatter, "torch", aliases=["pt", "pytorch"]) else: _a = ValueError("PyTorch needs to be installed to be able to return PyTorch tensors.") _register_unavailable_formatter(_torch_error, "torch", aliases=["pt", "pytorch"]) if config.TF_AVAILABLE: from .tf_formatter import TFFormatter _register_formatter(TFFormatter, "tensorflow", aliases=["tf"]) else: _a = ValueError("Tensorflow needs to be installed to be able to return Tensorflow tensors.") _register_unavailable_formatter(_tf_error, "tensorflow", aliases=["tf"]) if config.JAX_AVAILABLE: from .jax_formatter import JaxFormatter _register_formatter(JaxFormatter, "jax", aliases=[]) else: _a = ValueError("JAX needs to be installed to be able to return JAX arrays.") _register_unavailable_formatter(_jax_error, "jax", aliases=[]) def lowerCAmelCase__(__snake_case ) -> Optional[str]: '''simple docstring''' if format_type in _FORMAT_TYPES_ALIASES: return _FORMAT_TYPES_ALIASES[format_type] else: return format_type def lowerCAmelCase__(__snake_case ,**__snake_case ) -> Formatter: '''simple docstring''' lowerCamelCase__ = get_format_type_from_alias(__snake_case ) if format_type in _FORMAT_TYPES: return _FORMAT_TYPES[format_type](**__snake_case ) if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE: raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type] else: raise ValueError( F'Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None )}, but got \'{format_type}\'' )
714
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging _a = logging.get_logger(__name__) class __A : '''simple docstring''' lowerCAmelCase_ = None @experimental def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) -> Tuple: '''simple docstring''' if ParallelBackendConfig.backend_name is None: return _map_with_multiprocessing_pool( __snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) return _map_with_joblib(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) -> int: '''simple docstring''' lowerCamelCase__ = num_proc if num_proc <= len(__snake_case ) else len(__snake_case ) lowerCamelCase__ = [] # We organize the splits ourselve (contiguous splits) for index in range(__snake_case ): lowerCamelCase__ = len(__snake_case ) // num_proc lowerCamelCase__ = len(__snake_case ) % num_proc lowerCamelCase__ = div * index + min(__snake_case ,__snake_case ) lowerCamelCase__ = start + div + (1 if index < mod else 0) split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc) ) if len(__snake_case ) != sum(len(i[1] ) for i in split_kwds ): raise ValueError( F'Error dividing inputs iterable among processes. ' F'Total number of objects {len(__snake_case )}, ' F'length: {sum(len(i[1] ) for i in split_kwds )}' ) logger.info( F'Spawning {num_proc} processes for {len(__snake_case )} objects in slices of {[len(i[1] ) for i in split_kwds]}' ) lowerCamelCase__ , lowerCamelCase__ = None, None if not disable_tqdm: lowerCamelCase__ , lowerCamelCase__ = (RLock(),), tqdm.set_lock with Pool(__snake_case ,initargs=__snake_case ,initializer=__snake_case ) as pool: lowerCamelCase__ = pool.map(__snake_case ,__snake_case ) logger.info(F'Finished {num_proc} processes' ) lowerCamelCase__ = [obj for proc_res in mapped for obj in proc_res] logger.info(F'Unpacked {len(__snake_case )} objects' ) return mapped def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) -> List[str]: '''simple docstring''' import joblib with joblib.parallel_backend(ParallelBackendConfig.backend_name ,n_jobs=__snake_case ): return joblib.Parallel()( joblib.delayed(__snake_case )((function, obj, types, None, True, None) ) for obj in iterable ) @experimental @contextlib.contextmanager def lowerCAmelCase__(__snake_case ) -> int: '''simple docstring''' lowerCamelCase__ = backend_name if backend_name == "spark": from joblibspark import register_spark register_spark() # TODO: call create_cache_and_write_probe if "download" in steps # TODO: raise NotImplementedError when Dataset.map etc is called try: yield finally: lowerCamelCase__ = None
29
0
import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('''3.8'''): import importlib_metadata else: import importlib.metadata as importlib_metadata def lowerCamelCase__ ( __A :Optional[Any] ,__A :List[str]=False ): """simple docstring""" try: __snake_case = os.environ[key] except KeyError: # KEY isn't set, default to `default`. __snake_case = default else: # KEY is set, convert it to True or False. try: __snake_case = strtobool(__A ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F'If set, {key} must be yes or no.' ) return _value UpperCamelCase__ = parse_flag_from_env('''RUN_SLOW''', default=False) UpperCamelCase__ = parse_flag_from_env('''RUN_REMOTE''', default=False) UpperCamelCase__ = parse_flag_from_env('''RUN_LOCAL''', default=True) UpperCamelCase__ = parse_flag_from_env('''RUN_PACKAGED''', default=True) # Compression UpperCamelCase__ = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''') UpperCamelCase__ = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''') UpperCamelCase__ = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''') # Audio UpperCamelCase__ = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('''soundfile''') is None or version.parse(importlib_metadata.version('''soundfile''')) < version.parse('''0.12.0'''), reason='''test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ''', ) # Beam UpperCamelCase__ = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('''0.3.2'''), reason='''test requires apache-beam and a compatible dill version''', ) # Dill-cloudpickle compatibility UpperCamelCase__ = pytest.mark.skipif( config.DILL_VERSION <= version.parse('''0.3.2'''), reason='''test requires dill>0.3.2 for cloudpickle compatibility''', ) # Windows UpperCamelCase__ = pytest.mark.skipif( sys.platform == '''win32''', reason='''test should not be run on Windows''', ) def lowerCamelCase__ ( __A :Optional[int] ): """simple docstring""" try: import faiss # noqa except ImportError: __snake_case = unittest.skip("""test requires faiss""" )(__A ) return test_case def lowerCamelCase__ ( __A :Tuple ): """simple docstring""" try: import regex # noqa except ImportError: __snake_case = unittest.skip("""test requires regex""" )(__A ) return test_case def lowerCamelCase__ ( __A :Optional[int] ): """simple docstring""" try: import elasticsearch # noqa except ImportError: __snake_case = unittest.skip("""test requires elasticsearch""" )(__A ) return test_case def lowerCamelCase__ ( __A :Union[str, Any] ): """simple docstring""" try: import sqlalchemy # noqa except ImportError: __snake_case = unittest.skip("""test requires sqlalchemy""" )(__A ) return test_case def lowerCamelCase__ ( __A :Dict ): """simple docstring""" if not config.TORCH_AVAILABLE: __snake_case = unittest.skip("""test requires PyTorch""" )(__A ) return test_case def lowerCamelCase__ ( __A :str ): """simple docstring""" if not config.TF_AVAILABLE: __snake_case = unittest.skip("""test requires TensorFlow""" )(__A ) return test_case def lowerCamelCase__ ( __A :List[str] ): """simple docstring""" if not config.JAX_AVAILABLE: __snake_case = unittest.skip("""test requires JAX""" )(__A ) return test_case def lowerCamelCase__ ( __A :Dict ): """simple docstring""" if not config.PIL_AVAILABLE: __snake_case = unittest.skip("""test requires Pillow""" )(__A ) return test_case def lowerCamelCase__ ( __A :str ): """simple docstring""" try: import transformers # noqa F401 except ImportError: return unittest.skip("""test requires transformers""" )(__A ) else: return test_case def lowerCamelCase__ ( __A :Tuple ): """simple docstring""" try: import tiktoken # noqa F401 except ImportError: return unittest.skip("""test requires tiktoken""" )(__A ) else: return test_case def lowerCamelCase__ ( __A :List[Any] ): """simple docstring""" try: import spacy # noqa F401 except ImportError: return unittest.skip("""test requires spacy""" )(__A ) else: return test_case def lowerCamelCase__ ( __A :Optional[int] ): """simple docstring""" def _require_spacy_model(__A :List[str] ): try: import spacy # noqa F401 spacy.load(__A ) except ImportError: return unittest.skip("""test requires spacy""" )(__A ) except OSError: return unittest.skip("""test requires spacy model '{}'""".format(__A ) )(__A ) else: return test_case return _require_spacy_model def lowerCamelCase__ ( __A :int ): """simple docstring""" try: import pyspark # noqa F401 except ImportError: return unittest.skip("""test requires pyspark""" )(__A ) else: return test_case def lowerCamelCase__ ( __A :Any ): """simple docstring""" try: import joblibspark # noqa F401 except ImportError: return unittest.skip("""test requires joblibspark""" )(__A ) else: return test_case def lowerCamelCase__ ( __A :Optional[Any] ): """simple docstring""" if not _run_slow_tests or _run_slow_tests == 0: __snake_case = unittest.skip("""test is slow""" )(__A ) return test_case def lowerCamelCase__ ( __A :Tuple ): """simple docstring""" if not _run_local_tests or _run_local_tests == 0: __snake_case = unittest.skip("""test is local""" )(__A ) return test_case def lowerCamelCase__ ( __A :List[Any] ): """simple docstring""" if not _run_packaged_tests or _run_packaged_tests == 0: __snake_case = unittest.skip("""test is packaged""" )(__A ) return test_case def lowerCamelCase__ ( __A :Union[str, Any] ): """simple docstring""" if not _run_remote_tests or _run_remote_tests == 0: __snake_case = unittest.skip("""test requires remote""" )(__A ) return test_case def lowerCamelCase__ ( *__A :Any ): """simple docstring""" def decorate(cls :Union[str, Any] ): for name, fn in cls.__dict__.items(): if callable(__A ) and name.startswith("""test""" ): for decorator in decorators: __snake_case = decorator(__A ) setattr(cls ,__A ,__A ) return cls return decorate class __snake_case ( snake_case__ ): """simple docstring""" pass class __snake_case ( snake_case__ ): """simple docstring""" __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 2 @contextmanager def lowerCamelCase__ ( __A :Tuple=OfflineSimulationMode.CONNECTION_FAILS ,__A :int=1e-1_6 ): """simple docstring""" __snake_case = requests.Session().request def timeout_request(__A :List[str] ,__A :Tuple ,__A :List[str] ,**__A :str ): # Change the url to an invalid url so that the connection hangs __snake_case = """https://10.255.255.1""" if kwargs.get("""timeout""" ) is None: raise RequestWouldHangIndefinitelyError( F'Tried a call to {url} in offline mode with no timeout set. Please set a timeout.' ) __snake_case = timeout try: return online_request(__A ,__A ,**__A ) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier __snake_case = url __snake_case = e.args[0] __snake_case = (max_retry_error.args[0].replace("""10.255.255.1""" ,F'OfflineMock[{url}]' ),) __snake_case = (max_retry_error,) raise def raise_connection_error(__A :Dict ,__A :List[str] ,**__A :List[str] ): raise requests.ConnectionError("""Offline mode is enabled.""" ,request=__A ) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("""requests.Session.send""" ,__A ): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("""requests.Session.request""" ,__A ): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("""datasets.config.HF_DATASETS_OFFLINE""" ,__A ): yield else: raise ValueError("""Please use a value from the OfflineSimulationMode enum.""" ) @contextmanager def lowerCamelCase__ ( *__A :Any ,**__A :Optional[int] ): """simple docstring""" __snake_case = str(Path().resolve() ) with tempfile.TemporaryDirectory(*__A ,**__A ) as tmp_dir: try: os.chdir(__A ) yield finally: os.chdir(__A ) @contextmanager def lowerCamelCase__ ( ): """simple docstring""" import gc gc.collect() __snake_case = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def lowerCamelCase__ ( ): """simple docstring""" import gc gc.collect() __snake_case = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def lowerCamelCase__ ( __A :List[str] ,__A :str ): """simple docstring""" return deepcopy(__A ).integers(0 ,1_0_0 ,1_0 ).tolist() == deepcopy(__A ).integers(0 ,1_0_0 ,1_0 ).tolist() def lowerCamelCase__ ( __A :List[str] ): """simple docstring""" import decorator from requests.exceptions import HTTPError def _wrapper(__A :str ,*__A :Optional[int] ,**__A :Any ): try: return func(*__A ,**__A ) except HTTPError as err: if str(__A ).startswith("""500""" ) or str(__A ).startswith("""502""" ): pytest.xfail(str(__A ) ) raise err return decorator.decorator(_wrapper ,__A ) class __snake_case : """simple docstring""" def __init__( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" __snake_case = returncode __snake_case = stdout __snake_case = stderr async def lowerCamelCase__ ( __A :Dict ,__A :Optional[Any] ): """simple docstring""" while True: __snake_case = await stream.readline() if line: callback(__A ) else: break async def lowerCamelCase__ ( __A :Any ,__A :Tuple=None ,__A :Tuple=None ,__A :Optional[int]=None ,__A :Optional[int]=False ,__A :int=False ): """simple docstring""" if echo: print("""\nRunning: """ ,""" """.join(__A ) ) __snake_case = await asyncio.create_subprocess_exec( cmd[0] ,*cmd[1:] ,stdin=__A ,stdout=asyncio.subprocess.PIPE ,stderr=asyncio.subprocess.PIPE ,env=__A ,) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) __snake_case = [] __snake_case = [] def tee(__A :Any ,__A :Any ,__A :Optional[int] ,__A :Optional[Any]="" ): __snake_case = line.decode("""utf-8""" ).rstrip() sink.append(__A ) if not quiet: print(__A ,__A ,file=__A ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout ,lambda __A : tee(__A ,__A ,sys.stdout ,label="""stdout:""" ) ), _read_stream(p.stderr ,lambda __A : tee(__A ,__A ,sys.stderr ,label="""stderr:""" ) ), ] ,timeout=__A ,) return _RunOutput(await p.wait() ,__A ,__A ) def lowerCamelCase__ ( __A :Union[str, Any] ,__A :str=None ,__A :Any=None ,__A :Tuple=1_8_0 ,__A :List[Any]=False ,__A :str=True ): """simple docstring""" __snake_case = asyncio.get_event_loop() __snake_case = loop.run_until_complete( _stream_subprocess(__A ,env=__A ,stdin=__A ,timeout=__A ,quiet=__A ,echo=__A ) ) __snake_case = """ """.join(__A ) if result.returncode > 0: __snake_case = """\n""".join(result.stderr ) raise RuntimeError( F'\'{cmd_str}\' failed with returncode {result.returncode}\n\n' F'The combined stderr from workers follows:\n{stderr}' ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(F'\'{cmd_str}\' produced no output.' ) return result def lowerCamelCase__ ( ): """simple docstring""" __snake_case = os.environ.get("""PYTEST_XDIST_WORKER""" ,"""gw0""" ) __snake_case = re.sub(r"""^gw""" ,"""""" ,__A ,0 ,re.M ) return int(__A ) def lowerCamelCase__ ( ): """simple docstring""" __snake_case = 2_9_5_0_0 __snake_case = pytest_xdist_worker_id() return port + uniq_delta
268
from __future__ import annotations def lowerCamelCase__ ( __A :list[float] ,__A :Union[str, Any] ): """simple docstring""" print(F'Vertex\tShortest Distance from vertex {src}' ) for i, d in enumerate(__A ): print(F'{i}\t\t{d}' ) def lowerCamelCase__ ( __A :list[dict[str, int]] ,__A :list[float] ,__A :int ): """simple docstring""" for j in range(__A ): __snake_case , __snake_case , __snake_case = (graph[j][k] for k in ["""src""", """dst""", """weight"""]) if distance[u] != float("""inf""" ) and distance[u] + w < distance[v]: return True return False def lowerCamelCase__ ( __A :list[dict[str, int]] ,__A :int ,__A :int ,__A :int ): """simple docstring""" __snake_case = [float("""inf""" )] * vertex_count __snake_case = 0.0 for _ in range(vertex_count - 1 ): for j in range(__A ): __snake_case , __snake_case , __snake_case = (graph[j][k] for k in ["""src""", """dst""", """weight"""]) if distance[u] != float("""inf""" ) and distance[u] + w < distance[v]: __snake_case = distance[u] + w __snake_case = check_negative_cycle(__A ,__A ,__A ) if negative_cycle_exists: raise Exception("""Negative cycle found""" ) return distance if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase__ = int(input('''Enter number of vertices: ''').strip()) UpperCamelCase__ = int(input('''Enter number of edges: ''').strip()) UpperCamelCase__ = [{} for _ in range(E)] for i in range(E): print('''Edge ''', i + 1) UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ = ( int(x) for x in input('''Enter source, destination, weight: ''').strip().split(''' ''') ) UpperCamelCase__ = {'''src''': src, '''dst''': dest, '''weight''': weight} UpperCamelCase__ = int(input('''\nEnter shortest path source:''').strip()) UpperCamelCase__ = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
268
1
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys snake_case_ : Optional[Any] = subprocess.check_output('''git merge-base main HEAD'''.split()).decode('''utf-8''') snake_case_ : List[str] = subprocess.check_output(f"""git diff --name-only {fork_point_sha}""".split()).decode('''utf-8''').split() snake_case_ : Tuple = '''|'''.join(sys.argv[1:]) snake_case_ : List[str] = re.compile(Rf"""^({joined_dirs}).*?\.py$""") snake_case_ : Optional[Any] = [x for x in modified_files if regex.match(x)] print(''' '''.join(relevant_modified_files), end='''''')
718
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class A__ ( UpperCamelCase__ , unittest.TestCase ): UpperCAmelCase = ProphetNetTokenizer UpperCAmelCase = False def __UpperCamelCase ( self : List[Any] ) -> int: """simple docstring""" super().setUp() _SCREAMING_SNAKE_CASE =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] _SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __UpperCamelCase ( self : str , _a : Union[str, Any] ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE ='''UNwant\u00E9d,running''' _SCREAMING_SNAKE_CASE ='''unwanted, running''' return input_text, output_text def __UpperCamelCase ( self : Optional[int] ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =self.tokenizer_class(self.vocab_file ) _SCREAMING_SNAKE_CASE =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(_a , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [9, 6, 7, 12, 10, 11] ) def __UpperCamelCase ( self : Tuple ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def __UpperCamelCase ( self : Dict ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =BasicTokenizer(do_lower_case=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __UpperCamelCase ( self : Dict ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =BasicTokenizer(do_lower_case=_a , strip_accents=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def __UpperCamelCase ( self : List[str] ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =BasicTokenizer(do_lower_case=_a , strip_accents=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __UpperCamelCase ( self : Optional[int] ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =BasicTokenizer(do_lower_case=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __UpperCamelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =BasicTokenizer(do_lower_case=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __UpperCamelCase ( self : Dict ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =BasicTokenizer(do_lower_case=_a , strip_accents=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __UpperCamelCase ( self : Optional[Any] ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =BasicTokenizer(do_lower_case=_a , strip_accents=_a ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __UpperCamelCase ( self : List[str] ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =BasicTokenizer(do_lower_case=_a , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def __UpperCamelCase ( self : List[Any] ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] _SCREAMING_SNAKE_CASE ={} for i, token in enumerate(_a ): _SCREAMING_SNAKE_CASE =i _SCREAMING_SNAKE_CASE =WordpieceTokenizer(vocab=_a , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] ) @require_torch def __UpperCamelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) _SCREAMING_SNAKE_CASE =['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] _SCREAMING_SNAKE_CASE =[1037, 2146, 2_0423, 2005, 7680, 7849, 3989, 1012, 102] _SCREAMING_SNAKE_CASE =tokenizer(_a , padding=_a , return_tensors='''pt''' ) self.assertIsInstance(_a , _a ) _SCREAMING_SNAKE_CASE =list(batch.input_ids.numpy()[0] ) self.assertListEqual(_a , _a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def __UpperCamelCase ( self : List[str] ) -> Optional[int]: """simple docstring""" self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def __UpperCamelCase ( self : int ) -> Dict: """simple docstring""" self.assertTrue(_is_control('''\u0005''' ) ) self.assertFalse(_is_control('''A''' ) ) self.assertFalse(_is_control(''' ''' ) ) self.assertFalse(_is_control('''\t''' ) ) self.assertFalse(_is_control('''\r''' ) ) def __UpperCamelCase ( self : List[str] ) -> List[str]: """simple docstring""" self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) @slow def __UpperCamelCase ( self : Tuple ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) _SCREAMING_SNAKE_CASE =tokenizer.encode('''sequence builders''' , add_special_tokens=_a ) _SCREAMING_SNAKE_CASE =tokenizer.encode('''multi-sequence build''' , add_special_tokens=_a ) _SCREAMING_SNAKE_CASE =tokenizer.build_inputs_with_special_tokens(_a ) _SCREAMING_SNAKE_CASE =tokenizer.build_inputs_with_special_tokens(_a , _a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
191
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int = logging.get_logger(__name__) _lowercase : Optional[Any] = { 'naver-clova-ix/donut-base': 'https://huggingface.co/naver-clova-ix/donut-base/resolve/main/config.json', # See all Donut models at https://huggingface.co/models?filter=donut-swin } class _UpperCAmelCase ( _lowerCAmelCase ): a__ : Dict = "donut-swin" a__ : str = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Dict , _lowercase : Union[str, Any]=2_24 , _lowercase : List[Any]=4 , _lowercase : Tuple=3 , _lowercase : Union[str, Any]=96 , _lowercase : Dict=[2, 2, 6, 2] , _lowercase : Optional[int]=[3, 6, 12, 24] , _lowercase : Union[str, Any]=7 , _lowercase : List[str]=4.0 , _lowercase : List[Any]=True , _lowercase : Dict=0.0 , _lowercase : str=0.0 , _lowercase : Union[str, Any]=0.1 , _lowercase : Optional[Any]="gelu" , _lowercase : Optional[Any]=False , _lowercase : List[str]=0.02 , _lowercase : Union[str, Any]=1E-5 , **_lowercase : int , ): super().__init__(**_lowercase ) __UpperCAmelCase = image_size __UpperCAmelCase = patch_size __UpperCAmelCase = num_channels __UpperCAmelCase = embed_dim __UpperCAmelCase = depths __UpperCAmelCase = len(_lowercase ) __UpperCAmelCase = num_heads __UpperCAmelCase = window_size __UpperCAmelCase = mlp_ratio __UpperCAmelCase = qkv_bias __UpperCAmelCase = hidden_dropout_prob __UpperCAmelCase = attention_probs_dropout_prob __UpperCAmelCase = drop_path_rate __UpperCAmelCase = hidden_act __UpperCAmelCase = use_absolute_embeddings __UpperCAmelCase = layer_norm_eps __UpperCAmelCase = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __UpperCAmelCase = int(embed_dim * 2 ** (len(_lowercase ) - 1) )
49
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case__ (A__ , A__ , unittest.TestCase ): """simple docstring""" __lowerCAmelCase :Optional[Any] = StableDiffusionXLImgaImgPipeline __lowerCAmelCase :Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} __lowerCAmelCase :Optional[Any] = PipelineTesterMixin.required_optional_params - {"latents"} __lowerCAmelCase :Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __lowerCAmelCase :Optional[int] = IMAGE_TO_IMAGE_IMAGE_PARAMS __lowerCAmelCase :Optional[int] = IMAGE_TO_IMAGE_IMAGE_PARAMS def SCREAMING_SNAKE_CASE__( self ) -> str: """simple docstring""" torch.manual_seed(0 ) a__ : Optional[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , attention_head_dim=(2, 4) , use_linear_projection=__lowercase , addition_embed_type="""text_time""" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) a__ : List[Any] = EulerDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , steps_offset=1 , beta_schedule="""scaled_linear""" , timestep_spacing="""leading""" , ) torch.manual_seed(0 ) a__ : Tuple = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) a__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act="""gelu""" , projection_dim=3_2 , ) a__ : Optional[int] = CLIPTextModel(__lowercase ) a__ : List[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__lowercase ) a__ : Union[str, Any] = CLIPTextModelWithProjection(__lowercase ) a__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" , local_files_only=__lowercase ) a__ : List[str] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """text_encoder_2""": text_encoder_a, """tokenizer_2""": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase=0 ) -> Tuple: """simple docstring""" a__ : Any = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__lowercase ) ).to(__lowercase ) a__ : Union[str, Any] = image / 2 + 0.5 if str(__lowercase ).startswith("""mps""" ): a__ : Dict = torch.manual_seed(__lowercase ) else: a__ : List[str] = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) a__ : Optional[Any] = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 5.0, """output_type""": """numpy""", """strength""": 0.7_5, } return inputs def SCREAMING_SNAKE_CASE__( self ) -> Tuple: """simple docstring""" a__ : int = """cpu""" # ensure determinism for the device-dependent torch.Generator a__ : Any = self.get_dummy_components() a__ : List[Any] = StableDiffusionXLImgaImgPipeline(**__lowercase ) a__ : List[Any] = sd_pipe.to(__lowercase ) sd_pipe.set_progress_bar_config(disable=__lowercase ) a__ : Dict = self.get_dummy_inputs(__lowercase ) a__ : str = sd_pipe(**__lowercase ).images a__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) a__ : Union[str, Any] = np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def SCREAMING_SNAKE_CASE__( self ) -> int: """simple docstring""" super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def SCREAMING_SNAKE_CASE__( self ) -> Optional[int]: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def SCREAMING_SNAKE_CASE__( self ) -> Optional[int]: """simple docstring""" pass def SCREAMING_SNAKE_CASE__( self ) -> Tuple: """simple docstring""" a__ : Union[str, Any] = self.get_dummy_components() a__ : List[str] = StableDiffusionXLImgaImgPipeline(**__lowercase ) a__ : Optional[int] = sd_pipe.to(__lowercase ) a__ : int = sd_pipe.to(__lowercase ) sd_pipe.set_progress_bar_config(disable=__lowercase ) # forward without prompt embeds a__ : Any = self.get_dummy_inputs(__lowercase ) a__ : Optional[int] = 3 * ["""this is a negative prompt"""] a__ : List[str] = negative_prompt a__ : Any = 3 * [inputs["""prompt"""]] a__ : Union[str, Any] = sd_pipe(**__lowercase ) a__ : Dict = output.images[0, -3:, -3:, -1] # forward with prompt embeds a__ : Optional[Any] = self.get_dummy_inputs(__lowercase ) a__ : Dict = 3 * ["""this is a negative prompt"""] a__ : int = 3 * [inputs.pop("""prompt""" )] ( ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ) : List[Any] = sd_pipe.encode_prompt(__lowercase , negative_prompt=__lowercase ) a__ : Any = sd_pipe( **__lowercase , prompt_embeds=__lowercase , negative_prompt_embeds=__lowercase , pooled_prompt_embeds=__lowercase , negative_pooled_prompt_embeds=__lowercase , ) a__ : Optional[int] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class snake_case__ (unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE__( self ) -> Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase="cpu" , __lowercase=torch.floataa , __lowercase=0 ) -> List[str]: """simple docstring""" a__ : List[Any] = torch.Generator(device=__lowercase ).manual_seed(__lowercase ) a__ : List[Any] = np.random.RandomState(__lowercase ).standard_normal((1, 4, 6_4, 6_4) ) a__ : Dict = torch.from_numpy(__lowercase ).to(device=__lowercase , dtype=__lowercase ) a__ : List[Any] = { """prompt""": """a photograph of an astronaut riding a horse""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def SCREAMING_SNAKE_CASE__( self ) -> int: """simple docstring""" a__ : Optional[int] = DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""" ) pipe.to(__lowercase ) pipe.set_progress_bar_config(disable=__lowercase ) a__ : Any = self.get_inputs(__lowercase ) a__ : List[str] = pipe(**__lowercase ).images a__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) a__ : Any = np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
136
0
import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class A__ : def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=99 , A_=32 , A_=5 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=50 , A_=0.02 , A_=True , A_=None , ): '''simple docstring''' UpperCamelCase : Optional[Any] = parent UpperCamelCase : List[str] = batch_size UpperCamelCase : Optional[int] = seq_length UpperCamelCase : Union[str, Any] = is_training UpperCamelCase : List[Any] = use_input_mask UpperCamelCase : str = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Union[str, Any] = num_attention_heads UpperCamelCase : List[str] = intermediate_size UpperCamelCase : int = hidden_act UpperCamelCase : Union[str, Any] = hidden_dropout_prob UpperCamelCase : List[str] = attention_probs_dropout_prob UpperCamelCase : Tuple = max_position_embeddings UpperCamelCase : List[Any] = initializer_range UpperCamelCase : Union[str, Any] = use_labels UpperCamelCase : str = scope def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : List[str] = None if self.use_input_mask: UpperCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: UpperCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Optional[int] = self.get_config() return config, input_ids, input_mask, token_labels def __UpperCamelCase( self ): '''simple docstring''' return BertGenerationConfig( 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 , is_decoder=A_ , initializer_range=self.initializer_range , ) def __UpperCamelCase( self ): '''simple docstring''' ( UpperCamelCase ) : Dict = self.prepare_config_and_inputs() UpperCamelCase : Optional[Any] = True UpperCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) UpperCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , **A_ , ): '''simple docstring''' UpperCamelCase : Optional[Any] = BertGenerationEncoder(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : List[str] = model(A_ , attention_mask=A_ ) UpperCamelCase : int = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , **A_ , ): '''simple docstring''' UpperCamelCase : str = True UpperCamelCase : Tuple = BertGenerationEncoder(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : Dict = model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , ) UpperCamelCase : Optional[int] = model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , A_ , A_ , **A_ , ): '''simple docstring''' UpperCamelCase : Union[str, Any] = True UpperCamelCase : Tuple = True UpperCamelCase : Optional[int] = BertGenerationDecoder(config=A_ ).to(A_ ).eval() # first forward pass UpperCamelCase : str = model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , use_cache=A_ , ) UpperCamelCase : Dict = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase : Dict = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and UpperCamelCase : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase : Dict = torch.cat([input_mask, next_mask] , dim=-1 ) UpperCamelCase : List[str] = model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , output_hidden_states=A_ , )["hidden_states"][0] UpperCamelCase : Union[str, Any] = model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , past_key_values=A_ , output_hidden_states=A_ , )["hidden_states"][0] # select random slice UpperCamelCase : List[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase : Dict = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A_ , A_ , atol=1e-3 ) ) def __UpperCamelCase( self , A_ , A_ , A_ , A_ , *A_ , ): '''simple docstring''' UpperCamelCase : Any = BertGenerationDecoder(A_ ) model.to(A_ ) model.eval() UpperCamelCase : Union[str, Any] = model(A_ , attention_mask=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.prepare_config_and_inputs() UpperCamelCase : Dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class A__ ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): _UpperCAmelCase :str = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () _UpperCAmelCase :Optional[int] = (BertGenerationDecoder,) if is_torch_available() else () _UpperCAmelCase :List[str] = ( {'feature-extraction': BertGenerationEncoder, 'text-generation': BertGenerationDecoder} if is_torch_available() else {} ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = BertGenerationEncoderTester(self ) UpperCamelCase : Optional[Any] = ConfigTester(self , config_class=A_ , hidden_size=37 ) def __UpperCamelCase( self ): '''simple docstring''' self.config_tester.run_common_tests() def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() UpperCamelCase : Dict = "bert" self.model_tester.create_and_check_model(A_ , A_ , A_ , A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*A_ ) def __UpperCamelCase( self ): '''simple docstring''' ( UpperCamelCase ) : Tuple = self.model_tester.prepare_config_and_inputs_for_decoder() UpperCamelCase : List[str] = None self.model_tester.create_and_check_model_as_decoder( A_ , A_ , A_ , A_ , A_ , A_ , ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*A_ ) @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[Any] = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) self.assertIsNotNone(A_ ) @require_torch class A__ ( unittest.TestCase ): @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) UpperCamelCase : Tuple = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] ) with torch.no_grad(): UpperCamelCase : Union[str, Any] = model(A_ )[0] UpperCamelCase : List[str] = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape , A_ ) UpperCamelCase : int = torch.tensor( [[[0.17_75, 0.00_83, -0.03_21], [1.60_02, 0.12_87, 0.39_12], [2.14_73, 0.57_91, 0.60_66]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , A_ , atol=1e-4 ) ) @require_torch class A__ ( unittest.TestCase ): @slow def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = BertGenerationDecoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) UpperCamelCase : List[Any] = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] ) with torch.no_grad(): UpperCamelCase : int = model(A_ )[0] UpperCamelCase : Optional[int] = torch.Size([1, 8, 5_0358] ) self.assertEqual(output.shape , A_ ) UpperCamelCase : List[Any] = torch.tensor( [[[-0.57_88, -2.59_94, -3.70_54], [0.04_38, 4.79_97, 1.87_95], [1.58_62, 6.64_09, 4.46_38]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , A_ , atol=1e-4 ) )
706
import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , ) -> str: if config_name_or_path is None: UpperCamelCase : Dict = "facebook/rag-token-base" if model_type == "rag_token" else "facebook/rag-sequence-base" if generator_tokenizer_name_or_path is None: UpperCamelCase : Tuple = generator_name_or_path if question_encoder_tokenizer_name_or_path is None: UpperCamelCase : Tuple = question_encoder_name_or_path UpperCamelCase : Any = RagTokenForGeneration if model_type == "rag_token" else RagSequenceForGeneration # Save model. UpperCamelCase : Optional[Any] = RagConfig.from_pretrained(_lowerCAmelCase ) UpperCamelCase : Union[str, Any] = AutoConfig.from_pretrained(_lowerCAmelCase ) UpperCamelCase : Tuple = AutoConfig.from_pretrained(_lowerCAmelCase ) UpperCamelCase : int = gen_config UpperCamelCase : Dict = question_encoder_config UpperCamelCase : Tuple = model_class.from_pretrained_question_encoder_generator( _lowerCAmelCase , _lowerCAmelCase , config=_lowerCAmelCase ) rag_model.save_pretrained(_lowerCAmelCase ) # Sanity check. model_class.from_pretrained(_lowerCAmelCase ) # Save tokenizers. UpperCamelCase : Optional[Any] = AutoTokenizer.from_pretrained(_lowerCAmelCase ) gen_tokenizer.save_pretrained(dest_dir / "generator_tokenizer/" ) UpperCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained(_lowerCAmelCase ) question_encoder_tokenizer.save_pretrained(dest_dir / "question_encoder_tokenizer/" ) if __name__ == "__main__": __lowerCamelCase : Tuple = argparse.ArgumentParser() parser.add_argument( """--model_type""", choices=["""rag_sequence""", """rag_token"""], required=True, type=str, help="""RAG model type: rag_sequence, rag_token""", ) parser.add_argument("""--dest""", type=str, required=True, help="""Path to the output checkpoint directory.""") parser.add_argument("""--generator_name_or_path""", type=str, required=True, help="""Generator model identifier""") parser.add_argument( """--question_encoder_name_or_path""", type=str, required=True, help="""Question encoder model identifier""" ) parser.add_argument( """--generator_tokenizer_name_or_path""", type=str, help="""Generator tokenizer identifier, if not specified, resolves to ``generator_name_or_path``""", ) parser.add_argument( """--question_encoder_tokenizer_name_or_path""", type=str, help="""Question encoder tokenizer identifier, if not specified, resolves to ``question_encoder_name_or_path``""", ) parser.add_argument( """--config_name_or_path""", type=str, help=( """Identifier of the model config to use, if not provided, resolves to a base config for a given""" """ ``model_type``""" ), ) __lowerCamelCase : Dict = parser.parse_args() __lowerCamelCase : Dict = Path(args.dest) dest_dir.mkdir(exist_ok=True) consolidate( args.model_type, args.generator_name_or_path, args.question_encoder_name_or_path, dest_dir, args.config_name_or_path, args.generator_tokenizer_name_or_path, args.question_encoder_tokenizer_name_or_path, )
38
0
"""simple docstring""" import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCAmelCase_ = { 'tiny.en': 'https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt', 'tiny': 'https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt', 'base.en': 'https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt', 'base': 'https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt', 'small.en': 'https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt', 'small': 'https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt', 'medium.en': 'https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt', 'medium': 'https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt', 'large': 'https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt', 'large-v2': 'https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt', } def __UpperCAmelCase ( __lowerCamelCase ) -> str: lowercase__ : Union[str, Any] = ['''layers''', '''blocks'''] for k in ignore_keys: state_dict.pop(__lowerCamelCase , __lowerCamelCase ) lowerCAmelCase_ = { 'blocks': 'layers', 'mlp.0': 'fc1', 'mlp.2': 'fc2', 'mlp_ln': 'final_layer_norm', '.attn.query': '.self_attn.q_proj', '.attn.key': '.self_attn.k_proj', '.attn.value': '.self_attn.v_proj', '.attn_ln': '.self_attn_layer_norm', '.attn.out': '.self_attn.out_proj', '.cross_attn.query': '.encoder_attn.q_proj', '.cross_attn.key': '.encoder_attn.k_proj', '.cross_attn.value': '.encoder_attn.v_proj', '.cross_attn_ln': '.encoder_attn_layer_norm', '.cross_attn.out': '.encoder_attn.out_proj', 'decoder.ln.': 'decoder.layer_norm.', 'encoder.ln.': 'encoder.layer_norm.', 'token_embedding': 'embed_tokens', 'encoder.positional_embedding': 'encoder.embed_positions.weight', 'decoder.positional_embedding': 'decoder.embed_positions.weight', 'ln_post': 'layer_norm', } def __UpperCAmelCase ( __lowerCamelCase ) -> Any: lowercase__ : List[Any] = list(s_dict.keys() ) for key in keys: lowercase__ : Tuple = key for k, v in WHISPER_MAPPING.items(): if k in key: lowercase__ : List[Any] = new_key.replace(__lowerCamelCase , __lowerCamelCase ) print(f"""{key} -> {new_key}""" ) lowercase__ : int = s_dict.pop(__lowerCamelCase ) return s_dict def __UpperCAmelCase ( __lowerCamelCase ) -> str: lowercase__ , lowercase__ : Optional[Any] = emb.weight.shape lowercase__ : Any = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) lowercase__ : Any = emb.weight.data return lin_layer def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> bytes: os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) lowercase__ : str = os.path.basename(__lowerCamelCase ) lowercase__ : Tuple = url.split('''/''' )[-2] lowercase__ : List[str] = os.path.join(__lowerCamelCase , __lowerCamelCase ) if os.path.exists(__lowerCamelCase ) and not os.path.isfile(__lowerCamelCase ): raise RuntimeError(f"""{download_target} exists and is not a regular file""" ) if os.path.isfile(__lowerCamelCase ): lowercase__ : Dict = open(__lowerCamelCase , '''rb''' ).read() if hashlib.shaaaa(__lowerCamelCase ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"""{download_target} exists, but the SHA256 checksum does not match; re-downloading the file""" ) with urllib.request.urlopen(__lowerCamelCase ) as source, open(__lowerCamelCase , '''wb''' ) as output: with tqdm( total=int(source.info().get('''Content-Length''' ) ) , ncols=80 , unit='''iB''' , unit_scale=__lowerCamelCase , unit_divisor=10_24 ) as loop: while True: lowercase__ : Optional[int] = source.read(81_92 ) if not buffer: break output.write(__lowerCamelCase ) loop.update(len(__lowerCamelCase ) ) lowercase__ : List[Any] = open(__lowerCamelCase , '''rb''' ).read() if hashlib.shaaaa(__lowerCamelCase ).hexdigest() != expected_shaaaa: raise RuntimeError( '''Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.''' ) return model_bytes def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase ) -> int: if ".pt" not in checkpoint_path: lowercase__ : Tuple = _download(_MODELS[checkpoint_path] ) else: lowercase__ : Dict = torch.load(__lowerCamelCase , map_location='''cpu''' ) lowercase__ : Tuple = original_checkpoint['''dims'''] lowercase__ : List[str] = original_checkpoint['''model_state_dict'''] lowercase__ : Union[str, Any] = state_dict['''decoder.token_embedding.weight'''] remove_ignore_keys_(__lowerCamelCase ) rename_keys(__lowerCamelCase ) lowercase__ : str = True lowercase__ : Optional[Any] = state_dict['''decoder.layers.0.fc1.weight'''].shape[0] lowercase__ : Optional[int] = WhisperConfig( vocab_size=dimensions['''n_vocab'''] , encoder_ffn_dim=__lowerCamelCase , decoder_ffn_dim=__lowerCamelCase , num_mel_bins=dimensions['''n_mels'''] , d_model=dimensions['''n_audio_state'''] , max_target_positions=dimensions['''n_text_ctx'''] , encoder_layers=dimensions['''n_audio_layer'''] , encoder_attention_heads=dimensions['''n_audio_head'''] , decoder_layers=dimensions['''n_text_layer'''] , decoder_attention_heads=dimensions['''n_text_state'''] , max_source_positions=dimensions['''n_audio_ctx'''] , ) lowercase__ : List[str] = WhisperForConditionalGeneration(__lowerCamelCase ) lowercase__ , lowercase__ : List[Any] = model.model.load_state_dict(__lowerCamelCase , strict=__lowerCamelCase ) if len(__lowerCamelCase ) > 0 and not set(__lowerCamelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' f""" but all the following weights are missing {missing}""" ) if tie_embeds: lowercase__ : Any = make_linear_from_emb(model.model.decoder.embed_tokens ) else: lowercase__ : Any = proj_out_weights model.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Patht to the downloaded checkpoints') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') lowerCAmelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
560
"""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_ = { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class __A ( A_ ): '''simple docstring''' lowerCAmelCase : List[str] = "roformer" def __init__( self : Any ,_snake_case : str=50_000 ,_snake_case : int=None ,_snake_case : int=768 ,_snake_case : Tuple=12 ,_snake_case : Dict=12 ,_snake_case : Dict=3_072 ,_snake_case : Tuple="gelu" ,_snake_case : List[Any]=0.1 ,_snake_case : List[Any]=0.1 ,_snake_case : Optional[Any]=1_536 ,_snake_case : Dict=2 ,_snake_case : Union[str, Any]=0.02 ,_snake_case : Optional[Any]=1e-12 ,_snake_case : Optional[Any]=0 ,_snake_case : Tuple=False ,_snake_case : Optional[int]=True ,**_snake_case : Optional[int] ,) -> Tuple: """simple docstring""" super().__init__(pad_token_id=_snake_case ,**_snake_case ) lowercase__ : Optional[int] = vocab_size lowercase__ : int = hidden_size if embedding_size is None else embedding_size lowercase__ : Union[str, Any] = hidden_size lowercase__ : Any = num_hidden_layers lowercase__ : Union[str, Any] = num_attention_heads lowercase__ : str = hidden_act lowercase__ : Union[str, Any] = intermediate_size lowercase__ : Dict = hidden_dropout_prob lowercase__ : Optional[Any] = attention_probs_dropout_prob lowercase__ : List[Any] = max_position_embeddings lowercase__ : List[str] = type_vocab_size lowercase__ : Optional[int] = initializer_range lowercase__ : List[Any] = layer_norm_eps lowercase__ : Optional[Any] = rotary_value lowercase__ : Optional[int] = use_cache class __A ( A_ ): '''simple docstring''' @property def UpperCAmelCase ( self : Any ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": lowercase__ : Union[str, Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowercase__ : List[Any] = {0: '''batch''', 1: '''sequence'''} lowercase__ : Optional[Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
560
1
'''simple docstring''' def __lowercase ( __SCREAMING_SNAKE_CASE ) -> set: """simple docstring""" __a = set() # edges = list of graph's edges __a = get_edges(__SCREAMING_SNAKE_CASE ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: __a , __a = edges.pop() chosen_vertices.add(__SCREAMING_SNAKE_CASE ) chosen_vertices.add(__SCREAMING_SNAKE_CASE ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(__SCREAMING_SNAKE_CASE ) return chosen_vertices def __lowercase ( __SCREAMING_SNAKE_CASE ) -> set: """simple docstring""" __a = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
201
'''simple docstring''' from ...processing_utils import ProcessorMixin class lowerCAmelCase_ ( snake_case__ ): """simple docstring""" a_ :Dict =["""image_processor""", """feature_extractor"""] a_ :str ="""TvltImageProcessor""" a_ :str ="""TvltFeatureExtractor""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' super().__init__(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) __a = image_processor __a = feature_extractor def __call__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : List[str]=False , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] , ): '''simple docstring''' if images is None and audio is None: raise ValueError("""You need to specify either an `images` or `audio` input to process.""" ) __a = None if images is not None: __a = self.image_processor(SCREAMING_SNAKE_CASE__ , mask_pixel=SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if images_mixed is not None: __a = self.image_processor(SCREAMING_SNAKE_CASE__ , is_mixed=SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if audio is not None: __a = self.feature_extractor( SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , sampling_rate=SCREAMING_SNAKE_CASE__ , mask_audio=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __a = {} if audio is not None: output_dict.update(SCREAMING_SNAKE_CASE__ ) if images is not None: output_dict.update(SCREAMING_SNAKE_CASE__ ) if images_mixed_dict is not None: output_dict.update(SCREAMING_SNAKE_CASE__ ) return output_dict @property def __a ( self : List[str] ): '''simple docstring''' __a = self.image_processor.model_input_names __a = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
201
1
import qiskit def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : int ): __UpperCAmelCase : Optional[int] = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum Circuit acting on the q register __UpperCAmelCase : Optional[Any] = qiskit.QuantumCircuit(__lowerCamelCase , __lowerCamelCase ) # Apply X (NOT) Gate to Qubits 0 & 1 circuit.x(0 ) circuit.x(1 ) # Map the quantum measurement to the classical bits circuit.measure([0, 1] , [0, 1] ) # Execute the circuit on the qasm simulator __UpperCAmelCase : str = qiskit.execute(__lowerCamelCase , __lowerCamelCase , shots=1000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(__lowerCamelCase ) if __name__ == "__main__": a : List[str] = single_qubit_measure(2, 2) print(f"""Total count for various states are: {counts}""")
63
"""simple docstring""" import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder _snake_case = 'base_with_context' def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Any = nn.Parameter(torch.FloatTensor(weights["""token_embedder"""]["""embedding"""] ) ) _a : Tuple = nn.Parameter( torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) , requires_grad=UpperCamelCase__ ) for lyr_num, lyr in enumerate(model.encoders ): _a : str = weights[F"""layers_{lyr_num}"""] _a : Optional[Any] = nn.Parameter( torch.FloatTensor(ly_weight["""pre_attention_layer_norm"""]["""scale"""] ) ) _a : List[str] = ly_weight["""attention"""] _a : Any = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) _a : int = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) _a : str = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) _a : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) _a : List[str] = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) ) _a : Any = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) ) _a : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) ) _a : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) ) _a : str = nn.Parameter(torch.FloatTensor(weights["""encoder_norm"""]["""scale"""] ) ) return model def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = nn.Parameter(torch.FloatTensor(weights["""input_proj"""]["""kernel"""].T ) ) _a : List[str] = nn.Parameter( torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) , requires_grad=UpperCamelCase__ ) for lyr_num, lyr in enumerate(model.encoders ): _a : Union[str, Any] = weights[F"""layers_{lyr_num}"""] _a : Optional[Any] = ly_weight["""attention"""] _a : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) _a : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) _a : str = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) _a : Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) _a : List[Any] = nn.Parameter( torch.FloatTensor(ly_weight["""pre_attention_layer_norm"""]["""scale"""] ) ) _a : List[str] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) ) _a : int = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) ) _a : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) ) _a : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) ) _a : Any = nn.Parameter(torch.FloatTensor(weights["""encoder_norm"""]["""scale"""] ) ) return model def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a : Dict = nn.Parameter(torch.FloatTensor(weights["""time_emb_dense0"""]["""kernel"""].T ) ) _a : int = nn.Parameter(torch.FloatTensor(weights["""time_emb_dense1"""]["""kernel"""].T ) ) _a : Optional[int] = nn.Parameter( torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) , requires_grad=UpperCamelCase__ ) _a : str = nn.Parameter( torch.FloatTensor(weights["""continuous_inputs_projection"""]["""kernel"""].T ) ) for lyr_num, lyr in enumerate(model.decoders ): _a : Tuple = weights[F"""layers_{lyr_num}"""] _a : Tuple = nn.Parameter( torch.FloatTensor(ly_weight["""pre_self_attention_layer_norm"""]["""scale"""] ) ) _a : Tuple = nn.Parameter( torch.FloatTensor(ly_weight["""FiLMLayer_0"""]["""DenseGeneral_0"""]["""kernel"""].T ) ) _a : Tuple = ly_weight["""self_attention"""] _a : Any = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) _a : Any = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) _a : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) _a : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) _a : Optional[int] = ly_weight["""MultiHeadDotProductAttention_0"""] _a : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) ) _a : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) ) _a : Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) ) _a : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) ) _a : str = nn.Parameter( torch.FloatTensor(ly_weight["""pre_cross_attention_layer_norm"""]["""scale"""] ) ) _a : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) ) _a : List[Any] = nn.Parameter( torch.FloatTensor(ly_weight["""FiLMLayer_1"""]["""DenseGeneral_0"""]["""kernel"""].T ) ) _a : List[str] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) ) _a : str = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) ) _a : List[str] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) ) _a : Tuple = nn.Parameter(torch.FloatTensor(weights["""decoder_norm"""]["""scale"""] ) ) _a : List[Any] = nn.Parameter(torch.FloatTensor(weights["""spec_out_dense"""]["""kernel"""].T ) ) return model def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' _a : Union[str, Any] = checkpoints.load_tax_checkpoint(args.checkpoint_path ) _a : str = jnp.tree_util.tree_map(onp.array , UpperCamelCase__ ) _a : Optional[Any] = [ """from __gin__ import dynamic_registration""", """from music_spectrogram_diffusion.models.diffusion import diffusion_utils""", """diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0""", """diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()""", ] _a : Any = os.path.join(args.checkpoint_path , """..""" , """config.gin""" ) _a : List[Any] = inference.parse_training_gin_file(UpperCamelCase__ , UpperCamelCase__ ) _a : List[Any] = inference.InferenceModel(args.checkpoint_path , UpperCamelCase__ ) _a : Optional[Any] = DDPMScheduler(beta_schedule="""squaredcos_cap_v2""" , variance_type="""fixed_large""" ) _a : Dict = SpectrogramNotesEncoder( max_length=synth_model.sequence_length["""inputs"""] , vocab_size=synth_model.model.module.config.vocab_size , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="""gated-gelu""" , ) _a : List[str] = SpectrogramContEncoder( input_dims=synth_model.audio_codec.n_dims , targets_context_length=synth_model.sequence_length["""targets_context"""] , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="""gated-gelu""" , ) _a : List[str] = TaFilmDecoder( input_dims=synth_model.audio_codec.n_dims , targets_length=synth_model.sequence_length["""targets_context"""] , max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time , d_model=synth_model.model.module.config.emb_dim , num_layers=synth_model.model.module.config.num_decoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , dropout_rate=synth_model.model.module.config.dropout_rate , ) _a : Optional[int] = load_notes_encoder(ta_checkpoint["""target"""]["""token_encoder"""] , UpperCamelCase__ ) _a : Tuple = load_continuous_encoder(ta_checkpoint["""target"""]["""continuous_encoder"""] , UpperCamelCase__ ) _a : Any = load_decoder(ta_checkpoint["""target"""]["""decoder"""] , UpperCamelCase__ ) _a : Dict = OnnxRuntimeModel.from_pretrained("""kashif/soundstream_mel_decoder""" ) _a : List[str] = SpectrogramDiffusionPipeline( notes_encoder=UpperCamelCase__ , continuous_encoder=UpperCamelCase__ , decoder=UpperCamelCase__ , scheduler=UpperCamelCase__ , melgan=UpperCamelCase__ , ) if args.save: pipe.save_pretrained(args.output_path ) if __name__ == "__main__": _snake_case = argparse.ArgumentParser() parser.add_argument('--output_path', default=None, type=str, required=True, help='Path to the converted model.') parser.add_argument( '--save', default=True, type=bool, required=False, help='Whether to save the converted model or not.' ) parser.add_argument( '--checkpoint_path', default=F'''{MODEL}/checkpoint_500000''', type=str, required=False, help='Path to the original jax model checkpoint.', ) _snake_case = parser.parse_args() main(args)
389
0
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=__lowerCamelCase ) class a ( __lowerCamelCase ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization __lowerCAmelCase : str = field(default="""summarization""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) __lowerCAmelCase : ClassVar[Features] = Features({"""text""": Value("""string""" )} ) __lowerCAmelCase : ClassVar[Features] = Features({"""summary""": Value("""string""" )} ) __lowerCAmelCase : str = "text" __lowerCAmelCase : str = "summary" @property def __lowerCamelCase ( self :Dict ): return {self.text_column: "text", self.summary_column: "summary"}
219
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging A__ = logging.get_logger(__name__) if is_vision_available(): import PIL class a ( __lowerCamelCase ): __lowerCAmelCase : Optional[int] = ["""pixel_values"""] def __init__( self :Union[str, Any] ,__lowercase :bool = True ,__lowercase :Dict[str, int] = None ,__lowercase :PILImageResampling = PILImageResampling.BICUBIC ,__lowercase :bool = True ,__lowercase :Dict[str, int] = None ,__lowercase :bool = True ,__lowercase :Union[int, float] = 1 / 2_5_5 ,__lowercase :bool = True ,__lowercase :Optional[Union[float, List[float]]] = None ,__lowercase :Optional[Union[float, List[float]]] = None ,__lowercase :bool = True ,**__lowercase :Tuple ,): super().__init__(**__lowercase ) snake_case__ : Optional[int] = size if size is not None else {'''shortest_edge''': 2_2_4} snake_case__ : Dict = get_size_dict(__lowercase ,default_to_square=__lowercase ) snake_case__ : List[Any] = crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4} snake_case__ : str = get_size_dict(__lowercase ,default_to_square=__lowercase ,param_name='''crop_size''' ) snake_case__ : Dict = do_resize snake_case__ : List[str] = size snake_case__ : Union[str, Any] = resample snake_case__ : str = do_center_crop snake_case__ : List[str] = crop_size snake_case__ : str = do_rescale snake_case__ : Dict = rescale_factor snake_case__ : Tuple = do_normalize snake_case__ : List[str] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN snake_case__ : str = image_std if image_std is not None else OPENAI_CLIP_STD snake_case__ : Optional[Any] = do_convert_rgb def __lowerCamelCase ( self :List[Any] ,__lowercase :np.ndarray ,__lowercase :Dict[str, int] ,__lowercase :PILImageResampling = PILImageResampling.BICUBIC ,__lowercase :Optional[Union[str, ChannelDimension]] = None ,**__lowercase :Optional[int] ,): snake_case__ : Optional[Any] = get_size_dict(__lowercase ,default_to_square=__lowercase ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) snake_case__ : Any = get_resize_output_image_size(__lowercase ,size=size['''shortest_edge'''] ,default_to_square=__lowercase ) return resize(__lowercase ,size=__lowercase ,resample=__lowercase ,data_format=__lowercase ,**__lowercase ) def __lowerCamelCase ( self :Tuple ,__lowercase :np.ndarray ,__lowercase :Dict[str, int] ,__lowercase :Optional[Union[str, ChannelDimension]] = None ,**__lowercase :Optional[Any] ,): snake_case__ : Optional[Any] = get_size_dict(__lowercase ) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(__lowercase ,size=(size['''height'''], size['''width''']) ,data_format=__lowercase ,**__lowercase ) def __lowerCamelCase ( self :Dict ,__lowercase :np.ndarray ,__lowercase :Union[int, float] ,__lowercase :Optional[Union[str, ChannelDimension]] = None ,**__lowercase :Dict ,): return rescale(__lowercase ,scale=__lowercase ,data_format=__lowercase ,**__lowercase ) def __lowerCamelCase ( self :int ,__lowercase :np.ndarray ,__lowercase :Union[float, List[float]] ,__lowercase :Union[float, List[float]] ,__lowercase :Optional[Union[str, ChannelDimension]] = None ,**__lowercase :List[str] ,): return normalize(__lowercase ,mean=__lowercase ,std=__lowercase ,data_format=__lowercase ,**__lowercase ) def __lowerCamelCase ( self :Dict ,__lowercase :ImageInput ,__lowercase :bool = None ,__lowercase :Dict[str, int] = None ,__lowercase :PILImageResampling = None ,__lowercase :bool = None ,__lowercase :int = None ,__lowercase :bool = None ,__lowercase :float = None ,__lowercase :bool = None ,__lowercase :Optional[Union[float, List[float]]] = None ,__lowercase :Optional[Union[float, List[float]]] = None ,__lowercase :bool = None ,__lowercase :Optional[Union[str, TensorType]] = None ,__lowercase :Optional[ChannelDimension] = ChannelDimension.FIRST ,**__lowercase :int ,): snake_case__ : Dict = do_resize if do_resize is not None else self.do_resize snake_case__ : Union[str, Any] = size if size is not None else self.size snake_case__ : Any = get_size_dict(__lowercase ,param_name='''size''' ,default_to_square=__lowercase ) snake_case__ : int = resample if resample is not None else self.resample snake_case__ : Tuple = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case__ : List[Any] = crop_size if crop_size is not None else self.crop_size snake_case__ : Union[str, Any] = get_size_dict(__lowercase ,param_name='''crop_size''' ,default_to_square=__lowercase ) snake_case__ : Any = do_rescale if do_rescale is not None else self.do_rescale snake_case__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case__ : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize snake_case__ : List[Any] = image_mean if image_mean is not None else self.image_mean snake_case__ : Optional[int] = image_std if image_std is not None else self.image_std snake_case__ : Optional[int] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb snake_case__ : Dict = make_list_of_images(__lowercase ) if not valid_images(__lowercase ): 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.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: snake_case__ : str = [convert_to_rgb(__lowercase ) for image in images] # All transformations expect numpy arrays. snake_case__ : Tuple = [to_numpy_array(__lowercase ) for image in images] if do_resize: snake_case__ : List[str] = [self.resize(image=__lowercase ,size=__lowercase ,resample=__lowercase ) for image in images] if do_center_crop: snake_case__ : str = [self.center_crop(image=__lowercase ,size=__lowercase ) for image in images] if do_rescale: snake_case__ : List[Any] = [self.rescale(image=__lowercase ,scale=__lowercase ) for image in images] if do_normalize: snake_case__ : Tuple = [self.normalize(image=__lowercase ,mean=__lowercase ,std=__lowercase ) for image in images] snake_case__ : Dict = [to_channel_dimension_format(__lowercase ,__lowercase ) for image in images] snake_case__ : List[Any] = {'''pixel_values''': images} return BatchFeature(data=__lowercase ,tensor_type=__lowercase )
219
1
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset from utils import logger class _UpperCAmelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' a_ : Any = params a_ : Dict = np.array(lowerCAmelCase_ ) a_ : str = np.array([len(lowerCAmelCase_ ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , lowerCAmelCase_ ): '''simple docstring''' return (self.token_ids[index], self.lengths[index]) def __len__( self ): '''simple docstring''' return len(self.lengths ) def _lowerCAmelCase ( self ): '''simple docstring''' assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def _lowerCAmelCase ( self ): '''simple docstring''' a_ : Union[str, Any] = self.params.max_model_input_size a_ : Optional[int] = self.lengths > max_len logger.info(f'''Splitting {sum(lowerCAmelCase_ )} too long sequences.''' ) def divide_chunks(lowerCAmelCase_ , lowerCAmelCase_ ): return [l[i : i + n] for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ )] a_ : List[Any] = [] a_ : Optional[Any] = [] if self.params.mlm: a_ , a_ : str = self.params.special_tok_ids["""cls_token"""], self.params.special_tok_ids["""sep_token"""] else: a_ , a_ : Dict = self.params.special_tok_ids["""bos_token"""], self.params.special_tok_ids["""eos_token"""] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: a_ : Any = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: a_ : Tuple = np.insert(lowerCAmelCase_ , 0 , lowerCAmelCase_ ) if sub_s[-1] != sep_id: a_ : Union[str, Any] = np.insert(lowerCAmelCase_ , len(lowerCAmelCase_ ) , lowerCAmelCase_ ) assert len(lowerCAmelCase_ ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(lowerCAmelCase_ ) new_tok_ids.extend(lowerCAmelCase_ ) new_lengths.extend([len(lowerCAmelCase_ ) for l in sub_seqs] ) a_ : Tuple = np.array(lowerCAmelCase_ ) a_ : str = np.array(lowerCAmelCase_ ) def _lowerCAmelCase ( self ): '''simple docstring''' a_ : Any = len(self ) a_ : Dict = self.lengths > 11 a_ : Union[str, Any] = self.token_ids[indices] a_ : Any = self.lengths[indices] a_ : Union[str, Any] = len(self ) logger.info(f'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def _lowerCAmelCase ( self ): '''simple docstring''' if "unk_token" not in self.params.special_tok_ids: return else: a_ : Optional[int] = self.params.special_tok_ids["""unk_token"""] a_ : List[str] = len(self ) a_ : List[str] = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) a_ : Dict = (unk_occs / self.lengths) < 0.5 a_ : Optional[int] = self.token_ids[indices] a_ : Union[str, Any] = self.lengths[indices] a_ : Union[str, Any] = len(self ) logger.info(f'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def _lowerCAmelCase ( self ): '''simple docstring''' if not self.params.is_master: return logger.info(f'''{len(self )} sequences''' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def _lowerCAmelCase ( self , lowerCAmelCase_ ): '''simple docstring''' a_ : Tuple = [t[0] for t in batch] a_ : Dict = [t[1] for t in batch] assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) # Max for paddings a_ : int = max(lowerCAmelCase_ ) # Pad token ids if self.params.mlm: a_ : Union[str, Any] = self.params.special_tok_ids["""pad_token"""] else: a_ : int = self.params.special_tok_ids["""unk_token"""] a_ : List[Any] = [list(t.astype(lowerCAmelCase_ ) ) + [pad_idx] * (max_seq_len_ - len(lowerCAmelCase_ )) for t in token_ids] assert len(tk_ ) == len(lowerCAmelCase_ ) assert all(len(lowerCAmelCase_ ) == max_seq_len_ for t in tk_ ) a_ : Any = torch.tensor(tk_ ) # (bs, max_seq_len_) a_ : Any = torch.tensor(lowerCAmelCase_ ) # (bs) return tk_t, lg_t
577
'''simple docstring''' def _snake_case ( A_ : Optional[int] ): """simple docstring""" a_ : str = len(A_ ) for i in range(length - 1 ): a_ : List[Any] = i for k in range(i + 1 , A_ ): if collection[k] < collection[least]: a_ : Union[str, Any] = k if least != i: a_ , a_ : int = (collection[i], collection[least]) return collection if __name__ == "__main__": __snake_case: Union[str, Any] = input("Enter numbers separated by a comma:\n").strip() __snake_case: Any = [int(item) for item in user_input.split(",")] print(selection_sort(unsorted))
577
1
import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class lowerCAmelCase_ ( A_ ,unittest.TestCase ): '''simple docstring''' A_ : Tuple = CpmAntTokenizer A_ : Optional[int] = False def _A ( self ): '''simple docstring''' super().setUp() a__ = [ """<d>""", """</d>""", """<s>""", """</s>""", """</_>""", """<unk>""", """<pad>""", """</n>""", """我""", """是""", """C""", """P""", """M""", """A""", """n""", """t""", ] a__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) @tooslow def _A ( self ): '''simple docstring''' a__ = CpmAntTokenizer.from_pretrained("""openbmb/cpm-ant-10b""" ) a__ = """今天天气真好!""" a__ = ["""今天""", """天气""", """真""", """好""", """!"""] a__ = tokenizer.tokenize(lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) a__ = """今天天气真好!""" a__ = [tokenizer.bos_token] + tokens a__ = [6, 9802, 1_4962, 2082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase ) , lowerCamelCase ) a__ = tokenizer.decode(lowerCamelCase ) self.assertEqual(lowerCamelCase , lowerCamelCase )
412
import operator as op def UpperCAmelCase ( lowercase__ : str ): '''simple docstring''' a__ = [] a__ = lambda lowercase__ , lowercase__ : int(x / y ) # noqa: E731 integer division operation a__ = { """^""": op.pow, """*""": op.mul, """/""": div, """+""": op.add, """-""": op.sub, } # operators & their respective operation # print table header print("""Symbol""".center(8 ) , """Action""".center(12 ) , """Stack""" , sep=""" | """ ) print("""-""" * (30 + len(lowercase__ )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(lowercase__ ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("""push(""" + x + """)""").ljust(12 ) , """,""".join(lowercase__ ) , sep=""" | """ ) else: a__ = stack.pop() # pop stack # output in tabular format print("""""".rjust(8 ) , ("""pop(""" + b + """)""").ljust(12 ) , """,""".join(lowercase__ ) , sep=""" | """ ) a__ = stack.pop() # pop stack # output in tabular format print("""""".rjust(8 ) , ("""pop(""" + a + """)""").ljust(12 ) , """,""".join(lowercase__ ) , sep=""" | """ ) stack.append( str(opr[x](int(lowercase__ ) , int(lowercase__ ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("""push(""" + a + x + b + """)""").ljust(12 ) , """,""".join(lowercase__ ) , sep=""" | """ , ) return int(stack[0] ) if __name__ == "__main__": _lowercase : int =input("""\n\nEnter a Postfix Equation (space separated) = """).split(""" """) print("""\n\tResult = """, solve(Postfix))
412
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: __magic_name__ = None __magic_name__ = logging.get_logger(__name__) __magic_name__ = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} __magic_name__ = { """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", }, """tokenizer_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json""", }, } __magic_name__ = { """albert-base-v1""": 5_1_2, """albert-large-v1""": 5_1_2, """albert-xlarge-v1""": 5_1_2, """albert-xxlarge-v1""": 5_1_2, """albert-base-v2""": 5_1_2, """albert-large-v2""": 5_1_2, """albert-xlarge-v2""": 5_1_2, """albert-xxlarge-v2""": 5_1_2, } __magic_name__ = """▁""" class lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __UpperCAmelCase : str = VOCAB_FILES_NAMES __UpperCAmelCase : Dict = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Union[str, Any] = AlbertTokenizer def __init__( self , a_=None , a_=None , a_=True , a_=True , a_=False , a_="[CLS]" , a_="[SEP]" , a_="<unk>" , a_="[SEP]" , a_="<pad>" , a_="[CLS]" , a_="[MASK]" , **a_ , ): lowerCamelCase_ : Optional[Any] = ( AddedToken(snake_case__ , lstrip=snake_case__ , rstrip=snake_case__ , normalized=snake_case__ ) if isinstance(snake_case__ , snake_case__ ) else mask_token ) super().__init__( snake_case__ , tokenizer_file=snake_case__ , do_lower_case=snake_case__ , remove_space=snake_case__ , keep_accents=snake_case__ , bos_token=snake_case__ , eos_token=snake_case__ , unk_token=snake_case__ , sep_token=snake_case__ , pad_token=snake_case__ , cls_token=snake_case__ , mask_token=snake_case__ , **snake_case__ , ) lowerCamelCase_ : Dict = do_lower_case lowerCamelCase_ : int = remove_space lowerCamelCase_ : int = keep_accents lowerCamelCase_ : Any = vocab_file lowerCamelCase_ : str = False if not self.vocab_file else True def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Tuple = [self.sep_token_id] lowerCamelCase_ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _UpperCamelCase ( self , a_ , a_ = None ): lowerCamelCase_ : Tuple = [self.sep_token_id] lowerCamelCase_ : 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 _UpperCamelCase ( self , a_ , a_ = None ): if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(snake_case__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCamelCase_ : Optional[Any] = os.path.join( snake_case__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case__ ): copyfile(self.vocab_file , snake_case__ ) return (out_vocab_file,)
250
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow a : Dict = logging.getLogger() @unittest.skip("Temporarily disable the doc tests." ) @require_torch @require_tf @slow class __UpperCAmelCase( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = True , ): '''simple docstring''' lowercase__ : List[Any]= [file for file in os.listdir(snake_case__ ) if os.path.isfile(os.path.join(snake_case__ , snake_case__ ) )] if identifier is not None: lowercase__ : str= [file for file in files if identifier in file] if n_identifier is not None: if isinstance(snake_case__ , snake_case__ ): for n_ in n_identifier: lowercase__ : List[Any]= [file for file in files if n_ not in file] else: lowercase__ : int= [file for file in files if n_identifier not in file] lowercase__ : List[Any]= ignore_files or [] ignore_files.append("__init__.py" ) lowercase__ : Union[str, Any]= [file for file in files if file not in ignore_files] for file in files: # Open all files print("Testing" , snake_case__ ) if only_modules: lowercase__ : Dict= file.split("." )[0] try: lowercase__ : int= getattr(snake_case__ , snake_case__ ) lowercase__ : Union[str, Any]= doctest.DocTestSuite(snake_case__ ) lowercase__ : Union[str, Any]= unittest.TextTestRunner().run(snake_case__ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'''{module_identifier} is not a module.''' ) else: lowercase__ : List[str]= doctest.testfile(str(".." / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= Path("src/transformers" ) lowercase__ : str= "modeling" lowercase__ : Dict= [ "modeling_ctrl.py", "modeling_tf_ctrl.py", ] self.analyze_directory(snake_case__ , identifier=snake_case__ , ignore_files=snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= Path("src/transformers" ) lowercase__ : Tuple= "tokenization" self.analyze_directory(snake_case__ , identifier=snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= Path("src/transformers" ) lowercase__ : int= "configuration" self.analyze_directory(snake_case__ , identifier=snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= Path("src/transformers" ) lowercase__ : List[str]= ["configuration", "modeling", "tokenization"] self.analyze_directory(snake_case__ , n_identifier=snake_case__ ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= Path("docs/source" ) lowercase__ : Any= ["favicon.ico"] self.analyze_directory(snake_case__ , ignore_files=snake_case__ , only_modules=snake_case__ )
218
0
class UpperCamelCase: def __init__( self : int , SCREAMING_SNAKE_CASE : Dict ) -> int: '''simple docstring''' __snake_case = arr.split("," ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: '''simple docstring''' __snake_case = [int(self.array[0] )] * len(self.array ) __snake_case = [int(self.array[0] )] * len(self.array ) for i in range(1 , len(self.array ) ): __snake_case = max( int(self.array[i] ) + sum_value[i - 1] , int(self.array[i] ) ) __snake_case = max(sum_value[i] , rear[i - 1] ) return rear[len(self.array ) - 1] if __name__ == "__main__": A : Tuple = input('please input some numbers:') A : List[str] = SubArray(whole_array) A : str = array.solve_sub_array() print(('the results is:', re))
473
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _lowerCAmelCase ( _lowerCAmelCase = "" ) -> dict[str, float]: '''simple docstring''' __snake_case = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" __snake_case = BeautifulSoup(requests.get(_lowerCAmelCase ).text , "html.parser" ) __snake_case = soup.find_all("td" , attrs="titleColumn" ) __snake_case = soup.find_all("td" , class_="ratingColumn imdbRating" ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(_lowerCAmelCase , _lowerCAmelCase ) } def _lowerCAmelCase ( _lowerCAmelCase = "IMDb_Top_250_Movies.csv" ) -> None: '''simple docstring''' __snake_case = get_imdb_top_aaa_movies() with open(_lowerCAmelCase , "w" , newline="" ) as out_file: __snake_case = csv.writer(_lowerCAmelCase ) writer.writerow(["Movie title", "IMDb rating"] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
473
1
'''simple docstring''' 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 import BertTokenizer lowerCAmelCase_ : Dict = logging.get_logger(__name__) lowerCAmelCase_ : List[str] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} lowerCAmelCase_ : Any = { '''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''' ), }, } lowerCAmelCase_ : List[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''' ), }, } lowerCAmelCase_ : Optional[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''' ), }, } lowerCAmelCase_ : Tuple = { '''facebook/dpr-ctx_encoder-single-nq-base''': 512, '''facebook/dpr-ctx_encoder-multiset-base''': 512, } lowerCAmelCase_ : Any = { '''facebook/dpr-question_encoder-single-nq-base''': 512, '''facebook/dpr-question_encoder-multiset-base''': 512, } lowerCAmelCase_ : Union[str, Any] = { '''facebook/dpr-reader-single-nq-base''': 512, '''facebook/dpr-reader-multiset-base''': 512, } lowerCAmelCase_ : Any = { '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True}, } lowerCAmelCase_ : Optional[Any] = { '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True}, } lowerCAmelCase_ : str = { '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True}, } class lowerCamelCase_ ( UpperCamelCase__ ): _lowerCAmelCase : Tuple = VOCAB_FILES_NAMES _lowerCAmelCase : Tuple = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase : str = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class lowerCamelCase_ ( UpperCamelCase__ ): _lowerCAmelCase : List[Any] = VOCAB_FILES_NAMES _lowerCAmelCase : Optional[int] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase : Tuple = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase : Tuple = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION lowerCAmelCase_ : Any = collections.namedtuple( 'DPRSpanPrediction', ['span_score', 'relevance_score', 'doc_id', 'start_index', 'end_index', 'text'] ) lowerCAmelCase_ : Tuple = collections.namedtuple('DPRReaderOutput', ['start_logits', 'end_logits', 'relevance_logits']) lowerCAmelCase_ : Optional[Any] = R''' Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: ``` [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> ``` Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `\'tf\'`: Return TensorFlow `tf.constant` objects. - `\'pt\'`: Return PyTorch `torch.Tensor` objects. - `\'np\'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer\'s default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Returns: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. ''' @add_start_docstrings(UpperCamelCase__ ) class lowerCamelCase_ : def __call__( self : int , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Optional[str] = None , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Union[bool, str] = False , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , lowerCAmelCase__ : Optional[bool] = None , **lowerCAmelCase__ : Dict , ): """simple docstring""" 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: SCREAMING_SNAKE_CASE : Union[str, 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 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = titles if not isinstance(_a , _a ) else [titles] SCREAMING_SNAKE_CASE : List[Any] = texts if not isinstance(_a , _a ) else [texts] SCREAMING_SNAKE_CASE : Union[str, Any] = len(_a ) SCREAMING_SNAKE_CASE : Optional[Any] = questions if not isinstance(_a , _a ) else [questions] * n_passages if len(_a ) != len(_a ): raise ValueError( F"""There should be as many titles than texts but got {len(_a )} titles and {len(_a )} texts.""" ) SCREAMING_SNAKE_CASE : str = super().__call__(_a , _a , padding=_a , truncation=_a )['''input_ids'''] SCREAMING_SNAKE_CASE : Dict = super().__call__(_a , add_special_tokens=_a , padding=_a , truncation=_a )['''input_ids'''] SCREAMING_SNAKE_CASE : Optional[int] = { '''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: SCREAMING_SNAKE_CASE : 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] ) SCREAMING_SNAKE_CASE : str = attention_mask return self.pad(_a , padding=_a , max_length=_a , return_tensors=_a ) def __lowercase ( self : int , lowerCAmelCase__ : BatchEncoding , lowerCAmelCase__ : DPRReaderOutput , lowerCAmelCase__ : int = 16 , lowerCAmelCase__ : int = 64 , lowerCAmelCase__ : int = 4 , ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = reader_input['''input_ids'''] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Union[str, Any] = reader_output[:3] SCREAMING_SNAKE_CASE : Any = len(_a ) SCREAMING_SNAKE_CASE : int = sorted(range(_a ) , reverse=_a , key=relevance_logits.__getitem__ ) SCREAMING_SNAKE_CASE : List[str] = [] for doc_id in sorted_docs: SCREAMING_SNAKE_CASE : Any = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence SCREAMING_SNAKE_CASE : Optional[int] = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: SCREAMING_SNAKE_CASE : Any = sequence_ids.index(self.pad_token_id ) else: SCREAMING_SNAKE_CASE : str = len(_a ) SCREAMING_SNAKE_CASE : List[Any] = 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 __lowercase ( self : str , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : List[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : int , ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = [] 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) ) SCREAMING_SNAKE_CASE : int = sorted(_a , key=lambda lowerCAmelCase__ : x[1] , reverse=_a ) SCREAMING_SNAKE_CASE : Optional[Any] = [] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(F"""Wrong span indices: [{start_index}:{end_index}]""" ) SCREAMING_SNAKE_CASE : int = end_index - start_index + 1 if length > max_answer_length: raise ValueError(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(UpperCamelCase__ ) class lowerCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): _lowerCAmelCase : Optional[Any] = VOCAB_FILES_NAMES _lowerCAmelCase : Dict = READER_PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase : str = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase : int = READER_PRETRAINED_INIT_CONFIGURATION _lowerCAmelCase : List[Any] = ['input_ids', 'attention_mask']
527
import requests from bsa import BeautifulSoup def lowerCamelCase( a__ = "https://www.worldometers.info/coronavirus"): _SCREAMING_SNAKE_CASE =BeautifulSoup(requests.get(a__).text ,'''html.parser''') _SCREAMING_SNAKE_CASE =soup.findAll('''h1''') _SCREAMING_SNAKE_CASE =soup.findAll('''div''' ,{'''class''': '''maincounter-number'''}) keys += soup.findAll('''span''' ,{'''class''': '''panel-title'''}) values += soup.findAll('''div''' ,{'''class''': '''number-table-main'''}) return {key.text.strip(): value.text.strip() for key, value in zip(a__ ,a__)} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(f"""{key}\n{value}\n""")
691
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _SCREAMING_SNAKE_CASE = { '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''], '''tokenization_tapas''': ['''TapasTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ '''TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TapasForMaskedLM''', '''TapasForQuestionAnswering''', '''TapasForSequenceClassification''', '''TapasModel''', '''TapasPreTrainedModel''', '''load_tf_weights_in_tapas''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ '''TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFTapasForMaskedLM''', '''TFTapasForQuestionAnswering''', '''TFTapasForSequenceClassification''', '''TFTapasModel''', '''TFTapasPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
56
'''simple docstring''' import math def _lowerCAmelCase ( lowerCamelCase_ : int ): assert isinstance(lowerCamelCase_ , lowerCamelCase_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False __lowercase = range(3 , int(math.sqrt(lowerCamelCase_ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _lowerCAmelCase ( lowerCamelCase_ : Dict , lowerCamelCase_ : Any=1 , **lowerCamelCase_ : Tuple ): __lowercase = factor * value __lowercase = value while not is_prime(lowerCamelCase_ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowerCamelCase_ ) return value
56
1
'''simple docstring''' import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/update_metadata.py lowerCAmelCase = """src/transformers""" # This is to make sure the transformers module imported is the one in the repo. lowerCAmelCase = direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. lowerCAmelCase = re.compile(R"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") lowerCAmelCase = re.compile(R"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. lowerCAmelCase = re.compile(R"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Fill this with tuples (pipeline_tag, model_mapping, auto_model) lowerCAmelCase = [ ("""pretraining""", """MODEL_FOR_PRETRAINING_MAPPING_NAMES""", """AutoModelForPreTraining"""), ("""feature-extraction""", """MODEL_MAPPING_NAMES""", """AutoModel"""), ("""audio-classification""", """MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForAudioClassification"""), ("""text-generation""", """MODEL_FOR_CAUSAL_LM_MAPPING_NAMES""", """AutoModelForCausalLM"""), ("""automatic-speech-recognition""", """MODEL_FOR_CTC_MAPPING_NAMES""", """AutoModelForCTC"""), ("""image-classification""", """MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForImageClassification"""), ("""image-segmentation""", """MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES""", """AutoModelForImageSegmentation"""), ("""fill-mask""", """MODEL_FOR_MASKED_LM_MAPPING_NAMES""", """AutoModelForMaskedLM"""), ("""object-detection""", """MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES""", """AutoModelForObjectDetection"""), ( """zero-shot-object-detection""", """MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES""", """AutoModelForZeroShotObjectDetection""", ), ("""question-answering""", """MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForQuestionAnswering"""), ("""text2text-generation""", """MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES""", """AutoModelForSeq2SeqLM"""), ("""text-classification""", """MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForSequenceClassification"""), ("""automatic-speech-recognition""", """MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES""", """AutoModelForSpeechSeq2Seq"""), ( """table-question-answering""", """MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForTableQuestionAnswering""", ), ("""token-classification""", """MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForTokenClassification"""), ("""multiple-choice""", """MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES""", """AutoModelForMultipleChoice"""), ( """next-sentence-prediction""", """MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES""", """AutoModelForNextSentencePrediction""", ), ( """audio-frame-classification""", """MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForAudioFrameClassification""", ), ("""audio-xvector""", """MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES""", """AutoModelForAudioXVector"""), ( """document-question-answering""", """MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForDocumentQuestionAnswering""", ), ( """visual-question-answering""", """MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES""", """AutoModelForVisualQuestionAnswering""", ), ("""image-to-text""", """MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES""", """AutoModelForVision2Seq"""), ( """zero-shot-image-classification""", """MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForZeroShotImageClassification""", ), ("""depth-estimation""", """MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES""", """AutoModelForDepthEstimation"""), ("""video-classification""", """MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES""", """AutoModelForVideoClassification"""), ("""mask-generation""", """MODEL_FOR_MASK_GENERATION_MAPPING_NAMES""", """AutoModelForMaskGeneration"""), ] def __A ( a_ : Union[str, Any] ): lowerCAmelCase : List[str] = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)" ,a_ ) return [m.group(0 ) for m in matches] def __A ( ): lowerCAmelCase : List[Any] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES lowerCAmelCase : Any = { config.replace("Config" ,"" ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. lowerCAmelCase : Any = collections.defaultdict(a_ ) lowerCAmelCase : Dict = collections.defaultdict(a_ ) lowerCAmelCase : Any = collections.defaultdict(a_ ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(a_ ): lowerCAmelCase : str = None if _re_tf_models.match(a_ ) is not None: lowerCAmelCase : Union[str, Any] = tf_models lowerCAmelCase : Any = _re_tf_models.match(a_ ).groups()[0] elif _re_flax_models.match(a_ ) is not None: lowerCAmelCase : Dict = flax_models lowerCAmelCase : Optional[Any] = _re_flax_models.match(a_ ).groups()[0] elif _re_pt_models.match(a_ ) is not None: lowerCAmelCase : int = pt_models lowerCAmelCase : int = _re_pt_models.match(a_ ).groups()[0] if lookup_dict is not None: while len(a_ ) > 0: if attr_name in model_prefix_to_model_type: lowerCAmelCase : Optional[int] = True break # Try again after removing the last word in the name lowerCAmelCase : str = "".join(camel_case_split(a_ )[:-1] ) lowerCAmelCase : List[str] = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) lowerCAmelCase : List[Any] = list(a_ ) all_models.sort() lowerCAmelCase : Union[str, Any] = {"model_type": all_models} lowerCAmelCase : str = [pt_models[t] for t in all_models] lowerCAmelCase : Tuple = [tf_models[t] for t in all_models] lowerCAmelCase : Any = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure lowerCAmelCase : List[str] = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: lowerCAmelCase : Optional[int] = "AutoProcessor" elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: lowerCAmelCase : int = "AutoTokenizer" elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: lowerCAmelCase : Union[str, Any] = "AutoFeatureExtractor" else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. lowerCAmelCase : Optional[int] = "AutoTokenizer" lowerCAmelCase : Union[str, Any] = [processors[t] for t in all_models] return pd.DataFrame(a_ ) def __A ( a_ : int ): lowerCAmelCase : str = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: lowerCAmelCase : Dict = [model_mapping, f'''TF_{model_mapping}''', f'''FLAX_{model_mapping}'''] lowerCAmelCase : List[Any] = [auto_class, f'''TF_{auto_class}''', f'''Flax_{auto_class}'''] # Loop through all three frameworks for module, cls, mapping in zip(a_ ,a_ ,a_ ): # The type of pipeline may not exist in this framework if not hasattr(a_ ,a_ ): continue # First extract all model_names lowerCAmelCase : Optional[Any] = [] for name in getattr(a_ ,a_ ).values(): if isinstance(a_ ,a_ ): model_names.append(a_ ) else: model_names.extend(list(a_ ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def __A ( a_ : str ,a_ : Any ): lowerCAmelCase : str = get_frameworks_table() lowerCAmelCase : str = Dataset.from_pandas(a_ ) lowerCAmelCase : Optional[Any] = hf_hub_download( "huggingface/transformers-metadata" ,"pipeline_tags.json" ,repo_type="dataset" ,token=a_ ) lowerCAmelCase : Dict = Dataset.from_json(a_ ) lowerCAmelCase : Dict = { tags_dataset[i]["model_class"]: (tags_dataset[i]["pipeline_tag"], tags_dataset[i]["auto_class"]) for i in range(len(a_ ) ) } lowerCAmelCase : List[Any] = update_pipeline_and_auto_class_table(a_ ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. lowerCAmelCase : Tuple = sorted(table.keys() ) lowerCAmelCase : Tuple = pd.DataFrame( { "model_class": model_classes, "pipeline_tag": [table[m][0] for m in model_classes], "auto_class": [table[m][1] for m in model_classes], } ) lowerCAmelCase : List[str] = Dataset.from_pandas(a_ ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(a_ ,"frameworks.json" ) ) tags_dataset.to_json(os.path.join(a_ ,"pipeline_tags.json" ) ) if commit_sha is not None: lowerCAmelCase : Dict = ( f'''Update with commit {commit_sha}\n\nSee: ''' f'''https://github.com/huggingface/transformers/commit/{commit_sha}''' ) else: lowerCAmelCase : Optional[int] = "Update" upload_folder( repo_id="huggingface/transformers-metadata" ,folder_path=a_ ,repo_type="dataset" ,token=a_ ,commit_message=a_ ,) def __A ( ): lowerCAmelCase : Union[str, Any] = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} lowerCAmelCase : List[Any] = transformers_module.pipelines.SUPPORTED_TASKS lowerCAmelCase : List[Any] = [] for key in pipeline_tasks: if key not in in_table: lowerCAmelCase : Optional[int] = pipeline_tasks[key]["pt"] if isinstance(a_ ,(list, tuple) ): lowerCAmelCase : Union[str, Any] = model[0] lowerCAmelCase : List[Any] = model.__name__ if model not in in_table.values(): missing.append(a_ ) if len(a_ ) > 0: lowerCAmelCase : Tuple = ", ".join(a_ ) raise ValueError( "The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside " f'''`utils/update_metadata.py`: {msg}. Please add them!''' ) if __name__ == "__main__": lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("""--token""", type=str, help="""The token to use to push to the transformers-metadata dataset.""") parser.add_argument("""--commit_sha""", type=str, help="""The sha of the commit going with this update.""") parser.add_argument("""--check-only""", action="""store_true""", help="""Activate to just check all pipelines are present.""") lowerCAmelCase = parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
525
'''simple docstring''' import math import tensorflow as tf from packaging import version def __A ( a_ : List[Any] ): lowerCAmelCase : Any = tf.convert_to_tensor(a_ ) lowerCAmelCase : List[Any] = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) ,x.dtype ) )) return x * cdf def __A ( a_ : int ): lowerCAmelCase : Dict = tf.convert_to_tensor(a_ ) lowerCAmelCase : int = tf.cast(math.pi ,x.dtype ) lowerCAmelCase : Dict = tf.cast(0.0_4_4_7_1_5 ,x.dtype ) lowerCAmelCase : Dict = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(a_ ,3 )) )) return x * cdf def __A ( a_ : Union[str, Any] ): lowerCAmelCase : Any = tf.convert_to_tensor(a_ ) return x * tf.tanh(tf.math.softplus(a_ ) ) def __A ( a_ : List[str] ): lowerCAmelCase : Dict = tf.convert_to_tensor(a_ ) lowerCAmelCase : Any = tf.cast(0.0_4_4_7_1_5 ,x.dtype ) lowerCAmelCase : Optional[int] = tf.cast(0.7_9_7_8_8_4_5_6_0_8 ,x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def __A ( a_ : Union[str, Any] ): lowerCAmelCase : Optional[int] = tf.convert_to_tensor(a_ ) lowerCAmelCase : List[Any] = tf.cast(1.7_0_2 ,x.dtype ) return x * tf.math.sigmoid(coeff * x ) def __A ( a_ : List[Any] ): return tf.clip_by_value(_gelu(a_ ) ,-1_0 ,1_0 ) def __A ( a_ : List[Any] ,a_ : List[Any]=-1 ): lowerCAmelCase , lowerCAmelCase : Optional[int] = tf.split(a_ ,2 ,axis=a_ ) return a * tf.math.sigmoid(a_ ) if version.parse(tf.version.VERSION) >= version.parse("""2.4"""): def __A ( a_ : Optional[Any] ): return tf.keras.activations.gelu(a_ ,approximate=a_ ) lowerCAmelCase = tf.keras.activations.gelu lowerCAmelCase = approximate_gelu_wrap else: lowerCAmelCase = _gelu lowerCAmelCase = _gelu_new lowerCAmelCase = { """gelu""": gelu, """gelu_10""": gelu_aa, """gelu_fast""": gelu_fast, """gelu_new""": gelu_new, """glu""": glu, """mish""": mish, """quick_gelu""": quick_gelu, """relu""": tf.keras.activations.relu, """sigmoid""": tf.keras.activations.sigmoid, """silu""": tf.keras.activations.swish, """swish""": tf.keras.activations.swish, """tanh""": tf.keras.activations.tanh, } def __A ( a_ : int ): if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}''' )
525
1
import os from math import logaa def __lowerCamelCase ( snake_case__ = "base_exp.txt" ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(snake_case__ ) ,snake_case__ ) ) ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = list(map(snake_case__ ,line.split(""",""" ) ) ) if x * logaa(snake_case__ ) > largest: _SCREAMING_SNAKE_CASE = x * logaa(snake_case__ ) _SCREAMING_SNAKE_CASE = i + 1 return result if __name__ == "__main__": print(solution())
706
from cva import destroyAllWindows, imread, imshow, waitKey def __lowerCamelCase ( snake_case__ ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(snake_case__ ): for j in range(snake_case__ ): _SCREAMING_SNAKE_CASE = [2_55, 2_55, 2_55] - img[i][j] return img if __name__ == "__main__": # read original image UpperCamelCase = imread('''image_data/lena.jpg''', 1) # convert to its negative UpperCamelCase = convert_to_negative(img) # show result image imshow('''negative of original image''', img) waitKey(0) destroyAllWindows()
569
0
import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES 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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCamelCase__ : """simple docstring""" def __init__( self : Optional[int] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple=13 , __lowerCAmelCase : List[str]=32 , __lowerCAmelCase : Optional[int]=3 , __lowerCAmelCase : Optional[int]=4 , __lowerCAmelCase : List[Any]=[10, 20, 30, 40] , __lowerCAmelCase : str=[2, 2, 3, 2] , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : str=True , __lowerCAmelCase : Optional[Any]=37 , __lowerCAmelCase : Dict="gelu" , __lowerCAmelCase : List[Any]=10 , __lowerCAmelCase : int=0.02 , __lowerCAmelCase : Any=["stage2", "stage3", "stage4"] , __lowerCAmelCase : List[Any]=[2, 3, 4] , __lowerCAmelCase : List[Any]=None , ) -> Optional[int]: _A = parent _A = batch_size _A = image_size _A = num_channels _A = num_stages _A = hidden_sizes _A = depths _A = is_training _A = use_labels _A = intermediate_size _A = hidden_act _A = num_labels _A = initializer_range _A = out_features _A = out_indices _A = scope def snake_case_ ( self : Any ) -> List[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.num_labels ) _A = self.get_config() return config, pixel_values, labels def snake_case_ ( self : Tuple ) -> List[str]: return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=__lowerCAmelCase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def snake_case_ ( self : str , __lowerCAmelCase : Any , __lowerCAmelCase : int , __lowerCAmelCase : int ) -> List[str]: _A = ConvNextVaModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _A = model(__lowerCAmelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def snake_case_ ( self : List[Any] , __lowerCAmelCase : str , __lowerCAmelCase : int , __lowerCAmelCase : Any ) -> Optional[Any]: _A = ConvNextVaForImageClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _A = model(__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def snake_case_ ( self : str , __lowerCAmelCase : int , __lowerCAmelCase : List[str] , __lowerCAmelCase : Dict ) -> int: _A = ConvNextVaBackbone(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _A = model(__lowerCAmelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _A = None _A = ConvNextVaBackbone(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _A = model(__lowerCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def snake_case_ ( self : Any ) -> Union[str, Any]: _A = self.prepare_config_and_inputs() _A , _A , _A = config_and_inputs _A = {'''pixel_values''': pixel_values} return config, inputs_dict def snake_case_ ( self : Optional[int] ) -> Optional[Any]: _A = self.prepare_config_and_inputs() _A , _A , _A = config_and_inputs _A = {'''pixel_values''': pixel_values, '''labels''': labels} return config, inputs_dict @require_torch class lowerCamelCase__ ( _A , _A , unittest.TestCase): """simple docstring""" a__ : Optional[int] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) a__ : Tuple = ( {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification} if is_torch_available() else {} ) a__ : Optional[Any] = False a__ : Any = False a__ : Dict = False a__ : Optional[Any] = False a__ : Optional[Any] = False def snake_case_ ( self : Optional[int] ) -> List[str]: _A = ConvNextVaModelTester(self ) _A = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=37 ) def snake_case_ ( self : Optional[Any] ) -> List[Any]: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def snake_case_ ( self : Any ) -> str: return @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''' ) def snake_case_ ( self : Any ) -> Any: pass @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''' ) def snake_case_ ( self : List[Any] ) -> Optional[int]: pass @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking''' ) def snake_case_ ( self : Union[str, Any] ) -> Tuple: pass def snake_case_ ( self : int ) -> List[Any]: if not self.model_tester.is_training: return for model_class in self.all_model_classes: _A , _A = self.model_tester.prepare_config_and_inputs_with_labels() _A = True if model_class.__name__ in [ *get_values(__lowerCAmelCase ), *get_values(__lowerCAmelCase ), ]: continue _A = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.train() _A = self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase , return_labels=__lowerCAmelCase ) _A = model(**__lowerCAmelCase ).loss loss.backward() def snake_case_ ( self : List[str] ) -> Any: if not self.model_tester.is_training: return for model_class in self.all_model_classes: _A , _A = self.model_tester.prepare_config_and_inputs_with_labels() _A = False _A = True if ( model_class.__name__ in [*get_values(__lowerCAmelCase ), *get_values(__lowerCAmelCase )] or not model_class.supports_gradient_checkpointing ): continue _A = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.gradient_checkpointing_enable() model.train() _A = self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase , return_labels=__lowerCAmelCase ) _A = model(**__lowerCAmelCase ).loss loss.backward() def snake_case_ ( self : Union[str, Any] ) -> str: _A , _A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A = model_class(__lowerCAmelCase ) _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] , __lowerCAmelCase ) def snake_case_ ( self : str ) -> List[Any]: _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def snake_case_ ( self : Tuple ) -> Any: def check_hidden_states_output(__lowerCAmelCase : Tuple , __lowerCAmelCase : int , __lowerCAmelCase : List[str] ): _A = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() with torch.no_grad(): _A = model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) ) _A = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _A = self.model_tester.num_stages self.assertEqual(len(__lowerCAmelCase ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _A , _A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _A = True check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _A = True check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def snake_case_ ( self : Optional[int] ) -> List[Any]: _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase ) @slow def snake_case_ ( self : List[str] ) -> Union[str, Any]: for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A = ConvNextVaModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: _A = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCamelCase__ ( unittest.TestCase): """simple docstring""" @cached_property def snake_case_ ( self : List[str] ) -> Dict: return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ) if is_vision_available() else None @slow def snake_case_ ( self : Tuple ) -> int: _A = ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ).to(__lowerCAmelCase ) _A = self.default_image_processor _A = prepare_img() _A = preprocessor(images=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): _A = model(**__lowerCAmelCase ) # verify the logits _A = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , __lowerCAmelCase ) _A = torch.tensor([0.9996, 0.1966, -0.4386] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) )
2
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 UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = """▁""" UpperCAmelCase_ = {"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} UpperCAmelCase_ = { """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } UpperCAmelCase_ = {"""vinai/bartpho-syllable""": 1_0_2_4} class lowerCamelCase__ ( _A): """simple docstring""" a__ : int = VOCAB_FILES_NAMES a__ : Tuple = PRETRAINED_VOCAB_FILES_MAP a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Tuple = ["input_ids", "attention_mask"] def __init__( self : Union[str, Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any]="<s>" , __lowerCAmelCase : Dict="</s>" , __lowerCAmelCase : List[Any]="</s>" , __lowerCAmelCase : Optional[Any]="<s>" , __lowerCAmelCase : Tuple="<unk>" , __lowerCAmelCase : int="<pad>" , __lowerCAmelCase : Optional[Any]="<mask>" , __lowerCAmelCase : Optional[Dict[str, Any]] = None , **__lowerCAmelCase : Tuple , ) -> None: # 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 , sep_token=__lowerCAmelCase , cls_token=__lowerCAmelCase , pad_token=__lowerCAmelCase , mask_token=__lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCAmelCase , ) _A = vocab_file _A = monolingual_vocab_file _A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__lowerCAmelCase ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility _A = {} _A = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(__lowerCAmelCase ) not in self.fairseq_tokens_to_ids: _A = cnt cnt += 1 with open(__lowerCAmelCase , '''r''' , encoding='''utf-8''' ) as f: for line in f.readlines(): _A = line.strip().split()[0] _A = len(self.fairseq_tokens_to_ids ) if str(__lowerCAmelCase ) not in self.fairseq_tokens_to_ids: _A = len(self.fairseq_tokens_to_ids ) _A = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Any ) -> List[Any]: _A = self.__dict__.copy() _A = None _A = self.sp_model.serialized_model_proto() return state def __setstate__( self : Union[str, Any] , __lowerCAmelCase : Dict ) -> List[Any]: _A = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _A = {} _A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def snake_case_ ( self : Optional[Any] , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None ) -> List[int]: 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 + sep + token_ids_a + sep def snake_case_ ( self : List[Any] , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None , __lowerCAmelCase : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCAmelCase , token_ids_a=__lowerCAmelCase , already_has_special_tokens=__lowerCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(__lowerCAmelCase )) + [1] return [1] + ([0] * len(__lowerCAmelCase )) + [1, 1] + ([0] * len(__lowerCAmelCase )) + [1] def snake_case_ ( self : Any , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None ) -> List[int]: _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 + sep + token_ids_a + sep ) * [0] @property def snake_case_ ( self : Optional[int] ) -> Union[str, Any]: return len(self.fairseq_ids_to_tokens ) def snake_case_ ( self : Dict ) -> Optional[Any]: _A = {self.convert_ids_to_tokens(__lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def snake_case_ ( self : List[str] , __lowerCAmelCase : str ) -> List[str]: return self.sp_model.encode(__lowerCAmelCase , out_type=__lowerCAmelCase ) def snake_case_ ( self : str , __lowerCAmelCase : Optional[Any] ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def snake_case_ ( self : int , __lowerCAmelCase : Optional[int] ) -> List[str]: return self.fairseq_ids_to_tokens[index] def snake_case_ ( self : List[str] , __lowerCAmelCase : Union[str, Any] ) -> Tuple: _A = ''''''.join(__lowerCAmelCase ).replace(__lowerCAmelCase , ''' ''' ).strip() return out_string def snake_case_ ( self : str , __lowerCAmelCase : str , __lowerCAmelCase : Optional[str] = None ) -> Tuple[str]: 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'''] ) _A = os.path.join( __lowerCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''monolingual_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 ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( __lowerCAmelCase ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , __lowerCAmelCase ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(__lowerCAmelCase , '''w''' , encoding='''utf-8''' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'''{str(__lowerCAmelCase )} \n''' ) return out_vocab_file, out_monolingual_vocab_file
2
1
def A__ ( SCREAMING_SNAKE_CASE__) -> List[Any]: __snake_case: List[Any] = len(SCREAMING_SNAKE_CASE__) for i in range(length - 1): __snake_case: Tuple = i for k in range(i + 1 , SCREAMING_SNAKE_CASE__): if collection[k] < collection[least]: __snake_case: str = k if least != i: __snake_case , __snake_case: Optional[Any] = (collection[i], collection[least]) return collection if __name__ == "__main__": __UpperCAmelCase : Any = input("Enter numbers separated by a comma:\n").strip() __UpperCAmelCase : List[str] = [int(item) for item in user_input.split(",")] print(selection_sort(unsorted))
155
def A__ ( SCREAMING_SNAKE_CASE__) -> list: __snake_case: List[str] = int(SCREAMING_SNAKE_CASE__) if n_element < 1: __snake_case: Any = ValueError("""a should be a positive number""") raise my_error __snake_case: str = [1] __snake_case , __snake_case , __snake_case: Union[str, Any] = (0, 0, 0) __snake_case: Optional[Any] = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5)) index += 1 return hamming_list if __name__ == "__main__": __UpperCAmelCase : int = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") __UpperCAmelCase : Union[str, Any] = hamming(int(n)) print("-----------------------------------------------------") print(f'The list with nth numbers is: {hamming_numbers}') print("-----------------------------------------------------")
155
1
from math import isqrt, loga def A__ ( SCREAMING_SNAKE_CASE_ : int ) -> list[int]: """simple docstring""" _UpperCAmelCase = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): _UpperCAmelCase = False return [i for i in range(2 , SCREAMING_SNAKE_CASE_ ) if is_prime[i]] def A__ ( SCREAMING_SNAKE_CASE_ : int = 80_08_00 , SCREAMING_SNAKE_CASE_ : int = 80_08_00 ) -> int: """simple docstring""" _UpperCAmelCase = degree * loga(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = int(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = calculate_prime_numbers(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = 0 _UpperCAmelCase = 0 _UpperCAmelCase = len(SCREAMING_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() = }''')
32
"""simple docstring""" # Lint as: python3 import itertools import os import re a_ = re.compile(r"""([A-Z]+)([A-Z][a-z])""") a_ = re.compile(r"""([a-z\d])([A-Z])""") a_ = re.compile(r"""(?<!_)_(?!_)""") a_ = re.compile(r"""(_{2,})""") a_ = r"""^\w+(\.\w+)*$""" a_ = r"""<>:/\|?*""" def UpperCAmelCase_ ( __a : Optional[int] ): '''simple docstring''' _lowerCamelCase : str = _uppercase_uppercase_re.sub(r'\1_\2' , __a ) _lowerCamelCase : Tuple = _lowercase_uppercase_re.sub(r'\1_\2' , __a ) return name.lower() def UpperCAmelCase_ ( __a : Optional[int] ): '''simple docstring''' _lowerCamelCase : Dict = _single_underscore_re.split(__a ) _lowerCamelCase : Tuple = [_multiple_underscores_re.split(__a ) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(__a ) if n != '' ) def UpperCAmelCase_ ( __a : List[Any] ): '''simple docstring''' if os.path.basename(__a ) != name: raise ValueError(f"Should be a dataset name, not a path: {name}" ) return camelcase_to_snakecase(__a ) def UpperCAmelCase_ ( __a : Union[str, Any] , __a : Optional[int] ): '''simple docstring''' if os.path.basename(__a ) != name: raise ValueError(f"Should be a dataset name, not a path: {name}" ) if not re.match(_split_re , __a ): raise ValueError(f"Split name should match '{_split_re}'' but got '{split}'." ) return f"{filename_prefix_for_name(__a )}-{split}" def UpperCAmelCase_ ( __a : Any , __a : Union[str, Any] , __a : List[Any] , __a : List[str]=None ): '''simple docstring''' _lowerCamelCase : List[Any] = filename_prefix_for_split(__a , __a ) if filetype_suffix: prefix += f".{filetype_suffix}" _lowerCamelCase : List[str] = os.path.join(__a , __a ) return f"{filepath}*" def UpperCAmelCase_ ( __a : str , __a : List[Any] , __a : List[str] , __a : Tuple=None , __a : Tuple=None ): '''simple docstring''' _lowerCamelCase : Tuple = filename_prefix_for_split(__a , __a ) _lowerCamelCase : List[str] = os.path.join(__a , __a ) if shard_lengths: _lowerCamelCase : Union[str, Any] = len(__a ) _lowerCamelCase : str = [f"{prefix}-{shard_id:05d}-of-{num_shards:05d}" for shard_id in range(__a )] if filetype_suffix: _lowerCamelCase : int = [filename + f".{filetype_suffix}" for filename in filenames] return filenames else: _lowerCamelCase : int = prefix if filetype_suffix: filename += f".{filetype_suffix}" return [filename]
437
0
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): A = """pt""" elif is_tf_available(): A = """tf""" else: A = """jax""" class a__ ( __magic_name__ , unittest.TestCase ): lowercase_ = PerceiverTokenizer lowercase_ = False def a_ ( self : Optional[int]): """simple docstring""" super().setUp() __UpperCAmelCase : Dict = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname) @cached_property def a_ ( self : int): """simple docstring""" return PerceiverTokenizer.from_pretrained("deepmind/language-perceiver") def a_ ( self : Any , **UpperCamelCase_ : Optional[int]): """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **UpperCamelCase_) def a_ ( self : Optional[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Any=False , UpperCamelCase_ : Dict=20 , UpperCamelCase_ : Union[str, Any]=5): """simple docstring""" __UpperCAmelCase : Optional[int] = [] for i in range(len(UpperCamelCase_)): try: __UpperCAmelCase : Union[str, Any] = tokenizer.decode([i] , clean_up_tokenization_spaces=UpperCamelCase_) except UnicodeDecodeError: pass toks.append((i, tok)) __UpperCAmelCase : Union[str, Any] = list(filter(lambda UpperCamelCase_: re.match(r"^[ a-zA-Z]+$" , t[1]) , UpperCamelCase_)) __UpperCAmelCase : Dict = list(filter(lambda UpperCamelCase_: [t[0]] == tokenizer.encode(t[1] , add_special_tokens=UpperCamelCase_) , UpperCamelCase_)) if max_length is not None and len(UpperCamelCase_) > max_length: __UpperCAmelCase : Dict = toks[:max_length] if min_length is not None and len(UpperCamelCase_) < min_length and len(UpperCamelCase_) > 0: while len(UpperCamelCase_) < min_length: __UpperCAmelCase : int = toks + toks # toks_str = [t[1] for t in toks] __UpperCAmelCase : Dict = [t[0] for t in toks] # Ensure consistency __UpperCAmelCase : List[Any] = tokenizer.decode(UpperCamelCase_ , clean_up_tokenization_spaces=UpperCamelCase_) if " " not in output_txt and len(UpperCamelCase_) > 1: __UpperCAmelCase : Optional[int] = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=UpperCamelCase_) + " " + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=UpperCamelCase_) ) if with_prefix_space: __UpperCAmelCase : int = " " + output_txt __UpperCAmelCase : Optional[Any] = tokenizer.encode(UpperCamelCase_ , add_special_tokens=UpperCamelCase_) return output_txt, output_ids def a_ ( self : Optional[Any]): """simple docstring""" __UpperCAmelCase : int = self.perceiver_tokenizer __UpperCAmelCase : Any = "Unicode €." __UpperCAmelCase : Union[str, Any] = tokenizer(UpperCamelCase_) __UpperCAmelCase : Optional[Any] = [4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5] self.assertEqual(encoded["input_ids"] , UpperCamelCase_) # decoding __UpperCAmelCase : List[Any] = tokenizer.decode(UpperCamelCase_) self.assertEqual(UpperCamelCase_ , "[CLS]Unicode €.[SEP]") __UpperCAmelCase : Tuple = tokenizer("e è é ê ë") __UpperCAmelCase : Dict = [4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5] self.assertEqual(encoded["input_ids"] , UpperCamelCase_) # decoding __UpperCAmelCase : Dict = tokenizer.decode(UpperCamelCase_) self.assertEqual(UpperCamelCase_ , "[CLS]e è é ê ë[SEP]") # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë")) , "[CLS]e è é ê ë[SEP]") def a_ ( self : Optional[Any]): """simple docstring""" __UpperCAmelCase : Union[str, Any] = self.perceiver_tokenizer __UpperCAmelCase : int = ["A long paragraph for summarization.", "Another paragraph for summarization."] # fmt: off __UpperCAmelCase : List[str] = [4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0] # fmt: on __UpperCAmelCase : str = tokenizer(UpperCamelCase_ , padding=UpperCamelCase_ , return_tensors=UpperCamelCase_) self.assertIsInstance(UpperCamelCase_ , UpperCamelCase_) if FRAMEWORK != "jax": __UpperCAmelCase : Dict = list(batch.input_ids.numpy()[0]) else: __UpperCAmelCase : Tuple = list(batch.input_ids.tolist()[0]) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_) self.assertEqual((2, 38) , batch.input_ids.shape) self.assertEqual((2, 38) , batch.attention_mask.shape) def a_ ( self : str): """simple docstring""" __UpperCAmelCase : int = self.perceiver_tokenizer __UpperCAmelCase : Union[str, Any] = ["A long paragraph for summarization.", "Another paragraph for summarization."] __UpperCAmelCase : Union[str, Any] = tokenizer(UpperCamelCase_ , padding=UpperCamelCase_ , return_tensors=UpperCamelCase_) # check if input_ids are returned and no decoder_input_ids self.assertIn("input_ids" , UpperCamelCase_) self.assertIn("attention_mask" , UpperCamelCase_) self.assertNotIn("decoder_input_ids" , UpperCamelCase_) self.assertNotIn("decoder_attention_mask" , UpperCamelCase_) def a_ ( self : Tuple): """simple docstring""" __UpperCAmelCase : Tuple = self.perceiver_tokenizer __UpperCAmelCase : Dict = [ "Summary of the text.", "Another summary.", ] __UpperCAmelCase : Optional[int] = tokenizer( text_target=UpperCamelCase_ , max_length=32 , padding="max_length" , truncation=UpperCamelCase_ , return_tensors=UpperCamelCase_) self.assertEqual(32 , targets["input_ids"].shape[1]) def a_ ( self : Any): """simple docstring""" __UpperCAmelCase : Union[str, Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}"): self.assertNotEqual(tokenizer.model_max_length , 42) # Now let's start the test __UpperCAmelCase : Optional[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}"): # Isolate this from the other tests because we save additional tokens/etc __UpperCAmelCase : Tuple = tempfile.mkdtemp() __UpperCAmelCase : List[str] = " He is very happy, UNwant\u00E9d,running" __UpperCAmelCase : str = tokenizer.encode(UpperCamelCase_ , add_special_tokens=UpperCamelCase_) tokenizer.save_pretrained(UpperCamelCase_) __UpperCAmelCase : List[str] = tokenizer.__class__.from_pretrained(UpperCamelCase_) __UpperCAmelCase : Optional[int] = after_tokenizer.encode(UpperCamelCase_ , add_special_tokens=UpperCamelCase_) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_) shutil.rmtree(UpperCamelCase_) __UpperCAmelCase : List[str] = self.get_tokenizers(model_max_length=42) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}"): # Isolate this from the other tests because we save additional tokens/etc __UpperCAmelCase : str = tempfile.mkdtemp() __UpperCAmelCase : Optional[Any] = " He is very happy, UNwant\u00E9d,running" tokenizer.add_tokens(["bim", "bambam"]) __UpperCAmelCase : str = tokenizer.additional_special_tokens additional_special_tokens.append("new_additional_special_token") tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens}) __UpperCAmelCase : Tuple = tokenizer.encode(UpperCamelCase_ , add_special_tokens=UpperCamelCase_) tokenizer.save_pretrained(UpperCamelCase_) __UpperCAmelCase : Optional[Any] = tokenizer.__class__.from_pretrained(UpperCamelCase_) __UpperCAmelCase : str = after_tokenizer.encode(UpperCamelCase_ , add_special_tokens=UpperCamelCase_) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_) self.assertIn("new_additional_special_token" , after_tokenizer.additional_special_tokens) self.assertEqual(after_tokenizer.model_max_length , 42) __UpperCAmelCase : Union[str, Any] = tokenizer.__class__.from_pretrained(UpperCamelCase_ , model_max_length=43) self.assertEqual(tokenizer.model_max_length , 43) shutil.rmtree(UpperCamelCase_) def a_ ( self : Optional[Any]): """simple docstring""" __UpperCAmelCase : List[Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(UpperCamelCase_) with open(os.path.join(UpperCamelCase_ , "special_tokens_map.json") , encoding="utf-8") as json_file: __UpperCAmelCase : int = json.load(UpperCamelCase_) with open(os.path.join(UpperCamelCase_ , "tokenizer_config.json") , encoding="utf-8") as json_file: __UpperCAmelCase : Tuple = json.load(UpperCamelCase_) __UpperCAmelCase : str = [F"<extra_id_{i}>" for i in range(125)] __UpperCAmelCase : List[Any] = added_tokens_extra_ids + [ "an_additional_special_token" ] __UpperCAmelCase : Optional[int] = added_tokens_extra_ids + [ "an_additional_special_token" ] with open(os.path.join(UpperCamelCase_ , "special_tokens_map.json") , "w" , encoding="utf-8") as outfile: json.dump(UpperCamelCase_ , UpperCamelCase_) with open(os.path.join(UpperCamelCase_ , "tokenizer_config.json") , "w" , encoding="utf-8") as outfile: json.dump(UpperCamelCase_ , UpperCamelCase_) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files __UpperCAmelCase : Tuple = tokenizer_class.from_pretrained( UpperCamelCase_ , ) self.assertIn( "an_additional_special_token" , tokenizer_without_change_in_init.additional_special_tokens) self.assertEqual( ["an_additional_special_token"] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"])) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained __UpperCAmelCase : int = added_tokens_extra_ids + [AddedToken("a_new_additional_special_token" , lstrip=UpperCamelCase_)] __UpperCAmelCase : Union[str, Any] = tokenizer_class.from_pretrained( UpperCamelCase_ , additional_special_tokens=UpperCamelCase_ , ) self.assertIn("a_new_additional_special_token" , tokenizer.additional_special_tokens) self.assertEqual( ["a_new_additional_special_token"] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"])) , ) def a_ ( self : Union[str, Any]): """simple docstring""" __UpperCAmelCase : List[Any] = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([178]) , "�") def a_ ( self : Dict): """simple docstring""" pass def a_ ( self : str): """simple docstring""" pass def a_ ( self : int): """simple docstring""" pass def a_ ( self : Tuple): """simple docstring""" pass def a_ ( self : Any): """simple docstring""" __UpperCAmelCase : Dict = self.get_tokenizers(fast=UpperCamelCase_ , do_lower_case=UpperCamelCase_) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}"): __UpperCAmelCase : Any = ["[CLS]", "t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "s", "t", "[SEP]"] __UpperCAmelCase : Optional[Any] = tokenizer.convert_tokens_to_string(UpperCamelCase_) self.assertIsInstance(UpperCamelCase_ , UpperCamelCase_)
487
"""simple docstring""" from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase = 1 / sqrt(2 ) ) -> IIRFilter: """simple docstring""" __UpperCAmelCase : List[str] = tau * frequency / samplerate __UpperCAmelCase : Optional[int] = sin(UpperCamelCase ) __UpperCAmelCase : Any = cos(UpperCamelCase ) __UpperCAmelCase : Tuple = _sin / (2 * q_factor) __UpperCAmelCase : Optional[Any] = (1 - _cos) / 2 __UpperCAmelCase : Any = 1 - _cos __UpperCAmelCase : List[str] = 1 + alpha __UpperCAmelCase : List[Any] = -2 * _cos __UpperCAmelCase : Dict = 1 - alpha __UpperCAmelCase : str = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase = 1 / sqrt(2 ) ) -> IIRFilter: """simple docstring""" __UpperCAmelCase : int = tau * frequency / samplerate __UpperCAmelCase : Optional[Any] = sin(UpperCamelCase ) __UpperCAmelCase : Dict = cos(UpperCamelCase ) __UpperCAmelCase : Tuple = _sin / (2 * q_factor) __UpperCAmelCase : Dict = (1 + _cos) / 2 __UpperCAmelCase : Tuple = -1 - _cos __UpperCAmelCase : Any = 1 + alpha __UpperCAmelCase : int = -2 * _cos __UpperCAmelCase : int = 1 - alpha __UpperCAmelCase : Union[str, Any] = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase = 1 / sqrt(2 ) ) -> IIRFilter: """simple docstring""" __UpperCAmelCase : Tuple = tau * frequency / samplerate __UpperCAmelCase : Tuple = sin(UpperCamelCase ) __UpperCAmelCase : List[str] = cos(UpperCamelCase ) __UpperCAmelCase : List[Any] = _sin / (2 * q_factor) __UpperCAmelCase : Any = _sin / 2 __UpperCAmelCase : Optional[int] = 0 __UpperCAmelCase : int = -ba __UpperCAmelCase : Dict = 1 + alpha __UpperCAmelCase : List[str] = -2 * _cos __UpperCAmelCase : int = 1 - alpha __UpperCAmelCase : int = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase = 1 / sqrt(2 ) ) -> IIRFilter: """simple docstring""" __UpperCAmelCase : str = tau * frequency / samplerate __UpperCAmelCase : List[Any] = sin(UpperCamelCase ) __UpperCAmelCase : Any = cos(UpperCamelCase ) __UpperCAmelCase : List[str] = _sin / (2 * q_factor) __UpperCAmelCase : Optional[Any] = 1 - alpha __UpperCAmelCase : Tuple = -2 * _cos __UpperCAmelCase : List[Any] = 1 + alpha __UpperCAmelCase : str = IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = 1 / sqrt(2 ) , ) -> IIRFilter: """simple docstring""" __UpperCAmelCase : Dict = tau * frequency / samplerate __UpperCAmelCase : Optional[int] = sin(UpperCamelCase ) __UpperCAmelCase : Optional[Any] = cos(UpperCamelCase ) __UpperCAmelCase : List[Any] = _sin / (2 * q_factor) __UpperCAmelCase : List[Any] = 10 ** (gain_db / 40) __UpperCAmelCase : List[str] = 1 + alpha * big_a __UpperCAmelCase : Optional[Any] = -2 * _cos __UpperCAmelCase : int = 1 - alpha * big_a __UpperCAmelCase : Optional[int] = 1 + alpha / big_a __UpperCAmelCase : Union[str, Any] = -2 * _cos __UpperCAmelCase : Dict = 1 - alpha / big_a __UpperCAmelCase : Dict = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = 1 / sqrt(2 ) , ) -> IIRFilter: """simple docstring""" __UpperCAmelCase : str = tau * frequency / samplerate __UpperCAmelCase : int = sin(UpperCamelCase ) __UpperCAmelCase : Optional[Any] = cos(UpperCamelCase ) __UpperCAmelCase : str = _sin / (2 * q_factor) __UpperCAmelCase : str = 10 ** (gain_db / 40) __UpperCAmelCase : Union[str, Any] = (big_a + 1) - (big_a - 1) * _cos __UpperCAmelCase : Optional[int] = (big_a + 1) + (big_a - 1) * _cos __UpperCAmelCase : List[str] = (big_a - 1) - (big_a + 1) * _cos __UpperCAmelCase : List[Any] = (big_a - 1) + (big_a + 1) * _cos __UpperCAmelCase : Optional[Any] = 2 * sqrt(UpperCamelCase ) * alpha __UpperCAmelCase : Tuple = big_a * (pmc + aaa) __UpperCAmelCase : Union[str, Any] = 2 * big_a * mpc __UpperCAmelCase : Optional[int] = big_a * (pmc - aaa) __UpperCAmelCase : Any = ppmc + aaa __UpperCAmelCase : Dict = -2 * pmpc __UpperCAmelCase : Any = ppmc - aaa __UpperCAmelCase : str = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = 1 / sqrt(2 ) , ) -> IIRFilter: """simple docstring""" __UpperCAmelCase : Dict = tau * frequency / samplerate __UpperCAmelCase : Optional[int] = sin(UpperCamelCase ) __UpperCAmelCase : Dict = cos(UpperCamelCase ) __UpperCAmelCase : str = _sin / (2 * q_factor) __UpperCAmelCase : int = 10 ** (gain_db / 40) __UpperCAmelCase : Optional[Any] = (big_a + 1) - (big_a - 1) * _cos __UpperCAmelCase : Optional[int] = (big_a + 1) + (big_a - 1) * _cos __UpperCAmelCase : Union[str, Any] = (big_a - 1) - (big_a + 1) * _cos __UpperCAmelCase : Tuple = (big_a - 1) + (big_a + 1) * _cos __UpperCAmelCase : Optional[Any] = 2 * sqrt(UpperCamelCase ) * alpha __UpperCAmelCase : Tuple = big_a * (ppmc + aaa) __UpperCAmelCase : Any = -2 * big_a * pmpc __UpperCAmelCase : int = big_a * (ppmc - aaa) __UpperCAmelCase : int = pmc + aaa __UpperCAmelCase : Tuple = 2 * mpc __UpperCAmelCase : Union[str, Any] = pmc - aaa __UpperCAmelCase : Any = IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
487
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class a__ ( a__ ): '''simple docstring''' def __init__( self , *lowerCamelCase_ , **lowerCamelCase_ ) -> None: warnings.warn( '''The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use ImageGPTImageProcessor instead.''' , lowerCamelCase_ , ) super().__init__(*lowerCamelCase_ , **lowerCamelCase_ )
90
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() __a : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase ( lowercase ): """simple docstring""" __lowercase = torch.load(lowercase , map_location='''cpu''' ) if "model" in sd.keys(): __lowercase = torch.load(lowercase , map_location='''cpu''' )['''model'''] # pop unnecessary weights __lowercase = [ '''decoder.version''', '''decoder.output_projection.weight''', ] for key in keys_to_delete: if key in sd: sd.pop(lowercase ) __lowercase = { '''decoder.project_in_dim.weight''': '''decoder.project_in.weight''', '''decoder.project_out_dim.weight''': '''decoder.project_out.weight''', '''decoder.layer_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.layer_norm.bias''': '''decoder.final_layer_norm.bias''', } for old_key, new_key in keys_to_rename.items(): if old_key in sd: __lowercase = sd.pop(lowercase ) __lowercase = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: __lowercase = sd[key] # We split QKV in separate Q,K,V __lowercase = key.replace('''.qkv_proj.''' , '''.q_proj.''' ) __lowercase = key.replace('''.qkv_proj.''' , '''.k_proj.''' ) __lowercase = key.replace('''.qkv_proj.''' , '''.v_proj.''' ) __lowercase = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 __lowercase , __lowercase , __lowercase = torch.split(lowercase , depth // 3 , dim=0 ) __lowercase = q __lowercase = k __lowercase = v del sd[key] return sd @torch.no_grad() def UpperCAmelCase ( lowercase , lowercase , lowercase=None ): """simple docstring""" __lowercase = load_checkpoint(lowercase ) if config is not None: __lowercase = OPTConfig.from_pretrained(lowercase ) else: __lowercase = OPTConfig() __lowercase = OPTModel(lowercase ).half().eval() model.load_state_dict(lowercase ) # Check results Path(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) if __name__ == "__main__": __a : int = argparse.ArgumentParser() # Required parameters parser.add_argument( """--fairseq_path""", type=str, help=( """path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:""" """ https://huggingface.co/models?other=opt_metasq""" ), ) parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--hf_config""", default=None, type=str, help="""Define HF config.""") __a : Any = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
534
0
import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print("Googling.....") lowercase = "https://www.google.com/search?q=" + " ".join(sys.argv[1:]) lowercase = requests.get(url, headers={"UserAgent": UserAgent().random}) # res.raise_for_status() with open("project1a.html", "wb") as out_file: # only for knowing the class for data in res.iter_content(10000): out_file.write(data) lowercase = BeautifulSoup(res.text, "html.parser") lowercase = list(soup.select(".eZt8xd"))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get("href")) else: webbrowser.open(f'https://google.com{link.get("href")}')
607
class UpperCamelCase_ : '''simple docstring''' def __init__( self , a ) -> None: snake_case_ = set_counts snake_case_ = max(a ) snake_case_ = len(a ) snake_case_ = [1] * num_sets snake_case_ = list(range(a ) ) def _UpperCamelCase ( self , a , a ) -> bool: snake_case_ = self.get_parent(a ) snake_case_ = self.get_parent(a ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] snake_case_ = 0 snake_case_ = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 snake_case_ = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] snake_case_ = 0 snake_case_ = src_parent snake_case_ = self.set_counts[src_parent] snake_case_ = max(self.max_set , a ) return True def _UpperCamelCase ( self , a ) -> int: if self.parents[disj_set] == disj_set: return disj_set snake_case_ = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
607
1
"""simple docstring""" def lowercase_ ( __UpperCAmelCase = 1000 ) -> int: return sum(e for e in range(3 , __UpperCAmelCase ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(f"""{solution() = }""")
299
"""simple docstring""" import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _lowerCamelCase ( nn.Module ): def __init__( self : Optional[Any] ) -> Optional[int]: """simple docstring""" super().__init__() lowerCAmelCase__ : Optional[int] = nn.Linear(3 , 4 ) lowerCAmelCase__ : int = nn.BatchNormad(4 ) lowerCAmelCase__ : Optional[Any] = nn.Linear(4 , 5 ) def _lowerCAmelCase ( self : List[str] , UpperCamelCase : List[Any] ) -> Tuple: """simple docstring""" return self.lineara(self.batchnorm(self.lineara(UpperCamelCase ) ) ) class _lowerCamelCase ( unittest.TestCase ): def _lowerCAmelCase ( self : Any ) -> Optional[int]: """simple docstring""" lowerCAmelCase__ : Any = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase , model.state_dict() ) lowerCAmelCase__ : List[str] = os.path.join(UpperCamelCase , """index.json""" ) self.assertTrue(os.path.isfile(UpperCamelCase ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: lowerCAmelCase__ : Tuple = os.path.join(UpperCamelCase , f"""{key}.dat""" ) self.assertTrue(os.path.isfile(UpperCamelCase ) ) # TODO: add tests on the fact weights are properly loaded def _lowerCAmelCase ( self : Dict ) -> int: """simple docstring""" lowerCAmelCase__ : List[str] = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: lowerCAmelCase__ : Union[str, Any] = torch.randn(2 , 3 , dtype=UpperCamelCase ) with TemporaryDirectory() as tmp_dir: lowerCAmelCase__ : Optional[Any] = offload_weight(UpperCamelCase , """weight""" , UpperCamelCase , {} ) lowerCAmelCase__ : Dict = os.path.join(UpperCamelCase , """weight.dat""" ) self.assertTrue(os.path.isfile(UpperCamelCase ) ) self.assertDictEqual(UpperCamelCase , {"""weight""": {"""shape""": [2, 3], """dtype""": str(UpperCamelCase ).split(""".""" )[1]}} ) lowerCAmelCase__ : Any = load_offloaded_weight(UpperCamelCase , index["""weight"""] ) self.assertTrue(torch.equal(UpperCamelCase , UpperCamelCase ) ) def _lowerCAmelCase ( self : Optional[int] ) -> Tuple: """simple docstring""" lowerCAmelCase__ : Union[str, Any] = ModelForTest() lowerCAmelCase__ : Optional[Any] = model.state_dict() lowerCAmelCase__ : Tuple = {k: v for k, v in state_dict.items() if """linear2""" not in k} lowerCAmelCase__ : Any = {k: v for k, v in state_dict.items() if """linear2""" in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : str = OffloadedWeightsLoader(state_dict=UpperCamelCase , save_folder=UpperCamelCase ) # Every key is there with the right value self.assertEqual(sorted(UpperCamelCase ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCamelCase , weight_map[key] ) ) lowerCAmelCase__ : str = {k: v for k, v in state_dict.items() if """weight""" in k} lowerCAmelCase__ : str = {k: v for k, v in state_dict.items() if """weight""" not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : Any = OffloadedWeightsLoader(state_dict=UpperCamelCase , save_folder=UpperCamelCase ) # Every key is there with the right value self.assertEqual(sorted(UpperCamelCase ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCamelCase , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(UpperCamelCase , UpperCamelCase ) # Duplicates are removed lowerCAmelCase__ : List[str] = OffloadedWeightsLoader(state_dict=UpperCamelCase , save_folder=UpperCamelCase ) # Every key is there with the right value self.assertEqual(sorted(UpperCamelCase ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(UpperCamelCase , weight_map[key] ) ) def _lowerCAmelCase ( self : Dict ) -> Any: """simple docstring""" lowerCAmelCase__ : List[str] = {"""a.1""": 0, """a.10""": 1, """a.2""": 2} lowerCAmelCase__ : Any = extract_submodules_state_dict(UpperCamelCase , ["""a.1""", """a.2"""] ) self.assertDictEqual(UpperCamelCase , {"""a.1""": 0, """a.2""": 2} ) lowerCAmelCase__ : str = {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2} lowerCAmelCase__ : Union[str, Any] = extract_submodules_state_dict(UpperCamelCase , ["""a.1""", """a.2"""] ) self.assertDictEqual(UpperCamelCase , {"""a.1.a""": 0, """a.2.a""": 2} )
299
1
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( __lowerCamelCase ): '''simple docstring''' _UpperCamelCase : List[str] = ["""image_processor""", """tokenizer"""] _UpperCamelCase : List[Any] = """CLIPImageProcessor""" _UpperCamelCase : Optional[int] = ("""CLIPTokenizer""", """CLIPTokenizerFast""") def __init__( self , snake_case=None , snake_case=None , **snake_case ): lowercase = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , lowercase_ , ) lowercase = kwargs.pop('feature_extractor' ) lowercase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(lowercase_ , lowercase_ ) def __call__( self , snake_case=None , snake_case=None , snake_case=None , **snake_case ): if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: lowercase = self.tokenizer(lowercase_ , return_tensors=lowercase_ , **lowercase_ ) if images is not None: lowercase = self.image_processor(lowercase_ , return_tensors=lowercase_ , **lowercase_ ) if text is not None and images is not None: lowercase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**lowercase_ ) , tensor_type=lowercase_ ) def SCREAMING_SNAKE_CASE__ ( self , *snake_case , **snake_case ): return self.tokenizer.batch_decode(*lowercase_ , **lowercase_ ) def SCREAMING_SNAKE_CASE__ ( self , *snake_case , **snake_case ): return self.tokenizer.decode(*lowercase_ , **lowercase_ ) @property def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.tokenizer.model_input_names lowercase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def SCREAMING_SNAKE_CASE__ ( self ): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , lowercase_ , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE__ ( self ): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , lowercase_ , ) return self.image_processor
716
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class A_ ( __lowerCamelCase ): '''simple docstring''' _UpperCamelCase : jnp.ndarray _UpperCamelCase : jnp.ndarray class A_ ( nn.Module ): '''simple docstring''' _UpperCamelCase : int _UpperCamelCase : Tuple[int] = (16, 32, 96, 256) _UpperCamelCase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE__ ( self ): lowercase = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) lowercase = [] for i in range(len(self.block_out_channels ) - 1 ): lowercase = self.block_out_channels[i] lowercase = self.block_out_channels[i + 1] lowercase = nn.Conv( snake_case , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(snake_case ) lowercase = nn.Conv( snake_case , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(snake_case ) lowercase = blocks lowercase = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , snake_case ): lowercase = self.conv_in(snake_case ) lowercase = nn.silu(snake_case ) for block in self.blocks: lowercase = block(snake_case ) lowercase = nn.silu(snake_case ) lowercase = self.conv_out(snake_case ) return embedding @flax_register_to_config class A_ ( nn.Module , __lowerCamelCase , __lowerCamelCase ): '''simple docstring''' _UpperCamelCase : int = 32 _UpperCamelCase : int = 4 _UpperCamelCase : Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _UpperCamelCase : Union[bool, Tuple[bool]] = False _UpperCamelCase : Tuple[int] = (320, 640, 1280, 1280) _UpperCamelCase : int = 2 _UpperCamelCase : Union[int, Tuple[int]] = 8 _UpperCamelCase : Optional[Union[int, Tuple[int]]] = None _UpperCamelCase : int = 1280 _UpperCamelCase : float = 0.0 _UpperCamelCase : bool = False _UpperCamelCase : jnp.dtype = jnp.floataa _UpperCamelCase : bool = True _UpperCamelCase : int = 0 _UpperCamelCase : str = "rgb" _UpperCamelCase : Tuple[int] = (16, 32, 96, 256) def SCREAMING_SNAKE_CASE__ ( self , snake_case ): # init input tensors lowercase = (1, self.in_channels, self.sample_size, self.sample_size) lowercase = jnp.zeros(snake_case , dtype=jnp.floataa ) lowercase = jnp.ones((1,) , dtype=jnp.intaa ) lowercase = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) lowercase = (1, 3, self.sample_size * 8, self.sample_size * 8) lowercase = jnp.zeros(snake_case , dtype=jnp.floataa ) lowercase , lowercase = jax.random.split(snake_case ) lowercase = {'params': params_rng, 'dropout': dropout_rng} return self.init(snake_case , snake_case , snake_case , snake_case , snake_case )["params"] def SCREAMING_SNAKE_CASE__ ( self ): lowercase = self.block_out_channels lowercase = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. lowercase = self.num_attention_heads or self.attention_head_dim # input lowercase = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time lowercase = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) lowercase = FlaxTimestepEmbedding(snake_case , dtype=self.dtype ) lowercase = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) lowercase = self.only_cross_attention if isinstance(snake_case , snake_case ): lowercase = (only_cross_attention,) * len(self.down_block_types ) if isinstance(snake_case , snake_case ): lowercase = (num_attention_heads,) * len(self.down_block_types ) # down lowercase = [] lowercase = [] lowercase = block_out_channels[0] lowercase = nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case ) for i, down_block_type in enumerate(self.down_block_types ): lowercase = output_channel lowercase = block_out_channels[i] lowercase = i == len(snake_case ) - 1 if down_block_type == "CrossAttnDownBlock2D": lowercase = FlaxCrossAttnDownBlockaD( in_channels=snake_case , out_channels=snake_case , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: lowercase = FlaxDownBlockaD( in_channels=snake_case , out_channels=snake_case , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(snake_case ) for _ in range(self.layers_per_block ): lowercase = nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case ) if not is_final_block: lowercase = nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case ) lowercase = down_blocks lowercase = controlnet_down_blocks # mid lowercase = block_out_channels[-1] lowercase = FlaxUNetMidBlockaDCrossAttn( in_channels=snake_case , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) lowercase = nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , snake_case , snake_case , snake_case , snake_case , snake_case = 1.0 , snake_case = True , snake_case = False , ): lowercase = self.controlnet_conditioning_channel_order if channel_order == "bgr": lowercase = jnp.flip(snake_case , axis=1 ) # 1. time if not isinstance(snake_case , jnp.ndarray ): lowercase = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(snake_case , jnp.ndarray ) and len(timesteps.shape ) == 0: lowercase = timesteps.astype(dtype=jnp.floataa ) lowercase = jnp.expand_dims(snake_case , 0 ) lowercase = self.time_proj(snake_case ) lowercase = self.time_embedding(snake_case ) # 2. pre-process lowercase = jnp.transpose(snake_case , (0, 2, 3, 1) ) lowercase = self.conv_in(snake_case ) lowercase = jnp.transpose(snake_case , (0, 2, 3, 1) ) lowercase = self.controlnet_cond_embedding(snake_case ) sample += controlnet_cond # 3. down lowercase = (sample,) for down_block in self.down_blocks: if isinstance(snake_case , snake_case ): lowercase , lowercase = down_block(snake_case , snake_case , snake_case , deterministic=not train ) else: lowercase , lowercase = down_block(snake_case , snake_case , deterministic=not train ) down_block_res_samples += res_samples # 4. mid lowercase = self.mid_block(snake_case , snake_case , snake_case , deterministic=not train ) # 5. contronet blocks lowercase = () for down_block_res_sample, controlnet_block in zip(snake_case , self.controlnet_down_blocks ): lowercase = controlnet_block(snake_case ) controlnet_down_block_res_samples += (down_block_res_sample,) lowercase = controlnet_down_block_res_samples lowercase = self.controlnet_mid_block(snake_case ) # 6. scaling lowercase = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=snake_case , mid_block_res_sample=snake_case )
565
0
'''simple docstring''' import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class lowerCAmelCase__ ( UpperCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , *a__ : List[Any] , a__ : Tuple=None , a__ : List[str]=None , **a__ : Any ): super().__init__(*a__ , **a__ ) UpperCAmelCase = eval_examples UpperCAmelCase = post_process_function def __snake_case ( self : Any , a__ : Any=None , a__ : Optional[Any]=None , a__ : Dict=None , a__ : str = "eval" ): UpperCAmelCase = self.eval_dataset if eval_dataset is None else eval_dataset UpperCAmelCase = self.get_eval_dataloader(a__ ) UpperCAmelCase = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. UpperCAmelCase = self.compute_metrics UpperCAmelCase = None UpperCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop UpperCAmelCase = time.time() try: UpperCAmelCase = eval_loop( a__ , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a__ , metric_key_prefix=a__ , ) finally: UpperCAmelCase = compute_metrics UpperCAmelCase = self.args.eval_batch_size * self.args.world_size if f"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( a__ , a__ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default UpperCAmelCase = self.post_process_function(a__ , a__ , output.predictions ) UpperCAmelCase = self.compute_metrics(a__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"{metric_key_prefix}_" ): UpperCAmelCase = metrics.pop(a__ ) metrics.update(output.metrics ) else: UpperCAmelCase = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(a__ ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) UpperCAmelCase = self.callback_handler.on_evaluate(self.args , self.state , self.control , a__ ) return metrics def __snake_case ( self : str , a__ : Optional[int] , a__ : List[Any] , a__ : List[str]=None , a__ : str = "test" ): UpperCAmelCase = self.get_test_dataloader(a__ ) # Temporarily disable metric computation, we will do it in the loop here. UpperCAmelCase = self.compute_metrics UpperCAmelCase = None UpperCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop UpperCAmelCase = time.time() try: UpperCAmelCase = eval_loop( a__ , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a__ , metric_key_prefix=a__ , ) finally: UpperCAmelCase = compute_metrics UpperCAmelCase = self.args.eval_batch_size * self.args.world_size if f"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( a__ , a__ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output UpperCAmelCase = self.post_process_function(a__ , a__ , output.predictions , '''predict''' ) UpperCAmelCase = self.compute_metrics(a__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"{metric_key_prefix}_" ): UpperCAmelCase = metrics.pop(a__ ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a__ )
51
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a =logging.get_logger(__name__) # General docstring a ="""MobileNetV1Config""" # Base docstring a ="""google/mobilenet_v1_1.0_224""" a =[1, 1024, 7, 7] # Image classification docstring a ="""google/mobilenet_v1_1.0_224""" a ="""tabby, tabby cat""" a =[ """google/mobilenet_v1_1.0_224""", """google/mobilenet_v1_0.75_192""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ) -> str: __lowerCamelCase : str = {} if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : int = model.mobilenet_va else: __lowerCamelCase : List[str] = model __lowerCamelCase : List[Any] = 'MobilenetV1/Conv2d_0/' __lowerCamelCase : List[Any] = backbone.conv_stem.convolution.weight __lowerCamelCase : List[str] = backbone.conv_stem.normalization.bias __lowerCamelCase : Tuple = backbone.conv_stem.normalization.weight __lowerCamelCase : Union[str, Any] = backbone.conv_stem.normalization.running_mean __lowerCamelCase : Optional[int] = backbone.conv_stem.normalization.running_var for i in range(1_3 ): __lowerCamelCase : Any = i + 1 __lowerCamelCase : Union[str, Any] = i * 2 __lowerCamelCase : Optional[Any] = backbone.layer[pt_index] __lowerCamelCase : Optional[int] = F"MobilenetV1/Conv2d_{tf_index}_depthwise/" __lowerCamelCase : Tuple = pointer.convolution.weight __lowerCamelCase : Optional[Any] = pointer.normalization.bias __lowerCamelCase : Union[str, Any] = pointer.normalization.weight __lowerCamelCase : List[str] = pointer.normalization.running_mean __lowerCamelCase : Union[str, Any] = pointer.normalization.running_var __lowerCamelCase : int = backbone.layer[pt_index + 1] __lowerCamelCase : Union[str, Any] = F"MobilenetV1/Conv2d_{tf_index}_pointwise/" __lowerCamelCase : Optional[Any] = pointer.convolution.weight __lowerCamelCase : Any = pointer.normalization.bias __lowerCamelCase : str = pointer.normalization.weight __lowerCamelCase : Dict = pointer.normalization.running_mean __lowerCamelCase : List[str] = pointer.normalization.running_var if isinstance(lowerCamelCase__ , lowerCamelCase__ ): __lowerCamelCase : Union[str, Any] = 'MobilenetV1/Logits/Conv2d_1c_1x1/' __lowerCamelCase : Any = model.classifier.weight __lowerCamelCase : int = model.classifier.bias return tf_to_pt_map def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model __lowerCamelCase : List[str] = tf.train.list_variables(lowerCamelCase__ ) __lowerCamelCase : List[str] = {} for name, shape in init_vars: logger.info(F"Loading TF weight {name} with shape {shape}" ) __lowerCamelCase : Any = tf.train.load_variable(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[Any] = array # Build TF to PyTorch weights loading map __lowerCamelCase : Tuple = _build_tf_to_pytorch_map(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"Importing {name}" ) if name not in tf_weights: logger.info(F"{name} not in tf pre-trained weights, skipping" ) continue __lowerCamelCase : Optional[int] = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) __lowerCamelCase : List[str] = np.transpose(lowerCamelCase__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer __lowerCamelCase : Any = array.squeeze().transpose() else: __lowerCamelCase : Tuple = np.transpose(lowerCamelCase__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" ) logger.info(F"Initialize PyTorch weight {name} {array.shape}" ) __lowerCamelCase : Optional[Any] = torch.from_numpy(lowerCamelCase__ ) tf_weights.pop(lowerCamelCase__ , lowerCamelCase__ ) tf_weights.pop(name + '/RMSProp' , lowerCamelCase__ ) tf_weights.pop(name + '/RMSProp_1' , lowerCamelCase__ ) tf_weights.pop(name + '/ExponentialMovingAverage' , lowerCamelCase__ ) logger.info(F"Weights not copied to PyTorch model: {', '.join(tf_weights.keys() )}" ) return model def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> torch.Tensor: __lowerCamelCase , __lowerCamelCase : int = features.shape[-2:] __lowerCamelCase , __lowerCamelCase : List[str] = conv_layer.stride __lowerCamelCase , __lowerCamelCase : str = conv_layer.kernel_size if in_height % stride_height == 0: __lowerCamelCase : Optional[int] = max(kernel_height - stride_height , 0 ) else: __lowerCamelCase : Union[str, Any] = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: __lowerCamelCase : List[str] = max(kernel_width - stride_width , 0 ) else: __lowerCamelCase : List[str] = max(kernel_width - (in_width % stride_width) , 0 ) __lowerCamelCase : List[str] = pad_along_width // 2 __lowerCamelCase : Optional[int] = pad_along_width - pad_left __lowerCamelCase : Any = pad_along_height // 2 __lowerCamelCase : List[Any] = pad_along_height - pad_top __lowerCamelCase : Union[str, Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(lowerCamelCase__ , lowerCamelCase__ , 'constant' , 0.0 ) class A_ ( nn.Module ): def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Optional[int] = 1 ,SCREAMING_SNAKE_CASE__ : Optional[int] = 1 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : Optional[bool] = True ,SCREAMING_SNAKE_CASE__ : Optional[bool or str] = True ,): super().__init__() __lowerCamelCase : Dict = config if in_channels % groups != 0: raise ValueError(F"Input channels ({in_channels}) are not divisible by {groups} groups.") if out_channels % groups != 0: raise ValueError(F"Output channels ({out_channels}) are not divisible by {groups} groups.") __lowerCamelCase : Optional[Any] = 0 if config.tf_padding else int((kernel_size - 1) / 2) __lowerCamelCase : Optional[int] = nn.Convad( in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,groups=SCREAMING_SNAKE_CASE__ ,bias=SCREAMING_SNAKE_CASE__ ,padding_mode='zeros' ,) if use_normalization: __lowerCamelCase : Optional[int] = nn.BatchNormad( num_features=SCREAMING_SNAKE_CASE__ ,eps=config.layer_norm_eps ,momentum=0.9997 ,affine=SCREAMING_SNAKE_CASE__ ,track_running_stats=SCREAMING_SNAKE_CASE__ ,) else: __lowerCamelCase : Dict = None if use_activation: if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Dict = ACTaFN[use_activation] elif isinstance(config.hidden_act ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : str = ACTaFN[config.hidden_act] else: __lowerCamelCase : List[str] = config.hidden_act else: __lowerCamelCase : List[str] = None def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : torch.Tensor): if self.config.tf_padding: __lowerCamelCase : Any = apply_tf_padding(SCREAMING_SNAKE_CASE__ ,self.convolution) __lowerCamelCase : Optional[int] = self.convolution(SCREAMING_SNAKE_CASE__) if self.normalization is not None: __lowerCamelCase : Dict = self.normalization(SCREAMING_SNAKE_CASE__) if self.activation is not None: __lowerCamelCase : List[str] = self.activation(SCREAMING_SNAKE_CASE__) return features class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Union[str, Any] = MobileNetVaConfig _UpperCAmelCase : List[str] = load_tf_weights_in_mobilenet_va _UpperCAmelCase : List[str] = '''mobilenet_v1''' _UpperCAmelCase : Any = '''pixel_values''' _UpperCAmelCase : int = False def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[nn.Linear, nn.Convad]): if isinstance(SCREAMING_SNAKE_CASE__ ,(nn.Linear, nn.Convad)): module.weight.data.normal_(mean=0.0 ,std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(SCREAMING_SNAKE_CASE__ ,nn.BatchNormad): module.bias.data.zero_() module.weight.data.fill_(1.0) a =r""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ a =r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : int ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig ,SCREAMING_SNAKE_CASE__ : bool = True): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = config __lowerCamelCase : Optional[int] = 3_2 __lowerCamelCase : List[str] = max(int(depth * config.depth_multiplier) ,config.min_depth) __lowerCamelCase : Optional[Any] = MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=config.num_channels ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=3 ,stride=2 ,) __lowerCamelCase : Any = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] __lowerCamelCase : str = nn.ModuleList() for i in range(1_3): __lowerCamelCase : str = out_channels if strides[i] == 2 or i == 0: depth *= 2 __lowerCamelCase : str = max(int(depth * config.depth_multiplier) ,config.min_depth) self.layer.append( MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=3 ,stride=strides[i] ,groups=SCREAMING_SNAKE_CASE__ ,)) self.layer.append( MobileNetVaConvLayer( SCREAMING_SNAKE_CASE__ ,in_channels=SCREAMING_SNAKE_CASE__ ,out_channels=SCREAMING_SNAKE_CASE__ ,kernel_size=1 ,)) __lowerCamelCase : Optional[int] = nn.AdaptiveAvgPoolad((1, 1)) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Dict): raise NotImplementedError @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __lowerCamelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values') __lowerCamelCase : Optional[Any] = self.conv_stem(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = () if output_hidden_states else None for i, layer_module in enumerate(self.layer): __lowerCamelCase : Dict = layer_module(SCREAMING_SNAKE_CASE__) if output_hidden_states: __lowerCamelCase : Any = all_hidden_states + (hidden_states,) __lowerCamelCase : Optional[Any] = hidden_states if self.pooler is not None: __lowerCamelCase : Tuple = torch.flatten(self.pooler(SCREAMING_SNAKE_CASE__) ,start_dim=1) else: __lowerCamelCase : List[str] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ ,pooler_output=SCREAMING_SNAKE_CASE__ ,hidden_states=SCREAMING_SNAKE_CASE__ ,) @add_start_docstrings( ''' MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , SCREAMING_SNAKE_CASE , ) class A_ ( SCREAMING_SNAKE_CASE ): def __init__( self : Any ,SCREAMING_SNAKE_CASE__ : MobileNetVaConfig): super().__init__(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = config.num_labels __lowerCamelCase : Optional[Any] = MobileNetVaModel(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[str] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head __lowerCamelCase : Any = nn.Dropout(config.classifier_dropout_prob ,inplace=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = nn.Linear(SCREAMING_SNAKE_CASE__ ,config.num_labels) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=SCREAMING_SNAKE_CASE__ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,): __lowerCamelCase : Any = return_dict if return_dict is not None else self.config.use_return_dict __lowerCamelCase : Optional[int] = self.mobilenet_va(SCREAMING_SNAKE_CASE__ ,output_hidden_states=SCREAMING_SNAKE_CASE__ ,return_dict=SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = outputs.pooler_output if return_dict else outputs[1] __lowerCamelCase : List[str] = self.classifier(self.dropout(SCREAMING_SNAKE_CASE__)) __lowerCamelCase : List[str] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __lowerCamelCase : Dict = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __lowerCamelCase : int = 'single_label_classification' else: __lowerCamelCase : Tuple = 'multi_label_classification' if self.config.problem_type == "regression": __lowerCamelCase : Tuple = MSELoss() if self.num_labels == 1: __lowerCamelCase : int = loss_fct(logits.squeeze() ,labels.squeeze()) else: __lowerCamelCase : Union[str, Any] = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config.problem_type == "single_label_classification": __lowerCamelCase : List[str] = CrossEntropyLoss() __lowerCamelCase : List[str] = loss_fct(logits.view(-1 ,self.num_labels) ,labels.view(-1)) elif self.config.problem_type == "multi_label_classification": __lowerCamelCase : int = BCEWithLogitsLoss() __lowerCamelCase : int = loss_fct(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if not return_dict: __lowerCamelCase : List[str] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=SCREAMING_SNAKE_CASE__ ,logits=SCREAMING_SNAKE_CASE__ ,hidden_states=outputs.hidden_states ,)
652
0
'''simple docstring''' from collections import defaultdict from math import ceil, sqrt def UpperCAmelCase ( UpperCAmelCase__ : int = 1_00_00_00 , UpperCAmelCase__ : int = 10): lowerCamelCase : defaultdict = defaultdict(UpperCAmelCase__) for outer_width in range(3 , (t_limit // 4) + 2): if outer_width * outer_width > t_limit: lowerCamelCase : List[str] = max( ceil(sqrt(outer_width * outer_width - t_limit)) , 1) else: lowerCamelCase : int = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(UpperCAmelCase__ , outer_width - 1 , 2): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10) if __name__ == "__main__": print(f"""{solution() = }""")
449
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class __snake_case ( a__): _lowerCAmelCase = (DPMSolverSinglestepScheduler,) _lowerCAmelCase = (('''num_inference_steps''', 25),) def UpperCAmelCase_ ( self, **A ): """simple docstring""" lowerCamelCase : List[Any] = { 'num_train_timesteps': 1000, 'beta_start': 0.0001, '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(**A ) return config def UpperCAmelCase_ ( self, A=0, **A ): """simple docstring""" lowerCamelCase : List[str] = dict(self.forward_default_kwargs ) lowerCamelCase : Optional[Any] = kwargs.pop('num_inference_steps', A ) lowerCamelCase : Union[str, Any] = self.dummy_sample lowerCamelCase : Dict = 0.1 * sample lowerCamelCase : Dict = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: lowerCamelCase : Optional[Any] = self.get_scheduler_config(**A ) lowerCamelCase : Dict = scheduler_class(**A ) scheduler.set_timesteps(A ) # copy over dummy past residuals lowerCamelCase : str = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(A ) lowerCamelCase : List[Any] = scheduler_class.from_pretrained(A ) new_scheduler.set_timesteps(A ) # copy over dummy past residuals lowerCamelCase : Optional[int] = dummy_past_residuals[: new_scheduler.config.solver_order] lowerCamelCase , lowerCamelCase : Optional[int] = sample, sample for t in range(A, time_step + scheduler.config.solver_order + 1 ): lowerCamelCase : Dict = scheduler.step(A, A, A, **A ).prev_sample lowerCamelCase : Optional[int] = new_scheduler.step(A, A, A, **A ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def UpperCAmelCase_ ( self ): """simple docstring""" pass def UpperCAmelCase_ ( self, A=0, **A ): """simple docstring""" lowerCamelCase : List[str] = dict(self.forward_default_kwargs ) lowerCamelCase : str = kwargs.pop('num_inference_steps', A ) lowerCamelCase : Union[str, Any] = self.dummy_sample lowerCamelCase : List[str] = 0.1 * sample lowerCamelCase : List[str] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: lowerCamelCase : Tuple = self.get_scheduler_config() lowerCamelCase : Optional[Any] = scheduler_class(**A ) scheduler.set_timesteps(A ) # copy over dummy past residuals (must be after setting timesteps) lowerCamelCase : Any = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(A ) lowerCamelCase : Tuple = scheduler_class.from_pretrained(A ) # copy over dummy past residuals new_scheduler.set_timesteps(A ) # copy over dummy past residual (must be after setting timesteps) lowerCamelCase : List[Any] = dummy_past_residuals[: new_scheduler.config.solver_order] lowerCamelCase : int = scheduler.step(A, A, A, **A ).prev_sample lowerCamelCase : Dict = new_scheduler.step(A, A, A, **A ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def UpperCAmelCase_ ( self, A=None, **A ): """simple docstring""" if scheduler is None: lowerCamelCase : Any = self.scheduler_classes[0] lowerCamelCase : Optional[Any] = self.get_scheduler_config(**A ) lowerCamelCase : Optional[int] = scheduler_class(**A ) lowerCamelCase : List[Any] = self.scheduler_classes[0] lowerCamelCase : Optional[Any] = self.get_scheduler_config(**A ) lowerCamelCase : Optional[int] = scheduler_class(**A ) lowerCamelCase : Any = 10 lowerCamelCase : Dict = self.dummy_model() lowerCamelCase : Any = self.dummy_sample_deter scheduler.set_timesteps(A ) for i, t in enumerate(scheduler.timesteps ): lowerCamelCase : Dict = model(A, A ) lowerCamelCase : List[str] = scheduler.step(A, A, A ).prev_sample return sample def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Dict = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) lowerCamelCase : Dict = 50 lowerCamelCase : Tuple = self.dummy_model() lowerCamelCase : Optional[int] = self.dummy_sample_deter scheduler.set_timesteps(A ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): lowerCamelCase : Any = model(A, A ) lowerCamelCase : Optional[int] = scheduler.step(A, A, A ).prev_sample lowerCamelCase : Any = torch.mean(torch.abs(A ) ) assert abs(result_mean.item() - 0.2574 ) < 1e-3 def UpperCAmelCase_ ( self ): """simple docstring""" for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=A ) def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Dict = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) lowerCamelCase : str = self.full_loop(scheduler=A ) lowerCamelCase : Optional[int] = torch.mean(torch.abs(A ) ) assert abs(result_mean.item() - 0.2791 ) < 1e-3 lowerCamelCase : Dict = DEISMultistepScheduler.from_config(scheduler.config ) lowerCamelCase : Optional[int] = DPMSolverMultistepScheduler.from_config(scheduler.config ) lowerCamelCase : Any = UniPCMultistepScheduler.from_config(scheduler.config ) lowerCamelCase : Optional[Any] = DPMSolverSinglestepScheduler.from_config(scheduler.config ) lowerCamelCase : str = self.full_loop(scheduler=A ) lowerCamelCase : Optional[int] = torch.mean(torch.abs(A ) ) assert abs(result_mean.item() - 0.2791 ) < 1e-3 def UpperCAmelCase_ ( self ): """simple docstring""" self.check_over_configs(thresholding=A ) 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=A, prediction_type=A, sample_max_value=A, algorithm_type='dpmsolver++', solver_order=A, solver_type=A, ) def UpperCAmelCase_ ( self ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A ) def UpperCAmelCase_ ( self ): """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=A, solver_type=A, prediction_type=A, algorithm_type=A, ) lowerCamelCase : Optional[Any] = self.full_loop( solver_order=A, solver_type=A, prediction_type=A, algorithm_type=A, ) assert not torch.isnan(A ).any(), "Samples have nan numbers" def UpperCAmelCase_ ( self ): """simple docstring""" self.check_over_configs(lower_order_final=A ) self.check_over_configs(lower_order_final=A ) def UpperCAmelCase_ ( self ): """simple docstring""" self.check_over_configs(lambda_min_clipped=-float('inf' ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def UpperCAmelCase_ ( self ): """simple docstring""" self.check_over_configs(variance_type=A ) self.check_over_configs(variance_type='learned_range' ) def UpperCAmelCase_ ( self ): """simple docstring""" for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=A, time_step=0 ) def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Union[str, Any] = self.full_loop() lowerCamelCase : str = torch.mean(torch.abs(A ) ) assert abs(result_mean.item() - 0.2791 ) < 1e-3 def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Union[str, Any] = self.full_loop(use_karras_sigmas=A ) lowerCamelCase : Tuple = torch.mean(torch.abs(A ) ) assert abs(result_mean.item() - 0.2248 ) < 1e-3 def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : List[Any] = self.full_loop(prediction_type='v_prediction' ) lowerCamelCase : Dict = torch.mean(torch.abs(A ) ) assert abs(result_mean.item() - 0.1453 ) < 1e-3 def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : List[Any] = self.full_loop(prediction_type='v_prediction', use_karras_sigmas=A ) lowerCamelCase : Optional[Any] = torch.mean(torch.abs(A ) ) assert abs(result_mean.item() - 0.0649 ) < 1e-3 def UpperCAmelCase_ ( self ): """simple docstring""" lowerCamelCase : Optional[Any] = self.scheduler_classes[0] lowerCamelCase : Dict = self.get_scheduler_config(thresholding=A, dynamic_thresholding_ratio=0 ) lowerCamelCase : str = scheduler_class(**A ) lowerCamelCase : List[Any] = 10 lowerCamelCase : List[str] = self.dummy_model() lowerCamelCase : int = self.dummy_sample_deter.half() scheduler.set_timesteps(A ) for i, t in enumerate(scheduler.timesteps ): lowerCamelCase : str = model(A, A ) lowerCamelCase : Tuple = scheduler.step(A, A, A ).prev_sample assert sample.dtype == torch.floataa
449
1
'''simple docstring''' from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent A_ : str ={'''UserAgent''': UserAgent().random} def snake_case_ ( __snake_case : List[Any]) -> dict: lowerCAmelCase_ = script.contents[0] lowerCAmelCase_ = json.loads(data[data.find('''{"config"''') : -1]) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class __UpperCAmelCase : def __init__( self , _lowerCamelCase ): lowerCAmelCase_ = F'''https://www.instagram.com/{username}/''' lowerCAmelCase_ = self.get_json() def UpperCAmelCase_ ( self ): lowerCAmelCase_ = requests.get(self.url , headers=_lowerCamelCase ).text lowerCAmelCase_ = BeautifulSoup(_lowerCamelCase , '''html.parser''' ).find_all('''script''' ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self ): return F'''{self.__class__.__name__}(\'{self.username}\')''' def __str__( self ): return F'''{self.fullname} ({self.username}) is {self.biography}''' @property def UpperCAmelCase_ ( self ): return self.user_data["username"] @property def UpperCAmelCase_ ( self ): return self.user_data["full_name"] @property def UpperCAmelCase_ ( self ): return self.user_data["biography"] @property def UpperCAmelCase_ ( self ): return self.user_data["business_email"] @property def UpperCAmelCase_ ( self ): return self.user_data["external_url"] @property def UpperCAmelCase_ ( self ): return self.user_data["edge_followed_by"]["count"] @property def UpperCAmelCase_ ( self ): return self.user_data["edge_follow"]["count"] @property def UpperCAmelCase_ ( self ): return self.user_data["edge_owner_to_timeline_media"]["count"] @property def UpperCAmelCase_ ( self ): return self.user_data["profile_pic_url_hd"] @property def UpperCAmelCase_ ( self ): return self.user_data["is_verified"] @property def UpperCAmelCase_ ( self ): return self.user_data["is_private"] def snake_case_ ( __snake_case : str = "github") -> None: import os if os.environ.get('''CI'''): return # test failing on GitHub Actions lowerCAmelCase_ = InstagramUser(__snake_case) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __snake_case) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith('''https://instagram.''') assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() A_ : Optional[Any] =InstagramUser('''github''') print(instagram_user) print(f'''{instagram_user.number_of_posts = }''') print(f'''{instagram_user.number_of_followers = }''') print(f'''{instagram_user.number_of_followings = }''') print(f'''{instagram_user.email = }''') print(f'''{instagram_user.website = }''') print(f'''{instagram_user.profile_picture_url = }''') print(f'''{instagram_user.is_verified = }''') print(f'''{instagram_user.is_private = }''')
274
'''simple docstring''' import gc import threading import time import psutil import torch class __UpperCAmelCase : def __init__( self ): lowerCAmelCase_ = psutil.Process() lowerCAmelCase_ = False def UpperCAmelCase_ ( self ): lowerCAmelCase_ = -1 while True: lowerCAmelCase_ = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def UpperCAmelCase_ ( self ): lowerCAmelCase_ = True lowerCAmelCase_ = threading.Thread(target=self.peak_monitor ) lowerCAmelCase_ = True self.thread.start() def UpperCAmelCase_ ( self ): lowerCAmelCase_ = False self.thread.join() return self.cpu_memory_peak A_ : List[str] =PeakCPUMemory() def snake_case_ ( ) -> Tuple: # Time lowerCAmelCase_ = {'''time''': time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem lowerCAmelCase_ = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count()): lowerCAmelCase_ = torch.cuda.memory_allocated(__snake_case) torch.cuda.reset_peak_memory_stats() return measures def snake_case_ ( __snake_case : Any) -> List[str]: # Time lowerCAmelCase_ = {'''time''': time.time() - start_measures['''time''']} gc.collect() torch.cuda.empty_cache() # CPU mem lowerCAmelCase_ = (psutil.Process().memory_info().rss - start_measures['''cpu''']) / 2**20 lowerCAmelCase_ = (cpu_peak_tracker.stop() - start_measures['''cpu''']) / 2**20 # GPU mem for i in range(torch.cuda.device_count()): lowerCAmelCase_ = (torch.cuda.memory_allocated(__snake_case) - start_measures[str(__snake_case)]) / 2**20 lowerCAmelCase_ = (torch.cuda.max_memory_allocated(__snake_case) - start_measures[str(__snake_case)]) / 2**20 return measures def snake_case_ ( __snake_case : Dict , __snake_case : Optional[int]) -> Dict: print(F'''{description}:''') print(F'''- Time: {measures['time']:.2f}s''') for i in range(torch.cuda.device_count()): print(F'''- GPU {i} allocated: {measures[str(__snake_case)]:.2f}MiB''') lowerCAmelCase_ = measures[F'''{i}-peak'''] print(F'''- GPU {i} peak: {peak:.2f}MiB''') print(F'''- CPU RAM allocated: {measures['cpu']:.2f}MiB''') print(F'''- CPU RAM peak: {measures['cpu-peak']:.2f}MiB''')
274
1
"""simple docstring""" import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Dict = RoFormerTokenizer A_ : Optional[Any] = RoFormerTokenizerFast A_ : Optional[Any] = True A_ : List[str] = True def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' super().setUp() def _SCREAMING_SNAKE_CASE ( self : Optional[int], **_lowerCamelCase : Any ): '''simple docstring''' return self.tokenizer_class.from_pretrained('''junnyu/roformer_chinese_base''', **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Dict, **_lowerCamelCase : Optional[int] ): '''simple docstring''' return self.rust_tokenizer_class.from_pretrained('''junnyu/roformer_chinese_base''', **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = '''永和服装饰品有限公司,今天天气非常好''' __A = '''永和 服装 饰品 有限公司 , 今 天 天 气 非常 好''' return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' __A = self.get_tokenizer() __A , __A = self.get_chinese_input_output_texts() __A = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase, output_text.split() ) __A = tokens + [tokenizer.unk_token] __A = [2_29_43, 2_13_32, 3_44_31, 4_59_04, 1_17, 3_06, 12_31, 12_31, 26_53, 3_39_94, 12_66, 1_00] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ), _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = self.get_rust_tokenizer() __A , __A = self.get_chinese_input_output_texts() __A = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase, output_text.split() ) __A = tokens + [tokenizer.unk_token] __A = [2_29_43, 2_13_32, 3_44_31, 4_59_04, 1_17, 3_06, 12_31, 12_31, 26_53, 3_39_94, 12_66, 1_00] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ), _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' pass
701
"""simple docstring""" import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py lowercase_ = '.' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) lowercase_ = [ 'Assert', 'AssignVariableOp', 'EmptyTensorList', 'MergeV2Checkpoints', 'ReadVariableOp', 'ResourceGather', 'RestoreV2', 'SaveV2', 'ShardedFilename', 'StatefulPartitionedCall', 'StaticRegexFullMatch', 'VarHandleOp', ] def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" __A = SavedModel() __A = [] with open(os.path.join(__UpperCamelCase , '''utils''' , '''tf_ops''' , '''onnx.json''' ) ) as f: __A = json.load(__UpperCamelCase )['''opsets'''] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(__UpperCamelCase )] ) with open(__UpperCamelCase , '''rb''' ) as f: saved_model.ParseFromString(f.read() ) __A = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want __A = sorted(__UpperCamelCase ) __A = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(__UpperCamelCase ) if strict and len(__UpperCamelCase ) > 0: raise Exception(f'Found the following incompatible ops for the opset {opset}:\n' + incompatible_ops ) elif len(__UpperCamelCase ) > 0: print(f'Found the following incompatible ops for the opset {opset}:' ) print(*__UpperCamelCase , sep='''\n''' ) else: print(f'The saved model {saved_model_path} can properly be converted with ONNX.' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument('--saved_model_path', help='Path of the saved model to check (the .pb file).') parser.add_argument( '--opset', default=12, type=int, help='The ONNX opset against which the model has to be tested.' ) parser.add_argument( '--framework', choices=['onnx'], default='onnx', help='Frameworks against which to test the saved model.' ) parser.add_argument( '--strict', action='store_true', help='Whether make the checking strict (raise errors) or not (raise warnings)' ) lowercase_ = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
215
0
import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class A__ ( snake_case__ ): """simple docstring""" __magic_name__ = (DDPMScheduler,) def a_ ( self , **__snake_case ): snake_case = { '''num_train_timesteps''': 1_0_0_0, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**__snake_case ) return config def a_ ( self ): for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=__snake_case ) def a_ ( self ): for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__snake_case , beta_end=__snake_case ) def a_ ( self ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__snake_case ) def a_ ( self ): for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=__snake_case ) def a_ ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=__snake_case ) def a_ ( self ): self.check_over_configs(thresholding=__snake_case ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=__snake_case , prediction_type=__snake_case , sample_max_value=__snake_case , ) def a_ ( self ): for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=__snake_case ) def a_ ( self ): for t in [0, 5_0_0, 9_9_9]: self.check_over_forward(time_step=__snake_case ) def a_ ( self ): snake_case = self.scheduler_classes[0] snake_case = self.get_scheduler_config() snake_case = scheduler_class(**__snake_case ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.0_0979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.02 ) ) < 1E-5 def a_ ( self ): snake_case = self.scheduler_classes[0] snake_case = self.get_scheduler_config() snake_case = scheduler_class(**__snake_case ) snake_case = len(__snake_case ) snake_case = self.dummy_model() snake_case = self.dummy_sample_deter snake_case = torch.manual_seed(0 ) for t in reversed(range(__snake_case ) ): # 1. predict noise residual snake_case = model(__snake_case , __snake_case ) # 2. predict previous mean of sample x_t-1 snake_case = scheduler.step(__snake_case , __snake_case , __snake_case , generator=__snake_case ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance snake_case = pred_prev_sample snake_case = torch.sum(torch.abs(__snake_case ) ) snake_case = torch.mean(torch.abs(__snake_case ) ) assert abs(result_sum.item() - 258.9606 ) < 1E-2 assert abs(result_mean.item() - 0.3372 ) < 1E-3 def a_ ( self ): snake_case = self.scheduler_classes[0] snake_case = self.get_scheduler_config(prediction_type='''v_prediction''' ) snake_case = scheduler_class(**__snake_case ) snake_case = len(__snake_case ) snake_case = self.dummy_model() snake_case = self.dummy_sample_deter snake_case = torch.manual_seed(0 ) for t in reversed(range(__snake_case ) ): # 1. predict noise residual snake_case = model(__snake_case , __snake_case ) # 2. predict previous mean of sample x_t-1 snake_case = scheduler.step(__snake_case , __snake_case , __snake_case , generator=__snake_case ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance snake_case = pred_prev_sample snake_case = torch.sum(torch.abs(__snake_case ) ) snake_case = torch.mean(torch.abs(__snake_case ) ) assert abs(result_sum.item() - 202.0296 ) < 1E-2 assert abs(result_mean.item() - 0.2631 ) < 1E-3 def a_ ( self ): snake_case = self.scheduler_classes[0] snake_case = self.get_scheduler_config() snake_case = scheduler_class(**__snake_case ) snake_case = [1_0_0, 8_7, 5_0, 1, 0] scheduler.set_timesteps(timesteps=__snake_case ) snake_case = scheduler.timesteps for i, timestep in enumerate(__snake_case ): if i == len(__snake_case ) - 1: snake_case = -1 else: snake_case = timesteps[i + 1] snake_case = scheduler.previous_timestep(__snake_case ) snake_case = prev_t.item() self.assertEqual(__snake_case , __snake_case ) def a_ ( self ): snake_case = self.scheduler_classes[0] snake_case = self.get_scheduler_config() snake_case = scheduler_class(**__snake_case ) snake_case = [1_0_0, 8_7, 5_0, 5_1, 0] with self.assertRaises(__snake_case , msg='''`custom_timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=__snake_case ) def a_ ( self ): snake_case = self.scheduler_classes[0] snake_case = self.get_scheduler_config() snake_case = scheduler_class(**__snake_case ) snake_case = [1_0_0, 8_7, 5_0, 1, 0] snake_case = len(__snake_case ) with self.assertRaises(__snake_case , msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=__snake_case , timesteps=__snake_case ) def a_ ( self ): snake_case = self.scheduler_classes[0] snake_case = self.get_scheduler_config() snake_case = scheduler_class(**__snake_case ) snake_case = [scheduler.config.num_train_timesteps] with self.assertRaises( __snake_case , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=__snake_case )
550
import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class A__ ( unittest.TestCase ): """simple docstring""" def __init__( self , __snake_case , __snake_case=1_3 , __snake_case=3_0 , __snake_case=2 , __snake_case=3 , __snake_case=True , __snake_case=True , __snake_case=3_2 , __snake_case=5 , __snake_case=4 , __snake_case=3_7 , __snake_case="gelu" , __snake_case=0.1 , __snake_case=0.1 , __snake_case=1_0 , __snake_case=0.02 , ): snake_case = parent snake_case = batch_size snake_case = image_size snake_case = patch_size snake_case = num_channels snake_case = is_training snake_case = use_labels snake_case = hidden_size snake_case = num_hidden_layers snake_case = num_attention_heads snake_case = intermediate_size snake_case = hidden_act snake_case = hidden_dropout_prob snake_case = attention_probs_dropout_prob snake_case = type_sequence_label_size snake_case = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) snake_case = (image_size // patch_size) ** 2 snake_case = num_patches + 1 def a_ ( self ): snake_case = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case = ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__snake_case , initializer_range=self.initializer_range , ) return config, pixel_values def a_ ( self , __snake_case , __snake_case ): snake_case = FlaxViTModel(config=__snake_case ) snake_case = model(__snake_case ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) snake_case = (self.image_size, self.image_size) snake_case = (self.patch_size, self.patch_size) snake_case = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size) ) def a_ ( self , __snake_case , __snake_case ): snake_case = self.type_sequence_label_size snake_case = FlaxViTForImageClassification(config=__snake_case ) snake_case = model(__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images snake_case = 1 snake_case = FlaxViTForImageClassification(__snake_case ) snake_case = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case = model(__snake_case ) def a_ ( self ): snake_case = self.prepare_config_and_inputs() ( ( snake_case ) , ( snake_case ) , ) = config_and_inputs snake_case = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class A__ ( snake_case__ , unittest.TestCase ): """simple docstring""" __magic_name__ = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def a_ ( self ): snake_case = FlaxViTModelTester(self ) snake_case = ConfigTester(self , config_class=__snake_case , has_text_modality=__snake_case , hidden_size=3_7 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) def a_ ( self ): snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__snake_case ) def a_ ( self ): snake_case , snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case = model_class(__snake_case ) snake_case = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case = [*signature.parameters.keys()] snake_case = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __snake_case ) def a_ ( self ): snake_case , snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): snake_case = self._prepare_for_class(__snake_case , __snake_case ) snake_case = model_class(__snake_case ) @jax.jit def model_jitted(__snake_case , **__snake_case ): return model(pixel_values=__snake_case , **__snake_case ) with self.subTest('''JIT Enabled''' ): snake_case = model_jitted(**__snake_case ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): snake_case = model_jitted(**__snake_case ).to_tuple() self.assertEqual(len(__snake_case ) , len(__snake_case ) ) for jitted_output, output in zip(__snake_case , __snake_case ): self.assertEqual(jitted_output.shape , output.shape ) @slow def a_ ( self ): for model_class_name in self.all_model_classes: snake_case = model_class_name.from_pretrained('''google/vit-base-patch16-224''' ) snake_case = model(np.ones((1, 3, 2_2_4, 2_2_4) ) ) self.assertIsNotNone(__snake_case )
550
1
"""simple docstring""" import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : int = logging.get_logger(__name__) lowerCAmelCase_ : Dict = { '''kakaobrain/align-base''': '''https://huggingface.co/kakaobrain/align-base/resolve/main/config.json''', } class UpperCamelCase_ ( a_ ): _A : Optional[Any] = 'align_text_model' def __init__( self , snake_case__=3_05_22 , snake_case__=7_68 , snake_case__=12 , snake_case__=12 , snake_case__=30_72 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=5_12 , snake_case__=2 , snake_case__=0.02 , snake_case__=1e-12 , snake_case__=0 , snake_case__="absolute" , snake_case__=True , **snake_case__ , ) -> Union[str, Any]: """simple docstring""" super().__init__(**snake_case__ ) UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_act UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = position_embedding_type UpperCAmelCase = use_cache UpperCAmelCase = pad_token_id @classmethod def UpperCamelCase_ ( cls , snake_case__ , **snake_case__ ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(snake_case__ ) UpperCAmelCase , UpperCAmelCase = cls.get_config_dict(snake_case__ , **snake_case__ ) # get the text config dict if we are loading from AlignConfig if config_dict.get("""model_type""" ) == "align": UpperCAmelCase = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(snake_case__ , **snake_case__ ) class UpperCamelCase_ ( a_ ): _A : int = 'align_vision_model' def __init__( self , snake_case__ = 3 , snake_case__ = 6_00 , snake_case__ = 2.0 , snake_case__ = 3.1 , snake_case__ = 8 , snake_case__ = [3, 3, 5, 3, 5, 5, 3] , snake_case__ = [32, 16, 24, 40, 80, 1_12, 1_92] , snake_case__ = [16, 24, 40, 80, 1_12, 1_92, 3_20] , snake_case__ = [] , snake_case__ = [1, 2, 2, 2, 1, 2, 1] , snake_case__ = [1, 2, 2, 3, 3, 4, 1] , snake_case__ = [1, 6, 6, 6, 6, 6, 6] , snake_case__ = 0.25 , snake_case__ = "swish" , snake_case__ = 25_60 , snake_case__ = "mean" , snake_case__ = 0.02 , snake_case__ = 0.001 , snake_case__ = 0.99 , snake_case__ = 0.2 , **snake_case__ , ) -> Dict: """simple docstring""" super().__init__(**snake_case__ ) UpperCAmelCase = num_channels UpperCAmelCase = image_size UpperCAmelCase = width_coefficient UpperCAmelCase = depth_coefficient UpperCAmelCase = depth_divisor UpperCAmelCase = kernel_sizes UpperCAmelCase = in_channels UpperCAmelCase = out_channels UpperCAmelCase = depthwise_padding UpperCAmelCase = strides UpperCAmelCase = num_block_repeats UpperCAmelCase = expand_ratios UpperCAmelCase = squeeze_expansion_ratio UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dim UpperCAmelCase = pooling_type UpperCAmelCase = initializer_range UpperCAmelCase = batch_norm_eps UpperCAmelCase = batch_norm_momentum UpperCAmelCase = drop_connect_rate UpperCAmelCase = sum(snake_case__ ) * 4 @classmethod def UpperCamelCase_ ( cls , snake_case__ , **snake_case__ ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(snake_case__ ) UpperCAmelCase , UpperCAmelCase = cls.get_config_dict(snake_case__ , **snake_case__ ) # get the vision config dict if we are loading from AlignConfig if config_dict.get("""model_type""" ) == "align": UpperCAmelCase = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(snake_case__ , **snake_case__ ) class UpperCamelCase_ ( a_ ): _A : str = 'align' _A : Optional[Any] = True def __init__( self , snake_case__=None , snake_case__=None , snake_case__=6_40 , snake_case__=1.0 , snake_case__=0.02 , **snake_case__ , ) -> Tuple: """simple docstring""" super().__init__(**snake_case__ ) if text_config is None: UpperCAmelCase = {} logger.info("""text_config is None. Initializing the AlignTextConfig with default values.""" ) if vision_config is None: UpperCAmelCase = {} logger.info("""vision_config is None. Initializing the AlignVisionConfig with default values.""" ) UpperCAmelCase = AlignTextConfig(**snake_case__ ) UpperCAmelCase = AlignVisionConfig(**snake_case__ ) UpperCAmelCase = projection_dim UpperCAmelCase = temperature_init_value UpperCAmelCase = initializer_range @classmethod def UpperCamelCase_ ( cls , snake_case__ , snake_case__ , **snake_case__ ) -> Optional[int]: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **snake_case__ ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" UpperCAmelCase = copy.deepcopy(self.__dict__ ) UpperCAmelCase = self.text_config.to_dict() UpperCAmelCase = self.vision_config.to_dict() UpperCAmelCase = self.__class__.model_type return output
378
"""simple docstring""" import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ : List[Any] = logging.get_logger(__name__) lowerCAmelCase_ : Optional[Any] = { '''facebook/encodec_24khz''': '''https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json''', '''facebook/encodec_48khz''': '''https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json''', } class UpperCamelCase_ ( a_ ): _A : Dict = 'encodec' def __init__( self , snake_case__=[1.5, 3.0, 6.0, 12.0, 24.0] , snake_case__=2_40_00 , snake_case__=1 , snake_case__=False , snake_case__=None , snake_case__=None , snake_case__=1_28 , snake_case__=32 , snake_case__=1 , snake_case__=[8, 5, 4, 2] , snake_case__="weight_norm" , snake_case__=7 , snake_case__=7 , snake_case__=3 , snake_case__=2 , snake_case__=True , snake_case__="reflect" , snake_case__=2 , snake_case__=2 , snake_case__=1.0 , snake_case__=10_24 , snake_case__=None , snake_case__=True , **snake_case__ , ) -> List[Any]: """simple docstring""" UpperCAmelCase = target_bandwidths UpperCAmelCase = sampling_rate UpperCAmelCase = audio_channels UpperCAmelCase = normalize UpperCAmelCase = chunk_length_s UpperCAmelCase = overlap UpperCAmelCase = hidden_size UpperCAmelCase = num_filters UpperCAmelCase = num_residual_layers UpperCAmelCase = upsampling_ratios UpperCAmelCase = norm_type UpperCAmelCase = kernel_size UpperCAmelCase = last_kernel_size UpperCAmelCase = residual_kernel_size UpperCAmelCase = dilation_growth_rate UpperCAmelCase = use_causal_conv UpperCAmelCase = pad_mode UpperCAmelCase = compress UpperCAmelCase = num_lstm_layers UpperCAmelCase = trim_right_ratio UpperCAmelCase = codebook_size UpperCAmelCase = codebook_dim if codebook_dim is not None else hidden_size UpperCAmelCase = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( f'''self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}''' ) super().__init__(**snake_case__ ) @property def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def UpperCamelCase_ ( self ) -> int: """simple docstring""" UpperCAmelCase = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def UpperCamelCase_ ( self ) -> int: """simple docstring""" return int(10_00 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
378
1
import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device UpperCamelCase = False class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" pass @slow @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" def __a ( self :Optional[int] ): UpperCamelCase__ :Optional[Any] = VersatileDiffusionImageVariationPipeline.from_pretrained("""shi-labs/versatile-diffusion""" ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) UpperCamelCase__ :str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg""" ) UpperCamelCase__ :List[Any] = torch.manual_seed(0 ) UpperCamelCase__ :Any = pipe( image=lowerCamelCase__ , generator=lowerCamelCase__ , guidance_scale=7.5 , num_inference_steps=50 , output_type="""numpy""" , ).images UpperCamelCase__ :Optional[int] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCamelCase__ :Any = np.array([0.0441, 0.0469, 0.0507, 0.0575, 0.0632, 0.0650, 0.0865, 0.0909, 0.0945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
45
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__ : dict ) -> tuple: return (data["data"], data["target"]) def A ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ) -> XGBClassifier: UpperCamelCase__ :Tuple = XGBClassifier() classifier.fit(lowercase__ , lowercase__ ) return classifier def A ( ) -> None: UpperCamelCase__ :str = load_iris() UpperCamelCase__ , UpperCamelCase__ :int = data_handling(lowercase__ ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ :int = train_test_split( lowercase__ , lowercase__ , test_size=0.25 ) UpperCamelCase__ :Optional[int] = iris["""target_names"""] # Create an XGBoost Classifier from the training data UpperCamelCase__ :Optional[Any] = 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()
45
1
_UpperCamelCase : Dict ='Input must be a string of 8 numbers plus letter' _UpperCamelCase : Any ='TRWAGMYFPDXBNJZSQVHLCKE' def a__ (__lowercase :str ) -> bool: if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): _A : Optional[Any] = f"""Expected string as input, found {type(UpperCamelCase__ ).__name__}""" raise TypeError(UpperCamelCase__ ) _A : List[str] = spanish_id.replace('''-''' , '''''' ).upper() if len(UpperCamelCase__ ) != 9: raise ValueError(UpperCamelCase__ ) try: _A : Union[str, Any] = int(spanish_id_clean[0:8] ) _A : List[Any] = spanish_id_clean[8] except ValueError as ex: raise ValueError(UpperCamelCase__ ) from ex if letter.isdigit(): raise ValueError(UpperCamelCase__ ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
720
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder _UpperCamelCase : Union[str, Any] =logging.get_logger(__name__) # pylint: disable=invalid-name _UpperCamelCase : List[Any] =256 class UpperCAmelCase__ ( __snake_case ): __snake_case : Tuple = ["melgan"] def __init__( self ,A__ ,A__ ,A__ ,A__ ,A__ ,): super().__init__() # From MELGAN _A : Any = math.log(1E-5 ) # Matches MelGAN training. _A : int = 4.0 # Largest value for most examples _A : int = 128 self.register_modules( notes_encoder=A__ ,continuous_encoder=A__ ,decoder=A__ ,scheduler=A__ ,melgan=A__ ,) def A__ ( self ,A__ ,A__=(-1.0, 1.0) ,A__=False ): _A , _A : int = output_range if clip: _A : int = torch.clip(A__ ,self.min_value ,self.max_value ) # Scale to [0, 1]. _A : Optional[Any] = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def A__ ( self ,A__ ,A__=(-1.0, 1.0) ,A__=False ): _A , _A : Dict = input_range _A : Tuple = torch.clip(A__ ,A__ ,A__ ) if clip else outputs # Scale to [0, 1]. _A : Any = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def A__ ( self ,A__ ,A__ ,A__ ): _A : Tuple = input_tokens > 0 _A , _A : str = self.notes_encoder( encoder_input_tokens=A__ ,encoder_inputs_mask=A__ ) _A , _A : List[str] = self.continuous_encoder( encoder_inputs=A__ ,encoder_inputs_mask=A__ ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def A__ ( self ,A__ ,A__ ,A__ ): _A : str = noise_time if not torch.is_tensor(A__ ): _A : Any = torch.tensor([timesteps] ,dtype=torch.long ,device=input_tokens.device ) elif torch.is_tensor(A__ ) and len(timesteps.shape ) == 0: _A : Union[str, Any] = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _A : int = timesteps * torch.ones(input_tokens.shape[0] ,dtype=timesteps.dtype ,device=timesteps.device ) _A : Dict = self.decoder( encodings_and_masks=A__ ,decoder_input_tokens=A__ ,decoder_noise_time=A__ ) return logits @torch.no_grad() def __call__( self ,A__ ,A__ = None ,A__ = 100 ,A__ = True ,A__ = "numpy" ,A__ = None ,A__ = 1 ,): if (callback_steps is None) or ( callback_steps is not None and (not isinstance(A__ ,A__ ) or callback_steps <= 0) ): raise ValueError( f"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" f""" {type(A__ )}.""" ) _A : Any = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] ,dtype=np.floataa ) _A : Optional[int] = np.zeros([1, 0, self.n_dims] ,np.floataa ) _A : Dict = torch.ones((1, TARGET_FEATURE_LENGTH) ,dtype=A__ ,device=self.device ) for i, encoder_input_tokens in enumerate(A__ ): if i == 0: _A : str = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device ,dtype=self.decoder.dtype ) # The first chunk has no previous context. _A : Dict = torch.zeros((1, TARGET_FEATURE_LENGTH) ,dtype=A__ ,device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. _A : Optional[int] = ones _A : Tuple = self.scale_features( A__ ,output_range=[-1.0, 1.0] ,clip=A__ ) _A : Tuple = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) ,continuous_inputs=A__ ,continuous_mask=A__ ,) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop _A : Any = randn_tensor( shape=encoder_continuous_inputs.shape ,generator=A__ ,device=self.device ,dtype=self.decoder.dtype ,) # set step values self.scheduler.set_timesteps(A__ ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): _A : Union[str, Any] = self.decode( encodings_and_masks=A__ ,input_tokens=A__ ,noise_time=t / self.scheduler.config.num_train_timesteps ,) # Compute previous output: x_t -> x_t-1 _A : List[str] = self.scheduler.step(A__ ,A__ ,A__ ,generator=A__ ).prev_sample _A : Union[str, Any] = self.scale_to_features(A__ ,input_range=[-1.0, 1.0] ) _A : Optional[Any] = mel[:1] _A : int = mel.cpu().float().numpy() _A : Optional[Any] = np.concatenate([full_pred_mel, pred_mel[:1]] ,axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(A__ ,A__ ) logger.info('''Generated segment''' ,A__ ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( '''Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.''' ) elif output_type == "numpy" and self.melgan is None: raise ValueError( '''Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.''' ) if output_type == "numpy": _A : Optional[Any] = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: _A : Dict = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=A__ )
332
0
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def UpperCAmelCase__ ( UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any]=10_24 , UpperCAmelCase_ : List[Any]=10_24 , UpperCAmelCase_ : List[str]=False , **UpperCAmelCase_ : str ) -> Dict: __lowerCamelCase : str = AutoTokenizer.from_pretrained(UpperCAmelCase_ ) __lowerCamelCase : Union[str, Any] = SeqaSeqDataset(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , type_path='train' , **UpperCAmelCase_ ) __lowerCamelCase : List[str] = tok.pad_token_id def get_lens(UpperCAmelCase_ : Optional[Any] ): __lowerCamelCase : Union[str, Any] = tqdm( DataLoader(UpperCAmelCase_ , batch_size=5_12 , num_workers=8 , shuffle=UpperCAmelCase_ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) __lowerCamelCase : Optional[Any] = [] for batch in dl: __lowerCamelCase : int = batch['input_ids'].ne(UpperCAmelCase_ ).sum(1 ).tolist() __lowerCamelCase : Any = batch['labels'].ne(UpperCAmelCase_ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(UpperCAmelCase_ , UpperCAmelCase_ ): max_lens.append(max(UpperCAmelCase_ , UpperCAmelCase_ ) ) else: max_lens.extend(UpperCAmelCase_ ) return max_lens __lowerCamelCase : int = get_lens(UpperCAmelCase_ ) __lowerCamelCase : Any = SeqaSeqDataset(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , type_path='val' , **UpperCAmelCase_ ) __lowerCamelCase : Union[str, Any] = get_lens(UpperCAmelCase_ ) pickle_save(UpperCAmelCase_ , train_ds.len_file ) pickle_save(UpperCAmelCase_ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
13
"""simple docstring""" import cmath import math def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> complex: UpperCAmelCase__ : str = math.radians(lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = math.radians(lowerCAmelCase ) # Convert voltage and current to rectangular form UpperCAmelCase__ : Union[str, Any] = cmath.rect(lowerCAmelCase , lowerCAmelCase ) UpperCAmelCase__ : List[str] = cmath.rect(lowerCAmelCase , lowerCAmelCase ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
182
0
from __future__ import annotations SCREAMING_SNAKE_CASE : List[str] = tuple[int, int, int] SCREAMING_SNAKE_CASE : List[Any] = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase SCREAMING_SNAKE_CASE : int = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" # -------------------------- default selection -------------------------- # rotors -------------------------- SCREAMING_SNAKE_CASE : int = """EGZWVONAHDCLFQMSIPJBYUKXTR""" SCREAMING_SNAKE_CASE : int = """FOBHMDKEXQNRAULPGSJVTYICZW""" SCREAMING_SNAKE_CASE : Optional[int] = """ZJXESIUQLHAVRMDOYGTNFWPBKC""" # reflector -------------------------- SCREAMING_SNAKE_CASE : Dict = { """A""": """N""", """N""": """A""", """B""": """O""", """O""": """B""", """C""": """P""", """P""": """C""", """D""": """Q""", """Q""": """D""", """E""": """R""", """R""": """E""", """F""": """S""", """S""": """F""", """G""": """T""", """T""": """G""", """H""": """U""", """U""": """H""", """I""": """V""", """V""": """I""", """J""": """W""", """W""": """J""", """K""": """X""", """X""": """K""", """L""": """Y""", """Y""": """L""", """M""": """Z""", """Z""": """M""", } # -------------------------- extra rotors -------------------------- SCREAMING_SNAKE_CASE : Any = """RMDJXFUWGISLHVTCQNKYPBEZOA""" SCREAMING_SNAKE_CASE : List[str] = """SGLCPQWZHKXAREONTFBVIYJUDM""" SCREAMING_SNAKE_CASE : Any = """HVSICLTYKQUBXDWAJZOMFGPREN""" SCREAMING_SNAKE_CASE : List[str] = """RZWQHFMVDBKICJLNTUXAGYPSOE""" SCREAMING_SNAKE_CASE : List[str] = """LFKIJODBEGAMQPXVUHYSTCZRWN""" SCREAMING_SNAKE_CASE : Dict = """KOAEGVDHXPQZMLFTYWJNBRCIUS""" def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> str: # Checks if there are 3 unique rotors if (unique_rotsel := len(set(_lowerCamelCase ) )) < 3: _lowercase : Optional[Any] = F'''Please use 3 unique rotors (not {unique_rotsel})''' raise Exception(_lowerCamelCase ) # Checks if rotor positions are valid _lowercase , _lowercase , _lowercase : Optional[Any] = rotpos if not 0 < rotorposa <= len(_lowerCamelCase ): _lowercase : Dict = F'''First rotor position is not within range of 1..26 ({rotorposa}''' raise ValueError(_lowerCamelCase ) if not 0 < rotorposa <= len(_lowerCamelCase ): _lowercase : Optional[Any] = F'''Second rotor position is not within range of 1..26 ({rotorposa})''' raise ValueError(_lowerCamelCase ) if not 0 < rotorposa <= len(_lowerCamelCase ): _lowercase : Any = F'''Third rotor position is not within range of 1..26 ({rotorposa})''' raise ValueError(_lowerCamelCase ) # Validates string and returns dict _lowercase : Tuple = _plugboard(_lowerCamelCase ) return rotpos, rotsel, pbdict def UpperCamelCase_( lowerCamelCase_ ) -> Optional[Any]: # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(_lowerCamelCase , _lowerCamelCase ): _lowercase : List[str] = F'''Plugboard setting isn\'t type string ({type(_lowerCamelCase )})''' raise TypeError(_lowerCamelCase ) elif len(_lowerCamelCase ) % 2 != 0: _lowercase : Union[str, Any] = F'''Odd number of symbols ({len(_lowerCamelCase )})''' raise Exception(_lowerCamelCase ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique _lowercase : Tuple = set() for i in pbstring: if i not in abc: _lowercase : Optional[Any] = F'''\'{i}\' not in list of symbols''' raise Exception(_lowerCamelCase ) elif i in tmppbl: _lowercase : str = F'''Duplicate symbol ({i})''' raise Exception(_lowerCamelCase ) else: tmppbl.add(_lowerCamelCase ) del tmppbl # Created the dictionary _lowercase : Optional[Any] = {} for j in range(0 , len(_lowerCamelCase ) - 1 , 2 ): _lowercase : Tuple = pbstring[j + 1] _lowercase : Optional[int] = pbstring[j] return pb def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = (rotora, rotora, rotora) , lowerCamelCase_ = "" , ) -> Optional[Any]: _lowercase : Dict = text.upper() _lowercase , _lowercase , _lowercase : Optional[int] = _validator( _lowerCamelCase , _lowerCamelCase , plugb.upper() ) _lowercase , _lowercase , _lowercase : Dict = rotor_position _lowercase , _lowercase , _lowercase : List[str] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 _lowercase : Any = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: _lowercase : List[Any] = plugboard[symbol] # rotor ra -------------------------- _lowercase : int = abc.index(_lowerCamelCase ) + rotorposa _lowercase : Tuple = rotora[index % len(_lowerCamelCase )] # rotor rb -------------------------- _lowercase : Optional[int] = abc.index(_lowerCamelCase ) + rotorposa _lowercase : List[str] = rotora[index % len(_lowerCamelCase )] # rotor rc -------------------------- _lowercase : int = abc.index(_lowerCamelCase ) + rotorposa _lowercase : Optional[int] = rotora[index % len(_lowerCamelCase )] # reflector -------------------------- # this is the reason you don't need another machine to decipher _lowercase : List[Any] = reflector[symbol] # 2nd rotors _lowercase : Union[str, Any] = abc[rotora.index(_lowerCamelCase ) - rotorposa] _lowercase : str = abc[rotora.index(_lowerCamelCase ) - rotorposa] _lowercase : int = abc[rotora.index(_lowerCamelCase ) - rotorposa] # 2nd plugboard if symbol in plugboard: _lowercase : str = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_lowerCamelCase ): _lowercase : int = 0 rotorposa += 1 if rotorposa >= len(_lowerCamelCase ): _lowercase : Any = 0 rotorposa += 1 if rotorposa >= len(_lowerCamelCase ): _lowercase : List[str] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_lowerCamelCase ) return "".join(_lowerCamelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE : Union[str, Any] = """This is my Python script that emulates the Enigma machine from WWII.""" SCREAMING_SNAKE_CASE : Optional[Any] = (1, 1, 1) SCREAMING_SNAKE_CASE : Union[str, Any] = """pictures""" SCREAMING_SNAKE_CASE : str = (rotora, rotora, rotora) SCREAMING_SNAKE_CASE : Optional[int] = enigma(message, rotor_pos, rotor_sel, pb) print("Encrypted message:", en) print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
700
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class _lowerCamelCase: def __init__( self, lowerCamelCase, lowerCamelCase=13, lowerCamelCase=30, lowerCamelCase=2, lowerCamelCase=3, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=32, lowerCamelCase=5, lowerCamelCase=4, lowerCamelCase=37, lowerCamelCase="gelu", lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=10, lowerCamelCase=0.0_2, lowerCamelCase=3, lowerCamelCase=None, lowerCamelCase=2, ) -> Optional[int]: """simple docstring""" _lowercase : Any = parent _lowercase : int = batch_size _lowercase : int = image_size _lowercase : str = patch_size _lowercase : int = num_channels _lowercase : Any = is_training _lowercase : Union[str, Any] = use_labels _lowercase : Dict = hidden_size _lowercase : List[str] = num_hidden_layers _lowercase : Optional[Any] = num_attention_heads _lowercase : Optional[int] = intermediate_size _lowercase : Tuple = hidden_act _lowercase : str = hidden_dropout_prob _lowercase : Optional[Any] = attention_probs_dropout_prob _lowercase : Tuple = type_sequence_label_size _lowercase : List[str] = initializer_range _lowercase : Any = scope _lowercase : Union[str, Any] = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) _lowercase : Union[str, Any] = (image_size // patch_size) ** 2 _lowercase : Any = num_patches + 2 def UpperCamelCase ( self) -> str: """simple docstring""" _lowercase : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) _lowercase : str = None if self.use_labels: _lowercase : List[Any] = ids_tensor([self.batch_size], self.type_sequence_label_size) _lowercase : str = self.get_config() return config, pixel_values, labels def UpperCamelCase ( self) -> int: """simple docstring""" return DeiTConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, is_decoder=lowerCamelCase, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, ) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Optional[int]: """simple docstring""" _lowercase : Any = DeiTModel(config=lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : Optional[int] = model(lowerCamelCase) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> int: """simple docstring""" _lowercase : Optional[Any] = DeiTForMaskedImageModeling(config=lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : List[Any] = model(lowerCamelCase) self.parent.assertEqual( result.reconstruction.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size)) # test greyscale images _lowercase : Any = 1 _lowercase : Optional[Any] = DeiTForMaskedImageModeling(lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) _lowercase : Optional[int] = model(lowerCamelCase) self.parent.assertEqual(result.reconstruction.shape, (self.batch_size, 1, self.image_size, self.image_size)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Any: """simple docstring""" _lowercase : str = self.type_sequence_label_size _lowercase : Dict = DeiTForImageClassification(lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : List[Any] = model(lowerCamelCase, labels=lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) # test greyscale images _lowercase : Optional[Any] = 1 _lowercase : Optional[Any] = DeiTForImageClassification(lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) _lowercase : List[Any] = model(lowerCamelCase, labels=lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" _lowercase : Tuple = self.prepare_config_and_inputs() ( ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ) : List[str] = config_and_inputs _lowercase : List[str] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _lowerCamelCase( _a, _a, unittest.TestCase ): lowercase_ : Optional[Any] = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ : Optional[Any] = ( { """feature-extraction""": DeiTModel, """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ : Dict = False lowercase_ : List[str] = False lowercase_ : Union[str, Any] = False def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" _lowercase : int = DeiTModelTester(self) _lowercase : Optional[Any] = ConfigTester(self, config_class=lowerCamelCase, has_text_modality=lowerCamelCase, hidden_size=37) def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds') def UpperCamelCase ( self) -> str: """simple docstring""" pass def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" _lowercase , _lowercase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : int = model_class(lowerCamelCase) self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) _lowercase : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase, nn.Linear)) def UpperCamelCase ( self) -> int: """simple docstring""" _lowercase , _lowercase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : Any = model_class(lowerCamelCase) _lowercase : Optional[Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowercase : Union[str, Any] = [*signature.parameters.keys()] _lowercase : str = ['pixel_values'] self.assertListEqual(arg_names[:1], lowerCamelCase) def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase) def UpperCamelCase ( self) -> str: """simple docstring""" _lowercase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase) def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase=False) -> Any: """simple docstring""" _lowercase : Dict = super()._prepare_for_class(lowerCamelCase, lowerCamelCase, return_labels=lowerCamelCase) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" if not self.model_tester.is_training: return _lowercase , _lowercase : str = self.model_tester.prepare_config_and_inputs_for_common() _lowercase : Tuple = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowerCamelCase) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue _lowercase : Optional[int] = model_class(lowerCamelCase) model.to(lowerCamelCase) model.train() _lowercase : Optional[Any] = self._prepare_for_class(lowerCamelCase, lowerCamelCase, return_labels=lowerCamelCase) _lowercase : List[str] = model(**lowerCamelCase).loss loss.backward() def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" _lowercase , _lowercase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return _lowercase : Dict = False _lowercase : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowerCamelCase) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue _lowercase : str = model_class(lowerCamelCase) model.gradient_checkpointing_enable() model.to(lowerCamelCase) model.train() _lowercase : Union[str, Any] = self._prepare_for_class(lowerCamelCase, lowerCamelCase, return_labels=lowerCamelCase) _lowercase : List[Any] = model(**lowerCamelCase).loss loss.backward() def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" _lowercase , _lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() _lowercase : int = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowerCamelCase), *get_values(lowerCamelCase), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type["title"]}'''): _lowercase : List[Any] = problem_type['title'] _lowercase : str = problem_type['num_labels'] _lowercase : Optional[int] = model_class(lowerCamelCase) model.to(lowerCamelCase) model.train() _lowercase : Tuple = self._prepare_for_class(lowerCamelCase, lowerCamelCase, return_labels=lowerCamelCase) if problem_type["num_labels"] > 1: _lowercase : Dict = inputs['labels'].unsqueeze(1).repeat(1, problem_type['num_labels']) _lowercase : Optional[int] = inputs['labels'].to(problem_type['dtype']) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowerCamelCase) as warning_list: _lowercase : Dict = model(**lowerCamelCase).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''') loss.backward() @slow def UpperCamelCase ( self) -> str: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowercase : Tuple = DeiTModel.from_pretrained(lowerCamelCase) self.assertIsNotNone(lowerCamelCase) def UpperCamelCase_( ) -> List[str]: _lowercase : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class _lowerCamelCase( unittest.TestCase ): @cached_property def UpperCamelCase ( self) -> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224') if is_vision_available() else None ) @slow def UpperCamelCase ( self) -> Dict: """simple docstring""" _lowercase : Optional[int] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224').to( lowerCamelCase) _lowercase : List[str] = self.default_image_processor _lowercase : List[str] = prepare_img() _lowercase : Tuple = image_processor(images=lowerCamelCase, return_tensors='pt').to(lowerCamelCase) # forward pass with torch.no_grad(): _lowercase : int = model(**lowerCamelCase) # verify the logits _lowercase : Any = torch.Size((1, 10_00)) self.assertEqual(outputs.logits.shape, lowerCamelCase) _lowercase : Union[str, Any] = torch.tensor([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1]).to(lowerCamelCase) self.assertTrue(torch.allclose(outputs.logits[0, :3], lowerCamelCase, atol=1E-4)) @slow @require_accelerate @require_torch_gpu def UpperCamelCase ( self) -> List[Any]: """simple docstring""" _lowercase : Tuple = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224', torch_dtype=torch.floataa, device_map='auto') _lowercase : Union[str, Any] = self.default_image_processor _lowercase : Union[str, Any] = prepare_img() _lowercase : int = image_processor(images=lowerCamelCase, return_tensors='pt') _lowercase : Union[str, Any] = inputs.pixel_values.to(lowerCamelCase) # forward pass to make sure inference works in fp16 with torch.no_grad(): _lowercase : Optional[int] = model(lowerCamelCase)
354
0
"""simple docstring""" import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : Tuple = tmp_path / """cache""" UpperCamelCase : List[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): UpperCamelCase : Dict = ParquetDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE , keep_in_memory=SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : Any = tmp_path / """cache""" UpperCamelCase : Optional[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} UpperCamelCase : Union[str, Any] = features.copy() if features else default_expected_features UpperCamelCase : Optional[int] = ( Features({feature: Value(SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCamelCase : Tuple = ParquetDatasetReader(SCREAMING_SNAKE_CASE , features=SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : List[Any] = tmp_path / """cache""" UpperCamelCase : Optional[int] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} UpperCamelCase : Union[str, Any] = ParquetDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE , split=SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): if issubclass(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : int = parquet_path elif issubclass(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : List[Any] = [parquet_path] UpperCamelCase : List[str] = tmp_path / """cache""" UpperCamelCase : Dict = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} UpperCamelCase : List[str] = ParquetDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read() _check_parquet_dataset(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=("train",) ): assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for split in splits: UpperCamelCase : Union[str, Any] = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : Tuple = tmp_path / """cache""" UpperCamelCase : List[Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): UpperCamelCase : str = ParquetDatasetReader( {"""train""": parquet_path} , cache_dir=SCREAMING_SNAKE_CASE , keep_in_memory=SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : Tuple = tmp_path / """cache""" UpperCamelCase : str = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} UpperCamelCase : Union[str, Any] = features.copy() if features else default_expected_features UpperCamelCase : int = ( Features({feature: Value(SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCamelCase : Union[str, Any] = ParquetDatasetReader({"""train""": parquet_path} , features=SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): if split: UpperCamelCase : Optional[int] = {split: parquet_path} else: UpperCamelCase : Any = """train""" UpperCamelCase : str = {"""train""": parquet_path, """test""": parquet_path} UpperCamelCase : Union[str, Any] = tmp_path / """cache""" UpperCamelCase : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} UpperCamelCase : Optional[Any] = ParquetDatasetReader(SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE ).read() _check_parquet_datasetdict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : Any = ParquetDatasetWriter(SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 UpperCamelCase : str = pq.ParquetFile(tmp_path / """foo.parquet""" ) UpperCamelCase : Optional[Any] = pf.read() assert dataset.data.table == output_table def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : Any = str(shared_datadir / """test_image_rgb.jpg""" ) UpperCamelCase : Any = {"""image""": [image_path]} UpperCamelCase : List[Any] = Features({"""image""": Image()} ) UpperCamelCase : Optional[Any] = Dataset.from_dict(SCREAMING_SNAKE_CASE , features=SCREAMING_SNAKE_CASE ) UpperCamelCase : Tuple = ParquetDatasetWriter(SCREAMING_SNAKE_CASE , tmp_path / """foo.parquet""" ) assert writer.write() > 0 UpperCamelCase : Any = Dataset.from_parquet(str(tmp_path / """foo.parquet""" ) ) assert dataset.features == reloaded_dataset.features UpperCamelCase : Dict = ParquetDatasetReader(str(tmp_path / """foo.parquet""" ) , streaming=SCREAMING_SNAKE_CASE ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( """feature, expected""" , [ (Features({"""foo""": Value("""int32""" )} ), None), (Features({"""image""": Image(), """foo""": Value("""int32""" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"""nested""": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): assert get_writer_batch_size(SCREAMING_SNAKE_CASE ) == expected
102
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __magic_name__ : int = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ : List[Any] = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] __magic_name__ : Optional[int] = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] __magic_name__ : str = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): __magic_name__ : Optional[Any] = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __magic_name__ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
102
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = """▁""" snake_case = {"""vocab_file""": """sentencepiece.bpe.model"""} snake_case = { """vocab_file""": { """facebook/mbart-large-en-ro""": ( """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model""" ), """facebook/mbart-large-cc25""": ( """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model""" ), } } snake_case = { """facebook/mbart-large-en-ro""": 1_024, """facebook/mbart-large-cc25""": 1_024, } # fmt: off snake_case = ["""ar_AR""", """cs_CZ""", """de_DE""", """en_XX""", """es_XX""", """et_EE""", """fi_FI""", """fr_XX""", """gu_IN""", """hi_IN""", """it_IT""", """ja_XX""", """kk_KZ""", """ko_KR""", """lt_LT""", """lv_LV""", """my_MM""", """ne_NP""", """nl_XX""", """ro_RO""", """ru_RU""", """si_LK""", """tr_TR""", """vi_VN""", """zh_CN"""] class SCREAMING_SNAKE_CASE ( __a ): '''simple docstring''' UpperCamelCase_ : str = VOCAB_FILES_NAMES UpperCamelCase_ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : List[Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : List[str] = ['''input_ids''', '''attention_mask'''] UpperCamelCase_ : Union[str, Any] = [] UpperCamelCase_ : str = [] def __init__( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int="<s>" , UpperCAmelCase_ : str="</s>" , UpperCAmelCase_ : Tuple="</s>" , UpperCAmelCase_ : Union[str, Any]="<s>" , UpperCAmelCase_ : Union[str, Any]="<unk>" , UpperCAmelCase_ : Optional[Any]="<pad>" , UpperCAmelCase_ : List[Any]="<mask>" , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : Optional[int] , ): SCREAMING_SNAKE_CASE : List[Any] = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token SCREAMING_SNAKE_CASE : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , cls_token=a_ , pad_token=a_ , mask_token=a_ , tokenizer_file=a_ , src_lang=a_ , tgt_lang=a_ , additional_special_tokens=a_ , sp_model_kwargs=self.sp_model_kwargs , **a_ , ) SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(a_ ) ) SCREAMING_SNAKE_CASE : List[Any] = 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 SCREAMING_SNAKE_CASE : List[Any] = {"""<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 SCREAMING_SNAKE_CASE : List[Any] = 1 SCREAMING_SNAKE_CASE : List[str] = len(self.sp_model ) SCREAMING_SNAKE_CASE : Tuple = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(a_ ) } SCREAMING_SNAKE_CASE : Any = {v: k for k, v in self.lang_code_to_id.items()} SCREAMING_SNAKE_CASE : Any = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) SCREAMING_SNAKE_CASE : int = {v: k for k, v in self.fairseq_tokens_to_ids.items()} SCREAMING_SNAKE_CASE : Optional[int] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) SCREAMING_SNAKE_CASE : Union[str, Any] = src_lang if src_lang is not None else """en_XX""" SCREAMING_SNAKE_CASE : Dict = self.lang_code_to_id[self._src_lang] SCREAMING_SNAKE_CASE : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[Any] = self.__dict__.copy() SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self : List[Any] , UpperCAmelCase_ : Optional[int] ): SCREAMING_SNAKE_CASE : int = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE : Union[str, Any] = {} SCREAMING_SNAKE_CASE : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _A ( self : Any ): return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _A ( self : List[Any] ): return self._src_lang @src_lang.setter def _A ( self : List[Any] , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Optional[int] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _A ( self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a_ , token_ids_a=a_ , already_has_special_tokens=a_ ) SCREAMING_SNAKE_CASE : str = [1] * len(self.prefix_tokens ) SCREAMING_SNAKE_CASE : List[str] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(a_ )) + suffix_ones return prefix_ones + ([0] * len(a_ )) + ([0] * len(a_ )) + suffix_ones def _A ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _A ( self : List[str] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : str = [self.sep_token_id] SCREAMING_SNAKE_CASE : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _A ( self : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] , UpperCAmelCase_ : Optional[str] , **UpperCAmelCase_ : Any ): if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) SCREAMING_SNAKE_CASE : List[Any] = src_lang SCREAMING_SNAKE_CASE : Dict = self(a_ , add_special_tokens=a_ , return_tensors=a_ , **a_ ) SCREAMING_SNAKE_CASE : Dict = self.convert_tokens_to_ids(a_ ) SCREAMING_SNAKE_CASE : Optional[Any] = tgt_lang_id return inputs def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Optional[Any] = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _A ( self : List[Any] , UpperCAmelCase_ : str ): return self.sp_model.encode(a_ , out_type=a_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : List[Any] ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE : Any = self.sp_model.PieceToId(a_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _A ( self : Optional[int] , UpperCAmelCase_ : List[Any] ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _A ( self : List[str] , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[int] = """""".join(a_ ).replace(a_ , " " ).strip() return out_string def _A ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): if not os.path.isdir(a_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE : List[str] = os.path.join( a_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_ , "wb" ) as fi: SCREAMING_SNAKE_CASE : str = self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,) def _A ( self : Optional[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str = "en_XX" , UpperCAmelCase_ : Optional[List[str]] = None , UpperCAmelCase_ : str = "ro_RO" , **UpperCAmelCase_ : Dict , ): SCREAMING_SNAKE_CASE : Optional[Any] = src_lang SCREAMING_SNAKE_CASE : int = tgt_lang return super().prepare_seqaseq_batch(a_ , a_ , **a_ ) def _A ( self : Optional[Any] ): return self.set_src_lang_special_tokens(self.src_lang ) def _A ( self : Tuple ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _A ( self : Optional[Any] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : List[Any] = self.lang_code_to_id[src_lang] SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id, self.cur_lang_code] def _A ( self : Tuple , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Tuple = self.lang_code_to_id[lang] SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
706
import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask snake_case = logging.getLogger(__name__) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Union[str, Any]=-1 ): # in NER datasets, the last column is usually reserved for NER label SCREAMING_SNAKE_CASE : int = label_idx def _A ( self : Any , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[Split, str] ): if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Optional[Any] = mode.value SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(UpperCAmelCase_ , f'''{mode}.txt''' ) SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : Any = [] with open(UpperCAmelCase_ , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : List[str] = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f'''{mode}-{guid_index}''' , words=UpperCAmelCase_ , labels=UpperCAmelCase_ ) ) guid_index += 1 SCREAMING_SNAKE_CASE : Union[str, Any] = [] SCREAMING_SNAKE_CASE : Optional[int] = [] else: SCREAMING_SNAKE_CASE : str = line.split(" " ) words.append(splits[0] ) if len(UpperCAmelCase_ ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=f'''{mode}-{guid_index}''' , words=UpperCAmelCase_ , labels=UpperCAmelCase_ ) ) return examples def _A ( self : Tuple , UpperCAmelCase_ : TextIO , UpperCAmelCase_ : TextIO , UpperCAmelCase_ : List ): SCREAMING_SNAKE_CASE : List[str] = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(UpperCAmelCase_ ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: SCREAMING_SNAKE_CASE : Optional[int] = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(UpperCAmelCase_ ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def _A ( self : Optional[Any] , UpperCAmelCase_ : str ): if path: with open(UpperCAmelCase_ , "r" ) as f: SCREAMING_SNAKE_CASE : List[Any] = f.read().splitlines() if "O" not in labels: SCREAMING_SNAKE_CASE : Tuple = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def __init__( self : Union[str, Any] ): # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def _A ( self : Optional[int] , UpperCAmelCase_ : str ): if path: with open(UpperCAmelCase_ , "r" ) as f: SCREAMING_SNAKE_CASE : Dict = f.read().splitlines() if "O" not in labels: SCREAMING_SNAKE_CASE : str = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def _A ( self : Dict , UpperCAmelCase_ : Any , UpperCAmelCase_ : Union[Split, str] ): if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : str = mode.value SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(UpperCAmelCase_ , f'''{mode}.txt''' ) SCREAMING_SNAKE_CASE : Optional[Any] = 1 SCREAMING_SNAKE_CASE : str = [] with open(UpperCAmelCase_ , encoding="utf-8" ) as f: for sentence in parse_incr(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : List[str] = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(UpperCAmelCase_ ) == len(UpperCAmelCase_ ) if words: examples.append(InputExample(guid=f'''{mode}-{guid_index}''' , words=UpperCAmelCase_ , labels=UpperCAmelCase_ ) ) guid_index += 1 return examples def _A ( self : str , UpperCAmelCase_ : TextIO , UpperCAmelCase_ : TextIO , UpperCAmelCase_ : List ): SCREAMING_SNAKE_CASE : Dict = 0 for sentence in parse_incr(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = preds_list[example_id] SCREAMING_SNAKE_CASE : Any = "" for token in sentence: out += f'''{token['form']} ({token['upos']}|{s_p.pop(0 )}) ''' out += "\n" writer.write(UpperCAmelCase_ ) example_id += 1 def _A ( self : Dict , UpperCAmelCase_ : str ): if path: with open(UpperCAmelCase_ , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
488
0
"""simple docstring""" from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class lowercase_ ( yaml.SafeLoader ): '''simple docstring''' def lowerCAmelCase_ ( self : List[str] , _UpperCAmelCase : List[Any] ): _A = [self.constructed_objects[key_node] for key_node, _ in node.value] _A = [tuple(_UpperCAmelCase ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ) else key for key in keys] _A = Counter(_UpperCAmelCase ) _A = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(F'''Got duplicate yaml keys: {duplicate_keys}''' ) def lowerCAmelCase_ ( self : Tuple , _UpperCAmelCase : int , _UpperCAmelCase : Union[str, Any]=False ): _A = super().construct_mapping(_UpperCAmelCase , deep=_UpperCAmelCase ) self._check_no_duplicates_on_constructed_node(_UpperCAmelCase ) return mapping def _snake_case ( _snake_case : str ) -> Tuple[Optional[str], str]: '''simple docstring''' _A = list(readme_content.splitlines() ) if full_content and full_content[0] == "---" and "---" in full_content[1:]: _A = full_content[1:].index('---' ) + 1 _A = '\n'.join(full_content[1:sep_idx] ) return yamlblock, "\n".join(full_content[sep_idx + 1 :] ) return None, "\n".join(_snake_case ) class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' # class attributes UpperCAmelCase : Union[str, Any] = {'''train_eval_index'''} # train-eval-index in the YAML metadata @classmethod def lowerCAmelCase_ ( cls : int , _UpperCAmelCase : Path ): with open(_UpperCAmelCase , encoding='utf-8' ) as readme_file: _A , _A = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(_UpperCAmelCase ) else: return cls() def lowerCAmelCase_ ( self : str , _UpperCAmelCase : Path ): if path.exists(): with open(_UpperCAmelCase , encoding='utf-8' ) as readme_file: _A = readme_file.read() else: _A = None _A = self._to_readme(_UpperCAmelCase ) with open(_UpperCAmelCase , 'w' , encoding='utf-8' ) as readme_file: readme_file.write(_UpperCAmelCase ) def lowerCAmelCase_ ( self : int , _UpperCAmelCase : Optional[str] = None ): if readme_content is not None: _A , _A = _split_yaml_from_readme(_UpperCAmelCase ) _A = '---\n' + self.to_yaml_string() + '---\n' + content else: _A = '---\n' + self.to_yaml_string() + '---\n' return full_content @classmethod def lowerCAmelCase_ ( cls : List[str] , _UpperCAmelCase : str ): _A = yaml.load(_UpperCAmelCase , Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields _A = { (key.replace('-' , '_' ) if key.replace('-' , '_' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**_UpperCAmelCase ) def lowerCAmelCase_ ( self : Dict ): return yaml.safe_dump( { (key.replace('_' , '-' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } , sort_keys=_UpperCAmelCase , allow_unicode=_UpperCAmelCase , encoding='utf-8' , ).decode('utf-8' ) a = { '''image-classification''': [], '''translation''': [], '''image-segmentation''': [], '''fill-mask''': [], '''automatic-speech-recognition''': [], '''token-classification''': [], '''sentence-similarity''': [], '''audio-classification''': [], '''question-answering''': [], '''summarization''': [], '''zero-shot-classification''': [], '''table-to-text''': [], '''feature-extraction''': [], '''other''': [], '''multiple-choice''': [], '''text-classification''': [], '''text-to-image''': [], '''text2text-generation''': [], '''zero-shot-image-classification''': [], '''tabular-classification''': [], '''tabular-regression''': [], '''image-to-image''': [], '''tabular-to-text''': [], '''unconditional-image-generation''': [], '''text-retrieval''': [], '''text-to-speech''': [], '''object-detection''': [], '''audio-to-audio''': [], '''text-generation''': [], '''conversational''': [], '''table-question-answering''': [], '''visual-question-answering''': [], '''image-to-text''': [], '''reinforcement-learning''': [], '''voice-activity-detection''': [], '''time-series-forecasting''': [], '''document-question-answering''': [], } if __name__ == "__main__": from argparse import ArgumentParser a = ArgumentParser(usage='''Validate the yaml metadata block of a README.md file.''') ap.add_argument('''readme_filepath''') a = ap.parse_args() a = Path(args.readme_filepath) a = DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
7
import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class UpperCamelCase__ (unittest.TestCase ): '''simple docstring''' def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]: lowerCamelCase : List[Any] = jnp.ones((batch_size, length) ) / length return scores def _lowercase ( self ) -> Optional[int]: lowerCamelCase : Optional[Any] = None lowerCamelCase : Optional[Any] = 20 lowerCamelCase : List[Any] = self._get_uniform_logits(batch_size=2 , length=UpperCamelCase__ ) # tweak scores to not be uniform anymore lowerCamelCase : Optional[int] = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch lowerCamelCase : List[Any] = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax lowerCamelCase : List[Any] = jax.nn.softmax(UpperCamelCase__ , axis=-1 ) lowerCamelCase : str = FlaxTemperatureLogitsWarper(temperature=0.5 ) lowerCamelCase : Tuple = FlaxTemperatureLogitsWarper(temperature=1.3 ) lowerCamelCase : List[Any] = jax.nn.softmax(temp_dist_warper_sharper(UpperCamelCase__ , scores.copy() , cur_len=UpperCamelCase__ ) , axis=-1 ) lowerCamelCase : Optional[int] = jax.nn.softmax(temp_dist_warper_smoother(UpperCamelCase__ , scores.copy() , cur_len=UpperCamelCase__ ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def _lowercase ( self ) -> List[str]: lowerCamelCase : Dict = None lowerCamelCase : List[str] = 10 lowerCamelCase : Optional[int] = 2 # create ramp distribution lowerCamelCase : Dict = np.broadcast_to(np.arange(UpperCamelCase__ )[None, :] , (batch_size, vocab_size) ).copy() lowerCamelCase : Tuple = ramp_logits[1:, : vocab_size // 2] + vocab_size lowerCamelCase : List[Any] = FlaxTopKLogitsWarper(3 ) lowerCamelCase : str = top_k_warp(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case lowerCamelCase : Union[str, Any] = 5 lowerCamelCase : Tuple = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) lowerCamelCase : Union[str, Any] = np.broadcast_to(np.arange(UpperCamelCase__ )[None, :] , (batch_size, length) ).copy() lowerCamelCase : Union[str, Any] = top_k_warp_safety_check(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def _lowercase ( self ) -> Optional[Any]: lowerCamelCase : Dict = None lowerCamelCase : Tuple = 10 lowerCamelCase : int = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) lowerCamelCase : int = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) lowerCamelCase : Dict = FlaxTopPLogitsWarper(0.8 ) lowerCamelCase : List[str] = np.exp(top_p_warp(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 lowerCamelCase : List[str] = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) ) # check edge cases with negative and extreme logits lowerCamelCase : List[str] = np.broadcast_to(np.arange(UpperCamelCase__ )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme lowerCamelCase : str = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept lowerCamelCase : str = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) lowerCamelCase : Optional[Any] = top_p_warp(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def _lowercase ( self ) -> Optional[Any]: lowerCamelCase : int = 20 lowerCamelCase : Optional[Any] = 4 lowerCamelCase : List[str] = 0 lowerCamelCase : List[str] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=UpperCamelCase__ ) # check that min length is applied at length 5 lowerCamelCase : str = ids_tensor((batch_size, 20) , vocab_size=20 ) lowerCamelCase : Any = 5 lowerCamelCase : Optional[int] = self._get_uniform_logits(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : Optional[Any] = min_dist_processor(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float("inf" )] ) # check that min length is not applied anymore at length 15 lowerCamelCase : Union[str, Any] = self._get_uniform_logits(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : List[Any] = 15 lowerCamelCase : str = min_dist_processor(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) self.assertFalse(jnp.isinf(UpperCamelCase__ ).any() ) def _lowercase ( self ) -> List[str]: lowerCamelCase : Any = 20 lowerCamelCase : List[str] = 4 lowerCamelCase : Optional[Any] = 0 lowerCamelCase : Union[str, Any] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCamelCase__ ) # check that all scores are -inf except the bos_token_id score lowerCamelCase : Any = ids_tensor((batch_size, 1) , vocab_size=20 ) lowerCamelCase : Any = 1 lowerCamelCase : Tuple = self._get_uniform_logits(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = logits_processor(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 lowerCamelCase : str = 3 lowerCamelCase : Union[str, Any] = self._get_uniform_logits(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : Optional[int] = logits_processor(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) self.assertFalse(jnp.isinf(UpperCamelCase__ ).any() ) def _lowercase ( self ) -> Tuple: lowerCamelCase : Optional[int] = 20 lowerCamelCase : str = 4 lowerCamelCase : str = 0 lowerCamelCase : Any = 5 lowerCamelCase : Optional[int] = FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCamelCase__ , eos_token_id=UpperCamelCase__ ) # check that all scores are -inf except the eos_token_id when max_length is reached lowerCamelCase : List[str] = ids_tensor((batch_size, 4) , vocab_size=20 ) lowerCamelCase : Any = 4 lowerCamelCase : Any = self._get_uniform_logits(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : List[str] = logits_processor(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached lowerCamelCase : Optional[Any] = 3 lowerCamelCase : Optional[Any] = self._get_uniform_logits(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : Optional[int] = logits_processor(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) self.assertFalse(jnp.isinf(UpperCamelCase__ ).any() ) def _lowercase ( self ) -> Optional[int]: lowerCamelCase : str = 4 lowerCamelCase : List[str] = 10 lowerCamelCase : List[str] = 15 lowerCamelCase : Optional[int] = 2 lowerCamelCase : List[Any] = 1 lowerCamelCase : str = 15 # dummy input_ids and scores lowerCamelCase : Dict = ids_tensor((batch_size, sequence_length) , UpperCamelCase__ ) lowerCamelCase : Tuple = input_ids.copy() lowerCamelCase : List[Any] = self._get_uniform_logits(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : Optional[Any] = scores.copy() # instantiate all dist processors lowerCamelCase : Optional[Any] = FlaxTemperatureLogitsWarper(temperature=0.5 ) lowerCamelCase : str = FlaxTopKLogitsWarper(3 ) lowerCamelCase : Tuple = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors lowerCamelCase : List[str] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=UpperCamelCase__ ) lowerCamelCase : str = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCamelCase__ ) lowerCamelCase : List[str] = FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCamelCase__ , eos_token_id=UpperCamelCase__ ) lowerCamelCase : Optional[int] = 10 # no processor list lowerCamelCase : Dict = temp_dist_warp(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) lowerCamelCase : Tuple = top_k_warp(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) lowerCamelCase : List[str] = top_p_warp(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = min_dist_proc(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) lowerCamelCase : Optional[int] = bos_dist_proc(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) lowerCamelCase : Optional[Any] = eos_dist_proc(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) # with processor list lowerCamelCase : List[Any] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) lowerCamelCase : Union[str, Any] = processor(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) # scores should be equal self.assertTrue(jnp.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def _lowercase ( self ) -> Any: lowerCamelCase : List[Any] = 4 lowerCamelCase : Optional[int] = 10 lowerCamelCase : Dict = 15 lowerCamelCase : Optional[int] = 2 lowerCamelCase : Dict = 1 lowerCamelCase : Optional[Any] = 15 # dummy input_ids and scores lowerCamelCase : List[Any] = ids_tensor((batch_size, sequence_length) , UpperCamelCase__ ) lowerCamelCase : Any = input_ids.copy() lowerCamelCase : Dict = self._get_uniform_logits(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : Dict = scores.copy() # instantiate all dist processors lowerCamelCase : int = FlaxTemperatureLogitsWarper(temperature=0.5 ) lowerCamelCase : List[Any] = FlaxTopKLogitsWarper(3 ) lowerCamelCase : List[str] = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors lowerCamelCase : int = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=UpperCamelCase__ ) lowerCamelCase : List[Any] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCamelCase__ ) lowerCamelCase : Optional[Any] = FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCamelCase__ , eos_token_id=UpperCamelCase__ ) lowerCamelCase : Dict = 10 # no processor list def run_no_processor_list(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase : Dict = temp_dist_warp(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) lowerCamelCase : Tuple = top_k_warp(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) lowerCamelCase : Optional[int] = top_p_warp(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) lowerCamelCase : int = min_dist_proc(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) lowerCamelCase : Optional[Any] = bos_dist_proc(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) lowerCamelCase : Dict = eos_dist_proc(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) return scores # with processor list def run_processor_list(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase : Optional[Any] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) lowerCamelCase : Tuple = processor(UpperCamelCase__ , UpperCamelCase__ , cur_len=UpperCamelCase__ ) return scores lowerCamelCase : Dict = jax.jit(UpperCamelCase__ ) lowerCamelCase : Optional[int] = jax.jit(UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = jitted_run_no_processor_list(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : Optional[Any] = jitted_run_processor_list(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # scores should be equal self.assertTrue(jnp.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
311
0
"""simple docstring""" def lowerCamelCase_ ( _lowerCamelCase ): if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError('only integers accepted as input' ) else: lowerCamelCase__ : List[Any] = str(abs(_lowerCamelCase ) ) lowerCamelCase__ : Any = [list(_lowerCamelCase ) for char in range(len(_lowerCamelCase ) )] for index in range(len(_lowerCamelCase ) ): num_transpositions[index].pop(_lowerCamelCase ) return max( int(''.join(list(_lowerCamelCase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
721
"""simple docstring""" import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList A_ : str = ["\nclass", "\ndef", "\n#", "\n@", "\nprint", "\nif"] class a_ ( snake_case_ ): '''simple docstring''' def __init__(self, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_=None, lowerCamelCase_=1 ): '''simple docstring''' lowerCamelCase__ : Any = tokenizer lowerCamelCase__ : Optional[Any] = dataset lowerCamelCase__ : int = len(lowerCamelCase_ ) if n_tasks is None else n_tasks lowerCamelCase__ : Any = n_copies def __iter__(self ): '''simple docstring''' lowerCamelCase__ : Dict = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['prompt'].strip() ) lowerCamelCase__ : Optional[int] = self.tokenizer(lowerCamelCase_, padding=lowerCamelCase_, return_tensors='pt' ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class a_ ( snake_case_ ): '''simple docstring''' def __init__(self, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ ): '''simple docstring''' lowerCamelCase__ : Any = start_length lowerCamelCase__ : List[str] = eof_strings lowerCamelCase__ : List[str] = tokenizer def __call__(self, lowerCamelCase_, lowerCamelCase_, **lowerCamelCase_ ): '''simple docstring''' lowerCamelCase__ : Any = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) lowerCamelCase__ : Optional[Any] = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(lowerCamelCase_ ) def lowerCamelCase_ ( _lowerCamelCase ): lowerCamelCase__ : Optional[Any] = re.split('(%s)' % '|'.join(_lowerCamelCase ) , _lowerCamelCase ) # last string should be "" return "".join(string_list[:-2] ) def lowerCamelCase_ ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=20 , **_lowerCamelCase ): lowerCamelCase__ : List[str] = defaultdict(_lowerCamelCase ) # dict of list of generated tokens for step, batch in tqdm(enumerate(_lowerCamelCase ) ): with torch.no_grad(): lowerCamelCase__ : str = batch['ids'].shape[-1] lowerCamelCase__ : int = accelerator.unwrap_model(_lowerCamelCase ).generate( input_ids=batch['ids'][:, : batch['input_len']] , num_return_sequences=_lowerCamelCase , **_lowerCamelCase ) # each task is generated batch_size times lowerCamelCase__ : Optional[Any] = batch['task_id'].repeat(_lowerCamelCase ) lowerCamelCase__ : List[Any] = accelerator.pad_across_processes( _lowerCamelCase , dim=1 , pad_index=tokenizer.pad_token_id ) lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = accelerator.gather((generated_tokens, generated_tasks) ) lowerCamelCase__ : List[Any] = generated_tokens.cpu().numpy() lowerCamelCase__ : Union[str, Any] = generated_tasks.cpu().numpy() for task, generated_tokens in zip(_lowerCamelCase , _lowerCamelCase ): gen_token_dict[task].append(_lowerCamelCase ) lowerCamelCase__ : str = [[] for _ in range(_lowerCamelCase )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: lowerCamelCase__ : Optional[Any] = tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase ) code_gens[task].append(remove_last_block(_lowerCamelCase ) ) return code_gens def lowerCamelCase_ ( ): # Setup configuration lowerCamelCase__ : int = HfArgumentParser(_lowerCamelCase ) lowerCamelCase__ : Optional[int] = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric lowerCamelCase__ : List[str] = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing lowerCamelCase__ : Tuple = 'false' if args.num_workers is None: lowerCamelCase__ : List[Any] = multiprocessing.cpu_count() # Use dataset load to feed to accelerate lowerCamelCase__ : List[Any] = Accelerator() set_seed(args.seed , device_specific=_lowerCamelCase ) # Load model and tokenizer lowerCamelCase__ : Any = AutoTokenizer.from_pretrained(args.model_ckpt ) lowerCamelCase__ : Optional[int] = tokenizer.eos_token lowerCamelCase__ : Any = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings lowerCamelCase__ : Optional[Any] = { 'do_sample': args.do_sample, 'temperature': args.temperature, 'max_new_tokens': args.max_new_tokens, 'top_p': args.top_p, 'top_k': args.top_k, 'stopping_criteria': StoppingCriteriaList([EndOfFunctionCriteria(0 , _lowerCamelCase , _lowerCamelCase )] ), } # Load evaluation dataset and metric lowerCamelCase__ : Any = load_dataset('openai_humaneval' ) lowerCamelCase__ : Optional[int] = load_metric('code_eval' ) lowerCamelCase__ : List[Any] = args.num_tasks if args.num_tasks is not None else len(human_eval['test'] ) lowerCamelCase__ : Optional[int] = args.n_samples // args.batch_size lowerCamelCase__ : Tuple = TokenizedDataset(_lowerCamelCase , human_eval['test'] , n_copies=_lowerCamelCase , n_tasks=_lowerCamelCase ) # do not confuse args.batch_size, which is actually the num_return_sequences lowerCamelCase__ : Union[str, Any] = DataLoader(_lowerCamelCase , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: lowerCamelCase__ : List[Any] = code_eval_metric.compute(references=[''] , predictions=[['']] ) except ValueError as exception: print( 'Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`' ' flag to enable code evaluation.' ) raise exception lowerCamelCase__ , lowerCamelCase__ : str = accelerator.prepare(_lowerCamelCase , _lowerCamelCase ) lowerCamelCase__ : Any = complete_code( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , n_tasks=_lowerCamelCase , batch_size=args.batch_size , **_lowerCamelCase , ) if accelerator.is_main_process: lowerCamelCase__ : List[str] = [] for task in tqdm(range(_lowerCamelCase ) ): lowerCamelCase__ : int = human_eval['test'][task]['test'] lowerCamelCase__ : Union[str, Any] = f'''check({human_eval['test'][task]['entry_point']})''' references.append('\n' + test_func + '\n' + entry_point ) # Evaluate completions with "code_eval" metric lowerCamelCase__ , lowerCamelCase__ : Any = code_eval_metric.compute( references=_lowerCamelCase , predictions=_lowerCamelCase , num_workers=args.num_workers ) print(f'''Results: {pass_at_k}''' ) # Save results to json file with open(args.output_file , 'w' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
696
0
from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class A : '''simple docstring''' def __init__( self : Optional[int] , _UpperCamelCase : Dict , ): _lowercase: Any = parent _lowercase: Tuple = 13 _lowercase: int = 7 _lowercase: Any = True _lowercase: List[str] = True _lowercase: Optional[int] = True _lowercase: List[Any] = 99 _lowercase: Any = 32 _lowercase: Optional[Any] = 2 _lowercase: List[Any] = 4 _lowercase: Dict = 37 _lowercase: List[Any] = "gelu" _lowercase: Any = 0.1 _lowercase: Dict = 0.1 _lowercase: Optional[int] = 512 _lowercase: Any = 16 _lowercase: Tuple = 2 _lowercase: Optional[Any] = 0.0_2 _lowercase: Any = 3 _lowercase: Dict = 4 _lowercase: str = None def UpperCAmelCase__ ( self : List[str]): _lowercase: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _lowercase: Any = None if self.use_input_mask: _lowercase: List[Any] = random_attention_mask([self.batch_size, self.seq_length]) _lowercase: Union[str, Any] = None _lowercase: Union[str, Any] = None _lowercase: List[Any] = None if self.use_labels: _lowercase: int = ids_tensor([self.batch_size] , self.type_sequence_label_size) _lowercase: str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) _lowercase: List[Any] = ids_tensor([self.batch_size] , self.num_choices) _lowercase: Union[str, Any] = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , 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 config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : List[Any]): ( ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ): Optional[Any] = self.prepare_config_and_inputs() _lowercase: List[Any] = True _lowercase: str = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) _lowercase: str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase__ ( self : Union[str, Any] , _UpperCamelCase : List[str] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Any , _UpperCamelCase : Dict , _UpperCamelCase : Optional[int] , _UpperCamelCase : Union[str, Any]): _lowercase: Tuple = TFEsmModel(config=_UpperCamelCase) _lowercase: str = {"input_ids": input_ids, "attention_mask": input_mask} _lowercase: Optional[int] = model(_UpperCamelCase) _lowercase: Optional[int] = [input_ids, input_mask] _lowercase: int = model(_UpperCamelCase) _lowercase: Tuple = model(_UpperCamelCase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCAmelCase__ ( self : Any , _UpperCamelCase : Optional[int] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : str , _UpperCamelCase : List[str] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : int , _UpperCamelCase : Tuple , _UpperCamelCase : Any , ): _lowercase: Dict = True _lowercase: Optional[Any] = TFEsmModel(config=_UpperCamelCase) _lowercase: Any = { "input_ids": input_ids, "attention_mask": input_mask, "encoder_hidden_states": encoder_hidden_states, "encoder_attention_mask": encoder_attention_mask, } _lowercase: Optional[int] = model(_UpperCamelCase) _lowercase: Optional[int] = [input_ids, input_mask] _lowercase: List[Any] = model(_UpperCamelCase , encoder_hidden_states=_UpperCamelCase) # Also check the case where encoder outputs are not passed _lowercase: Dict = model(_UpperCamelCase , attention_mask=_UpperCamelCase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCAmelCase__ ( self : List[str] , _UpperCamelCase : str , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Any , _UpperCamelCase : int , _UpperCamelCase : Tuple , _UpperCamelCase : int): _lowercase: int = TFEsmForMaskedLM(config=_UpperCamelCase) _lowercase: List[str] = model([input_ids, input_mask]) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def UpperCAmelCase__ ( self : str , _UpperCamelCase : List[Any] , _UpperCamelCase : str , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Dict , _UpperCamelCase : Any , _UpperCamelCase : List[str]): _lowercase: Union[str, Any] = self.num_labels _lowercase: int = TFEsmForTokenClassification(config=_UpperCamelCase) _lowercase: Tuple = {"input_ids": input_ids, "attention_mask": input_mask} _lowercase: Union[str, Any] = model(_UpperCamelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def UpperCAmelCase__ ( self : Tuple): _lowercase: Tuple = self.prepare_config_and_inputs() ( ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ): List[Any] = config_and_inputs _lowercase: str = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class A ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): '''simple docstring''' lowerCamelCase : Optional[Any] = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) lowerCamelCase : Tuple = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) lowerCamelCase : str = False lowerCamelCase : Tuple = False def UpperCAmelCase__ ( self : Tuple): _lowercase: List[str] = TFEsmModelTester(self) _lowercase: str = ConfigTester(self , config_class=_UpperCamelCase , hidden_size=37) def UpperCAmelCase__ ( self : int): self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : Tuple): _lowercase: int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCamelCase) def UpperCAmelCase__ ( self : Any): _lowercase: List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_UpperCamelCase) def UpperCAmelCase__ ( self : Union[str, Any]): _lowercase: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_UpperCamelCase) def UpperCAmelCase__ ( self : Tuple): _lowercase: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_UpperCamelCase) @slow def UpperCAmelCase__ ( self : Optional[int]): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowercase: Tuple = TFEsmModel.from_pretrained(_UpperCamelCase) self.assertIsNotNone(_UpperCamelCase) @unittest.skip("Protein models do not support embedding resizing.") def UpperCAmelCase__ ( self : List[str]): pass @unittest.skip("Protein models do not support embedding resizing.") def UpperCAmelCase__ ( self : Tuple): pass def UpperCAmelCase__ ( self : Optional[Any]): _lowercase , _lowercase: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase: List[str] = model_class(_UpperCamelCase) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer _lowercase: List[str] = model.get_bias() assert isinstance(_UpperCamelCase , _UpperCamelCase) for k, v in name.items(): assert isinstance(_UpperCamelCase , tf.Variable) else: _lowercase: List[str] = model.get_output_embeddings() assert x is None _lowercase: int = model.get_bias() assert name is None @require_tf class A ( unittest.TestCase ): '''simple docstring''' @slow def UpperCAmelCase__ ( self : Any): _lowercase: Any = TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D") _lowercase: List[str] = tf.constant([[0, 1, 2, 3, 4, 5]]) _lowercase: Optional[Any] = model(_UpperCamelCase)[0] _lowercase: Union[str, Any] = [1, 6, 33] self.assertEqual(list(output.numpy().shape) , _UpperCamelCase) # compare the actual values for a slice. _lowercase: Optional[int] = tf.constant( [ [ [8.9_2_1_5_1_8, -10.589_814, -6.4_6_7_1_3_0_7], [-6.3_9_6_7_1_5_6, -13.911_377, -1.1_2_1_1_9_1_5], [-7.7_8_1_2_4_7, -13.951_557, -3.7_4_0_5_9_2], ] ]) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-2)) @slow def UpperCAmelCase__ ( self : Optional[Any]): _lowercase: List[str] = TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D") _lowercase: Tuple = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]) _lowercase: Union[str, Any] = model(_UpperCamelCase)[0] # compare the actual values for a slice. _lowercase: Any = tf.constant( [ [ [0.1_4_4_4_3_0_9_2, 0.5_4_1_2_5_3_2_7, 0.3_2_4_7_7_3_9], [0.3_0_3_4_0_4_8_4, 0.0_0_5_2_6_6_7_6, 0.3_1_0_7_7_7_2_2], [0.3_2_2_7_8_0_4_3, -0.2_4_9_8_7_0_9_6, 0.3_4_1_4_6_2_8], ] ]) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4))
226
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class __lowerCamelCase ( unittest.TestCase ): @parameterized.expand([(None,), ('''foo.json''',)] ) def UpperCAmelCase__ ( self , UpperCAmelCase ): lowerCamelCase_ = GenerationConfig( do_sample=UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(UpperCAmelCase , config_name=UpperCAmelCase ) lowerCamelCase_ = GenerationConfig.from_pretrained(UpperCAmelCase , config_name=UpperCAmelCase ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , UpperCAmelCase ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , UpperCAmelCase ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = AutoConfig.from_pretrained('''gpt2''' ) lowerCamelCase_ = GenerationConfig.from_model_config(UpperCAmelCase ) lowerCamelCase_ = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(UpperCAmelCase , UpperCAmelCase ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = GenerationConfig() lowerCamelCase_ = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } lowerCamelCase_ = copy.deepcopy(UpperCAmelCase ) lowerCamelCase_ = generation_config.update(**UpperCAmelCase ) # update_kwargs was not modified (no side effects) self.assertEqual(UpperCAmelCase , UpperCAmelCase ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(UpperCAmelCase , {'''foo''': '''bar'''} ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = GenerationConfig() lowerCamelCase_ = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir: generation_config.save_pretrained(UpperCAmelCase ) lowerCamelCase_ = GenerationConfig.from_pretrained(UpperCAmelCase ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''' ) lowerCamelCase_ = GenerationConfig.from_model_config(UpperCAmelCase ) assert not hasattr(UpperCAmelCase , '''foo''' ) # no new kwargs should be initialized if from config def UpperCAmelCase__ ( self ): lowerCamelCase_ = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , UpperCAmelCase ) self.assertEqual(default_config.num_beams , 1 ) lowerCamelCase_ = GenerationConfig( do_sample=UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , UpperCAmelCase ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(UpperCAmelCase ) lowerCamelCase_ = GenerationConfig.from_pretrained(UpperCAmelCase , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , UpperCAmelCase ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class __lowerCamelCase ( unittest.TestCase ): @classmethod def UpperCAmelCase__ ( cls ): lowerCamelCase_ = TOKEN HfFolder.save_token(UpperCAmelCase ) @classmethod def UpperCAmelCase__ ( cls ): try: delete_repo(token=cls._token , repo_id='''test-generation-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' ) except HTTPError: pass def UpperCAmelCase__ ( self ): lowerCamelCase_ = GenerationConfig( do_sample=UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token ) lowerCamelCase_ = GenerationConfig.from_pretrained(f"{USER}/test-generation-config" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( UpperCAmelCase , repo_id='''test-generation-config''' , push_to_hub=UpperCAmelCase , use_auth_token=self._token ) lowerCamelCase_ = GenerationConfig.from_pretrained(f"{USER}/test-generation-config" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = GenerationConfig( do_sample=UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token ) lowerCamelCase_ = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( UpperCAmelCase , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=UpperCAmelCase , use_auth_token=self._token ) lowerCamelCase_ = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) )
29
0
"""simple docstring""" import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class __lowercase : """simple docstring""" def __init__(self , lowercase__ , lowercase__=13 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=99 , lowercase__=64 , lowercase__=32 , lowercase__=5 , lowercase__=4 , lowercase__=37 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=5_12 , lowercase__=16 , lowercase__=2 , lowercase__=0.02 , lowercase__=3 , lowercase__=4 , lowercase__=None , ): snake_case_ : Optional[Any] = parent snake_case_ : Optional[Any] = batch_size snake_case_ : str = seq_length snake_case_ : Union[str, Any] = is_training snake_case_ : Tuple = use_input_mask snake_case_ : int = use_token_type_ids snake_case_ : List[Any] = use_labels snake_case_ : List[Any] = vocab_size snake_case_ : Any = hidden_size snake_case_ : Tuple = embedding_size snake_case_ : List[Any] = num_hidden_layers snake_case_ : Optional[Any] = num_attention_heads snake_case_ : List[str] = intermediate_size snake_case_ : List[str] = hidden_act snake_case_ : Dict = hidden_dropout_prob snake_case_ : List[Any] = attention_probs_dropout_prob snake_case_ : Tuple = max_position_embeddings snake_case_ : Optional[int] = type_vocab_size snake_case_ : List[str] = type_sequence_label_size snake_case_ : Optional[int] = initializer_range snake_case_ : Any = num_labels snake_case_ : Any = num_choices snake_case_ : Optional[int] = scope def __UpperCamelCase (self ): snake_case_ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ : Union[str, Any] = None if self.use_input_mask: snake_case_ : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ : Dict = None if self.use_token_type_ids: snake_case_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ : Dict = None snake_case_ : Tuple = None snake_case_ : Optional[Any] = None if self.use_labels: snake_case_ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ : int = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ : Optional[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase (self ): return MegatronBertConfig( 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 , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__snake_case , initializer_range=self.initializer_range , ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): snake_case_ : Dict = MegatronBertModel(config=__snake_case ) model.to(__snake_case ) model.eval() snake_case_ : Tuple = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case ) snake_case_ : str = model(__snake_case , token_type_ids=__snake_case ) snake_case_ : Optional[int] = model(__snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): snake_case_ : Dict = MegatronBertForMaskedLM(config=__snake_case ) model.to(__snake_case ) model.eval() snake_case_ : List[Any] = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): snake_case_ : Any = MegatronBertForCausalLM(config=__snake_case ) model.to(__snake_case ) model.eval() snake_case_ : str = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): snake_case_ : Dict = MegatronBertForNextSentencePrediction(config=__snake_case ) model.to(__snake_case ) model.eval() snake_case_ : int = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): snake_case_ : Dict = MegatronBertForPreTraining(config=__snake_case ) model.to(__snake_case ) model.eval() snake_case_ : Optional[Any] = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case , next_sentence_label=__snake_case , ) 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 __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): snake_case_ : Dict = MegatronBertForQuestionAnswering(config=__snake_case ) model.to(__snake_case ) model.eval() snake_case_ : Tuple = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , start_positions=__snake_case , end_positions=__snake_case , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): snake_case_ : int = self.num_labels snake_case_ : List[str] = MegatronBertForSequenceClassification(__snake_case ) model.to(__snake_case ) model.eval() snake_case_ : List[str] = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): snake_case_ : Optional[Any] = self.num_labels snake_case_ : int = MegatronBertForTokenClassification(config=__snake_case ) model.to(__snake_case ) model.eval() snake_case_ : Any = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ): snake_case_ : Optional[Any] = self.num_choices snake_case_ : Tuple = MegatronBertForMultipleChoice(config=__snake_case ) model.to(__snake_case ) model.eval() snake_case_ : List[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ : List[str] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ : Dict = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase (self ): snake_case_ : List[str] = self.prepare_config_and_inputs() ( snake_case_ ) : Optional[Any] = config_and_inputs snake_case_ : List[Any] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowercase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase): """simple docstring""" _A : Tuple = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) _A : Tuple = ( { """feature-extraction""": MegatronBertModel, """fill-mask""": MegatronBertForMaskedLM, """question-answering""": MegatronBertForQuestionAnswering, """text-classification""": MegatronBertForSequenceClassification, """text-generation""": MegatronBertForCausalLM, """token-classification""": MegatronBertForTokenClassification, """zero-shot""": MegatronBertForSequenceClassification, } if is_torch_available() else {} ) _A : List[str] = True # test_resize_embeddings = False _A : Union[str, Any] = False def __UpperCamelCase (self , lowercase__ , lowercase__ , lowercase__=False ): snake_case_ : Union[str, Any] = super()._prepare_for_class(__snake_case , __snake_case , return_labels=__snake_case ) if return_labels: if model_class in get_values(__snake_case ): snake_case_ : int = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__snake_case ) snake_case_ : str = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__snake_case ) return inputs_dict def __UpperCamelCase (self ): snake_case_ : List[Any] = MegatronBertModelTester(self ) snake_case_ : Union[str, Any] = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def __UpperCamelCase (self ): self.config_tester.run_common_tests() def __UpperCamelCase (self ): snake_case_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*__snake_case ) def __UpperCamelCase (self ): snake_case_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*__snake_case ) def __UpperCamelCase (self ): snake_case_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*__snake_case ) def __UpperCamelCase (self ): snake_case_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*__snake_case ) def __UpperCamelCase (self ): snake_case_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*__snake_case ) def __UpperCamelCase (self ): snake_case_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*__snake_case ) def __UpperCamelCase (self ): snake_case_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*__snake_case ) def __UpperCamelCase (self ): snake_case_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*__snake_case ) def SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): return torch.tensor( a_ , dtype=torch.long , device=a_ , ) a_ = 1E-4 @require_torch @require_sentencepiece @require_tokenizers class __lowercase ( unittest.TestCase): """simple docstring""" @slow @unittest.skip("""Model is not available.""" ) def __UpperCamelCase (self ): snake_case_ : Union[str, Any] = '''nvidia/megatron-bert-uncased-345m''' if "MYDIR" in os.environ: snake_case_ : Any = os.path.join(os.environ["""MYDIR"""] , __snake_case ) snake_case_ : Union[str, Any] = MegatronBertModel.from_pretrained(__snake_case ) model.to(__snake_case ) model.half() snake_case_ : List[str] = _long_tensor([[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]] ) with torch.no_grad(): snake_case_ : Any = model(__snake_case )[0] snake_case_ : Tuple = torch.Size((1, 9, 10_24) ) self.assertEqual(output.shape , __snake_case ) snake_case_ : str = [-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728] for ii in range(3 ): for jj in range(3 ): snake_case_ : int = output[0, ii, jj] snake_case_ : str = expected[3 * ii + jj] snake_case_ : Union[str, Any] = '''ii={} jj={} a={} b={}'''.format(__snake_case , __snake_case , __snake_case , __snake_case ) self.assertTrue(math.isclose(__snake_case , __snake_case , rel_tol=__snake_case , abs_tol=__snake_case ) , msg=__snake_case )
704
"""simple docstring""" from copy import deepcopy class __lowercase : """simple docstring""" def __init__(self , lowercase__ = None , lowercase__ = None ): if arr is None and size is not None: snake_case_ : str = size snake_case_ : Optional[Any] = [0] * size elif arr is not None: self.init(lowercase__ ) else: raise ValueError("""Either arr or size must be specified""" ) def __UpperCamelCase (self , lowercase__ ): snake_case_ : Optional[Any] = len(lowercase__ ) snake_case_ : int = deepcopy(lowercase__ ) for i in range(1 , self.size ): snake_case_ : Optional[Any] = self.next_(lowercase__ ) if j < self.size: self.tree[j] += self.tree[i] def __UpperCamelCase (self ): snake_case_ : Dict = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): snake_case_ : Optional[int] = self.next_(lowercase__ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def __UpperCamelCase (lowercase__ ): return index + (index & (-index)) @staticmethod def __UpperCamelCase (lowercase__ ): return index - (index & (-index)) def __UpperCamelCase (self , lowercase__ , lowercase__ ): if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value snake_case_ : Tuple = self.next_(lowercase__ ) def __UpperCamelCase (self , lowercase__ , lowercase__ ): self.add(lowercase__ , value - self.get(lowercase__ ) ) def __UpperCamelCase (self , lowercase__ ): if right == 0: return 0 snake_case_ : List[str] = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] snake_case_ : Optional[int] = self.prev(lowercase__ ) return result def __UpperCamelCase (self , lowercase__ , lowercase__ ): return self.prefix(lowercase__ ) - self.prefix(lowercase__ ) def __UpperCamelCase (self , lowercase__ ): return self.query(lowercase__ , index + 1 ) def __UpperCamelCase (self , lowercase__ ): value -= self.tree[0] if value < 0: return -1 snake_case_ : Tuple = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 snake_case_ : Tuple = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
48
0
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class lowerCAmelCase_ ( _a ): def snake_case_ ( self ) -> int: UpperCamelCase : str = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type, pa.intaa() ) def snake_case_ ( self ) -> str: with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = pa.array(TypedSequence([1, 2, 3] ), type=pa.intaa() ) def snake_case_ ( self ) -> int: with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = pa.array(TypedSequence([1, 2, 3], try_type=Value('bool' ), type=Value('int64' ) ) ) def snake_case_ ( self ) -> Dict: UpperCamelCase : Tuple = pa.array(TypedSequence([1, 2, 3], type=Value('int32' ) ) ) self.assertEqual(arr.type, pa.intaa() ) def snake_case_ ( self ) -> List[str]: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase : Dict = pa.array(TypedSequence(['foo', 'bar'], type=Value('int64' ) ) ) def snake_case_ ( self ) -> Union[str, Any]: UpperCamelCase : Optional[Any] = pa.array(TypedSequence([1, 2, 3], try_type=Value('int32' ) ) ) self.assertEqual(arr.type, pa.intaa() ) def snake_case_ ( self ) -> List[Any]: UpperCamelCase : List[Any] = pa.array(TypedSequence(['foo', 'bar'], try_type=Value('int64' ) ) ) self.assertEqual(arr.type, pa.string() ) def snake_case_ ( self ) -> List[str]: UpperCamelCase : Union[str, Any] = pa.array(TypedSequence([[[1, 2, 3]]], type=ArrayaD((1, 3), 'int64' ) ) ) self.assertEqual(arr.type, ArrayaDExtensionType((1, 3), 'int64' ) ) def snake_case_ ( self ) -> Union[str, Any]: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase : List[Any] = pa.array(TypedSequence(['foo', 'bar'], type=ArrayaD((1, 3), 'int64' ) ) ) def snake_case_ ( self ) -> List[Any]: UpperCamelCase : Optional[int] = pa.array(TypedSequence([[[1, 2, 3]]], try_type=ArrayaD((1, 3), 'int64' ) ) ) self.assertEqual(arr.type, ArrayaDExtensionType((1, 3), 'int64' ) ) def snake_case_ ( self ) -> Tuple: UpperCamelCase : Tuple = pa.array(TypedSequence(['foo', 'bar'], try_type=ArrayaD((1, 3), 'int64' ) ) ) self.assertEqual(arr.type, pa.string() ) @require_pil def snake_case_ ( self ) -> List[str]: import PIL.Image UpperCamelCase : Any = PIL.Image.fromarray(np.arange(10, dtype=np.uinta ).reshape(2, 5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects', side_effect=SCREAMING_SNAKE_CASE_ ) as mock_cast_to_python_objects: UpperCamelCase : str = pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image], type=Image() ) ) UpperCamelCase , UpperCamelCase : Tuple = mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting', SCREAMING_SNAKE_CASE_ ) self.assertFalse(kwargs['optimize_list_casting'] ) def UpperCamelCase ( snake_case__ : List[str] , snake_case__ : int ) -> Optional[Any]: UpperCamelCase : str = pa.BufferReader(snake_case__ ) if isinstance(snake_case__ , pa.Buffer ) else pa.memory_map(snake_case__ ) UpperCamelCase : Union[str, Any] = pa.ipc.open_stream(snake_case__ ) UpperCamelCase : Dict = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('writer_batch_size' , [None, 1, 10] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def UpperCamelCase ( snake_case__ : int , snake_case__ : Tuple ) -> List[str]: UpperCamelCase : Dict = pa.BufferOutputStream() UpperCamelCase : Union[str, Any] = pa.schema(snake_case__ ) if fields else None with ArrowWriter(stream=snake_case__ , schema=snake_case__ , writer_batch_size=snake_case__ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) UpperCamelCase , UpperCamelCase : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : Any = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(snake_case__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def UpperCamelCase ( ) -> Tuple: UpperCamelCase : str = pa.BufferOutputStream() UpperCamelCase : str = Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=snake_case__ , features=snake_case__ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) UpperCamelCase , UpperCamelCase : Optional[int] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata UpperCamelCase : List[str] = pa.BufferReader(output.getvalue() ) UpperCamelCase : Union[str, Any] = pa.ipc.open_stream(snake_case__ ) UpperCamelCase : Optional[int] = f.read_all() UpperCamelCase : List[str] = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(snake_case__ ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 10] ) def UpperCamelCase ( snake_case__ : Optional[Any] ) -> str: UpperCamelCase : Union[str, Any] = pa.BufferOutputStream() with ArrowWriter( stream=snake_case__ , writer_batch_size=snake_case__ , hash_salt='split_name' , check_duplicates=snake_case__ , ) as writer: with pytest.raises(snake_case__ ): writer.write({'col_1': 'foo', 'col_2': 1} , key=[1, 2] ) UpperCamelCase , UpperCamelCase : Dict = writer.finalize() @pytest.mark.parametrize('writer_batch_size' , [None, 2, 10] ) def UpperCamelCase ( snake_case__ : Optional[Any] ) -> Optional[int]: UpperCamelCase : Optional[int] = pa.BufferOutputStream() with ArrowWriter( stream=snake_case__ , writer_batch_size=snake_case__ , hash_salt='split_name' , check_duplicates=snake_case__ , ) as writer: with pytest.raises(snake_case__ ): writer.write({'col_1': 'foo', 'col_2': 1} , key=10 ) writer.write({'col_1': 'bar', 'col_2': 2} , key=10 ) UpperCamelCase , UpperCamelCase : Optional[Any] = writer.finalize() @pytest.mark.parametrize('writer_batch_size' , [None, 2, 10] ) def UpperCamelCase ( snake_case__ : str ) -> Optional[int]: UpperCamelCase : Optional[Any] = pa.BufferOutputStream() with ArrowWriter( stream=snake_case__ , writer_batch_size=snake_case__ , hash_salt='split_name' , check_duplicates=snake_case__ , ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} , key=1 ) writer.write({'col_1': 'bar', 'col_2': 2} , key=2 ) UpperCamelCase , UpperCamelCase : List[str] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 10] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def UpperCamelCase ( snake_case__ : Optional[int] , snake_case__ : Union[str, Any] ) -> List[Any]: UpperCamelCase : Tuple = pa.BufferOutputStream() UpperCamelCase : Dict = pa.schema(snake_case__ ) if fields else None with ArrowWriter(stream=snake_case__ , schema=snake_case__ , writer_batch_size=snake_case__ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) UpperCamelCase , UpperCamelCase : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : List[Any] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(snake_case__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 10] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def UpperCamelCase ( snake_case__ : Optional[Any] , snake_case__ : Optional[int] ) -> List[str]: UpperCamelCase : Union[str, Any] = pa.BufferOutputStream() UpperCamelCase : List[Any] = pa.schema(snake_case__ ) if fields else None with ArrowWriter(stream=snake_case__ , schema=snake_case__ , writer_batch_size=snake_case__ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) UpperCamelCase , UpperCamelCase : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : Optional[Any] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(snake_case__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 10] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def UpperCamelCase ( snake_case__ : Any , snake_case__ : Dict ) -> Optional[int]: UpperCamelCase : Any = pa.BufferOutputStream() UpperCamelCase : Any = pa.schema(snake_case__ ) if fields else None with ArrowWriter(stream=snake_case__ , schema=snake_case__ , writer_batch_size=snake_case__ ) as writer: writer.write_row(pa.Table.from_pydict({'col_1': ['foo'], 'col_2': [1]} ) ) writer.write_row(pa.Table.from_pydict({'col_1': ['bar'], 'col_2': [2]} ) ) UpperCamelCase , UpperCamelCase : Optional[int] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase : Optional[Any] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(snake_case__ , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def UpperCamelCase ( ) -> List[Any]: with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase : str = {'col_1': pa.string(), 'col_2': pa.intaa()} UpperCamelCase : int = os.path.join(snake_case__ , 'test.arrow' ) with ArrowWriter(path=snake_case__ , schema=pa.schema(snake_case__ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) UpperCamelCase , UpperCamelCase : Any = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(snake_case__ , metadata=writer._schema.metadata ) _check_output(snake_case__ , 1 ) def UpperCamelCase ( snake_case__ : str ) -> Dict: if pa.types.is_list(snake_case__ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def UpperCamelCase ( snake_case__ : List[str] , snake_case__ : Optional[Any] ) -> Union[str, Any]: if isinstance(lst[0] , snake_case__ ): change_first_primitive_element_in_list(lst[0] , snake_case__ ) else: UpperCamelCase : Dict = value @pytest.mark.parametrize('optimized_int_type, expected_dtype' , [(None, pa.intaa()), (Value('int32' ), pa.intaa())] ) @pytest.mark.parametrize('sequence' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def UpperCamelCase ( snake_case__ : int , snake_case__ : Tuple , snake_case__ : Any ) -> Tuple: UpperCamelCase : Dict = pa.array(TypedSequence(snake_case__ , optimized_int_type=snake_case__ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( 'col, expected_dtype' , [ ('attention_mask', pa.inta()), ('special_tokens_mask', pa.inta()), ('token_type_ids', pa.inta()), ('input_ids', pa.intaa()), ('other', pa.intaa()), ] , ) @pytest.mark.parametrize('sequence' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def UpperCamelCase ( snake_case__ : str , snake_case__ : Tuple , snake_case__ : Tuple ) -> Dict: UpperCamelCase : Optional[Any] = pa.array(OptimizedTypedSequence(snake_case__ , col=snake_case__ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications UpperCamelCase : Tuple = copy.deepcopy(snake_case__ ) UpperCamelCase : str = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(snake_case__ , snake_case__ ) UpperCamelCase : List[str] = pa.array(OptimizedTypedSequence(snake_case__ , col=snake_case__ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception' , [False, True] ) def UpperCamelCase ( snake_case__ : Dict , snake_case__ : int ) -> Any: UpperCamelCase : List[Any] = str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=snake_case__ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def UpperCamelCase ( snake_case__ : int ) -> Optional[Any]: UpperCamelCase : List[Any] = 'mock://dataset-train.arrow' with ArrowWriter(path=snake_case__ , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(snake_case__ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) UpperCamelCase , UpperCamelCase : Optional[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(snake_case__ ) def UpperCamelCase ( ) -> Union[str, Any]: UpperCamelCase : str = pa.BufferOutputStream() with ParquetWriter(stream=snake_case__ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) UpperCamelCase , UpperCamelCase : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 UpperCamelCase : int = pa.BufferReader(output.getvalue() ) UpperCamelCase : Optional[Any] = pq.read_table(snake_case__ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files' , [False, True] ) def UpperCamelCase ( snake_case__ : Tuple , snake_case__ : List[str] ) -> str: import PIL.Image UpperCamelCase : str = str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(snake_case__ , format='png' ) UpperCamelCase : Optional[int] = pa.BufferOutputStream() with ParquetWriter( stream=snake_case__ , features=Features({'image': Image()} ) , embed_local_files=snake_case__ ) as writer: writer.write({'image': image_path} ) writer.finalize() UpperCamelCase : Union[str, Any] = pa.BufferReader(output.getvalue() ) UpperCamelCase : str = pq.read_table(snake_case__ ) UpperCamelCase : List[str] = pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'] , snake_case__ ) with open(snake_case__ , 'rb' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def UpperCamelCase ( ) -> str: UpperCamelCase : str = pa.schema([pa.field('col_1' , pa.string() , nullable=snake_case__ )] ) UpperCamelCase : Tuple = pa.BufferOutputStream() with ArrowWriter(stream=snake_case__ ) as writer: writer._build_writer(inferred_schema=snake_case__ ) assert writer._schema == pa.schema([pa.field('col_1' , pa.string() )] )
40
"""simple docstring""" import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class SCREAMING_SNAKE_CASE__ ( _a , unittest.TestCase ): _a = BertJapaneseTokenizer _a = False _a = True def __lowercase ( self : Any ): super().setUp() lowerCAmelCase = [ """[UNK]""", """[CLS]""", """[SEP]""", """こんにちは""", """こん""", """にちは""", """ばんは""", """##こん""", """##にちは""", """##ばんは""", """世界""", """##世界""", """、""", """##、""", """。""", """##。""", ] lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def __lowercase ( self : int , lowerCAmelCase : List[Any] ): lowerCAmelCase = """こんにちは、世界。 \nこんばんは、世界。""" lowerCAmelCase = """こんにちは 、 世界 。 こんばんは 、 世界 。""" return input_text, output_text def __lowercase ( self : Optional[Any] , lowerCAmelCase : List[Any] ): lowerCAmelCase , lowerCAmelCase = self.get_input_output_texts(lowerCAmelCase ) lowerCAmelCase = tokenizer.encode(lowerCAmelCase , add_special_tokens=lowerCAmelCase ) lowerCAmelCase = tokenizer.decode(lowerCAmelCase , clean_up_tokenization_spaces=lowerCAmelCase ) return text, ids def __lowercase ( self : List[str] ): pass # TODO add if relevant def __lowercase ( self : Optional[Any] ): pass # TODO add if relevant def __lowercase ( self : Any ): pass # TODO add if relevant def __lowercase ( self : List[Any] ): lowerCAmelCase = self.tokenizer_class(self.vocab_file ) lowerCAmelCase = tokenizer.tokenize("""こんにちは、世界。\nこんばんは、世界。""" ) self.assertListEqual(lowerCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) def __lowercase ( self : int ): lowerCAmelCase = self.tokenizer_class(self.vocab_file , word_tokenizer_type="""mecab""" ) self.assertIsNotNone(lowerCAmelCase ) lowerCAmelCase = """こんにちは、世界。\nこんばんは、世界。""" lowerCAmelCase = tokenizer.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) lowerCAmelCase = os.path.join(self.tmpdirname , """tokenizer.bin""" ) with open(lowerCAmelCase , """wb""" ) as handle: pickle.dump(lowerCAmelCase , lowerCAmelCase ) with open(lowerCAmelCase , """rb""" ) as handle: lowerCAmelCase = pickle.load(lowerCAmelCase ) lowerCAmelCase = tokenizer_new.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) def __lowercase ( self : str ): lowerCAmelCase = MecabTokenizer(mecab_dic="""ipadic""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , ) def __lowercase ( self : int ): try: lowerCAmelCase = MecabTokenizer(mecab_dic="""unidic_lite""" ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , ) def __lowercase ( self : Optional[int] ): try: lowerCAmelCase = MecabTokenizer(mecab_dic="""unidic""" ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , ) def __lowercase ( self : Any ): lowerCAmelCase = MecabTokenizer(do_lower_case=lowerCAmelCase , mecab_dic="""ipadic""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iphone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , ) def __lowercase ( self : Optional[int] ): try: lowerCAmelCase = MecabTokenizer( do_lower_case=lowerCAmelCase , normalize_text=lowerCAmelCase , mecab_option="""-d /usr/local/lib/mecab/dic/jumandic""" ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , ) def __lowercase ( self : int ): lowerCAmelCase = MecabTokenizer(normalize_text=lowerCAmelCase , mecab_dic="""ipadic""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップルストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """ """, """。"""] , ) @require_sudachi def __lowercase ( self : List[Any] ): lowerCAmelCase = self.tokenizer_class(self.vocab_file , word_tokenizer_type="""sudachi""" ) self.assertIsNotNone(lowerCAmelCase ) lowerCAmelCase = """こんにちは、世界。\nこんばんは、世界。""" lowerCAmelCase = tokenizer.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) lowerCAmelCase = os.path.join(self.tmpdirname , """tokenizer.bin""" ) with open(lowerCAmelCase , """wb""" ) as handle: pickle.dump(lowerCAmelCase , lowerCAmelCase ) with open(lowerCAmelCase , """rb""" ) as handle: lowerCAmelCase = pickle.load(lowerCAmelCase ) lowerCAmelCase = tokenizer_new.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) @require_sudachi def __lowercase ( self : str ): lowerCAmelCase = SudachiTokenizer(sudachi_dict_type="""core""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , [""" """, """\t""", """アップル""", """ストア""", """で""", """iPhone""", """8""", """ """, """が""", """ """, """ """, """\n """, """発売""", """さ""", """れ""", """た""", """ """, """。""", """ """, """ """] , ) @require_sudachi def __lowercase ( self : str ): lowerCAmelCase = SudachiTokenizer(sudachi_dict_type="""core""" , sudachi_split_mode="""A""" ) self.assertListEqual(tokenizer.tokenize("""外国人参政権""" ) , ["""外国""", """人""", """参政""", """権"""] ) @require_sudachi def __lowercase ( self : Dict ): lowerCAmelCase = SudachiTokenizer(sudachi_dict_type="""core""" , sudachi_split_mode="""B""" ) self.assertListEqual(tokenizer.tokenize("""外国人参政権""" ) , ["""外国人""", """参政権"""] ) @require_sudachi def __lowercase ( self : int ): lowerCAmelCase = SudachiTokenizer(sudachi_dict_type="""core""" , sudachi_split_mode="""C""" ) self.assertListEqual(tokenizer.tokenize("""外国人参政権""" ) , ["""外国人参政権"""] ) @require_sudachi def __lowercase ( self : str ): lowerCAmelCase = SudachiTokenizer(do_lower_case=lowerCAmelCase , sudachi_dict_type="""core""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , [""" """, """\t""", """アップル""", """ストア""", """で""", """iphone""", """8""", """ """, """が""", """ """, """ """, """\n """, """発売""", """さ""", """れ""", """た""", """ """, """。""", """ """, """ """] , ) @require_sudachi def __lowercase ( self : Tuple ): lowerCAmelCase = SudachiTokenizer(normalize_text=lowerCAmelCase , sudachi_dict_type="""core""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , [""" """, """\t""", """アップル""", """ストア""", """で""", """iPhone""", """8""", """ """, """が""", """ """, """ """, """\n """, """発売""", """さ""", """れ""", """た""", """\u3000""", """。""", """ """, """ """] , ) @require_sudachi def __lowercase ( self : List[Any] ): lowerCAmelCase = SudachiTokenizer(trim_whitespace=lowerCAmelCase , sudachi_dict_type="""core""" ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れ""", """た""", """。"""] , ) @require_jumanpp def __lowercase ( self : List[Any] ): lowerCAmelCase = self.tokenizer_class(self.vocab_file , word_tokenizer_type="""jumanpp""" ) self.assertIsNotNone(lowerCAmelCase ) lowerCAmelCase = """こんにちは、世界。\nこんばんは、世界。""" lowerCAmelCase = tokenizer.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , ["""こんにちは""", """、""", """世界""", """。""", """こん""", """##ばんは""", """、""", """世界""", """。"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) lowerCAmelCase = os.path.join(self.tmpdirname , """tokenizer.bin""" ) with open(lowerCAmelCase , """wb""" ) as handle: pickle.dump(lowerCAmelCase , lowerCAmelCase ) with open(lowerCAmelCase , """rb""" ) as handle: lowerCAmelCase = pickle.load(lowerCAmelCase ) lowerCAmelCase = tokenizer_new.tokenize(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) @require_jumanpp def __lowercase ( self : Optional[Any] ): lowerCAmelCase = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """\u3000""", """が""", """\u3000""", """\u3000""", """\u3000""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , ) @require_jumanpp def __lowercase ( self : Optional[Any] ): lowerCAmelCase = JumanppTokenizer(do_lower_case=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iphone""", """8""", """\u3000""", """が""", """\u3000""", """\u3000""", """\u3000""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , ) @require_jumanpp def __lowercase ( self : int ): lowerCAmelCase = JumanppTokenizer(normalize_text=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""ア""", """ッ""", """フ""", """゚""", """ル""", """ストア""", """で""", """iPhone""", """8""", """\u3000""", """が""", """\u3000""", """\u3000""", """\u3000""", """発売""", """さ""", """れた""", """\u3000""", """。"""] , ) @require_jumanpp def __lowercase ( self : Any ): lowerCAmelCase = JumanppTokenizer(trim_whitespace=lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tアップルストアでiPhone8 が \n 発売された 。 """ ) , ["""アップル""", """ストア""", """で""", """iPhone""", """8""", """が""", """発売""", """さ""", """れた""", """。"""] , ) @require_jumanpp def __lowercase ( self : Tuple ): lowerCAmelCase = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize("""ありがとうございますm(_ _)m見つけるのが大変です。""" ) , ["""ありがとう""", """ございます""", """m(_ _)m""", """見つける""", """の""", """が""", """大変です""", """。"""] , ) def __lowercase ( self : str ): lowerCAmelCase = ["""[UNK]""", """[CLS]""", """[SEP]""", """こんにちは""", """こん""", """にちは""", """ばんは""", """##こん""", """##にちは""", """##ばんは"""] lowerCAmelCase = {} for i, token in enumerate(lowerCAmelCase ): lowerCAmelCase = i lowerCAmelCase = WordpieceTokenizer(vocab=lowerCAmelCase , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""こんにちは""" ) , ["""こんにちは"""] ) self.assertListEqual(tokenizer.tokenize("""こんばんは""" ) , ["""こん""", """##ばんは"""] ) self.assertListEqual(tokenizer.tokenize("""こんばんは こんばんにちは こんにちは""" ) , ["""こん""", """##ばんは""", """[UNK]""", """こんにちは"""] ) def __lowercase ( self : Dict ): lowerCAmelCase = BertJapaneseTokenizer.from_pretrained("""nlp-waseda/roberta-base-japanese-with-auto-jumanpp""" ) lowerCAmelCase = tokenizer.subword_tokenizer lowerCAmelCase = subword_tokenizer.tokenize("""国境 の 長い トンネル を 抜ける と 雪国 であった 。""" ) self.assertListEqual(lowerCAmelCase , ["""▁国境""", """▁の""", """▁長い""", """▁トンネル""", """▁を""", """▁抜ける""", """▁と""", """▁雪""", """国""", """▁であった""", """▁。"""] ) lowerCAmelCase = subword_tokenizer.tokenize("""こんばんは こんばん にち は こんにちは""" ) self.assertListEqual(lowerCAmelCase , ["""▁こん""", """ばん""", """は""", """▁こん""", """ばん""", """▁に""", """ち""", """▁は""", """▁こんにちは"""] ) def __lowercase ( self : str ): lowerCAmelCase = self.tokenizer_class.from_pretrained("""cl-tohoku/bert-base-japanese""" ) lowerCAmelCase = tokenizer.encode("""ありがとう。""" , add_special_tokens=lowerCAmelCase ) lowerCAmelCase = tokenizer.encode("""どういたしまして。""" , add_special_tokens=lowerCAmelCase ) lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase ) lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase , lowerCAmelCase ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class SCREAMING_SNAKE_CASE__ ( _a , unittest.TestCase ): _a = BertJapaneseTokenizer _a = False def __lowercase ( self : Union[str, Any] ): super().setUp() lowerCAmelCase = ["""[UNK]""", """[CLS]""", """[SEP]""", """こ""", """ん""", """に""", """ち""", """は""", """ば""", """世""", """界""", """、""", """。"""] lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def __lowercase ( self : Optional[int] , **lowerCAmelCase : Optional[Any] ): return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type="""character""" , **lowerCAmelCase ) def __lowercase ( self : List[str] , lowerCAmelCase : Union[str, Any] ): lowerCAmelCase = """こんにちは、世界。 \nこんばんは、世界。""" lowerCAmelCase = """こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。""" return input_text, output_text def __lowercase ( self : List[Any] ): pass # TODO add if relevant def __lowercase ( self : Optional[Any] ): pass # TODO add if relevant def __lowercase ( self : int ): pass # TODO add if relevant def __lowercase ( self : Union[str, Any] ): lowerCAmelCase = self.tokenizer_class(self.vocab_file , subword_tokenizer_type="""character""" ) lowerCAmelCase = tokenizer.tokenize("""こんにちは、世界。 \nこんばんは、世界。""" ) self.assertListEqual( lowerCAmelCase , ["""こ""", """ん""", """に""", """ち""", """は""", """、""", """世""", """界""", """。""", """こ""", """ん""", """ば""", """ん""", """は""", """、""", """世""", """界""", """。"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] ) def __lowercase ( self : Any ): lowerCAmelCase = ["""[UNK]""", """[CLS]""", """[SEP]""", """こ""", """ん""", """に""", """ち""", """は""", """ば""", """世""", """界""", """、""", """。"""] lowerCAmelCase = {} for i, token in enumerate(lowerCAmelCase ): lowerCAmelCase = i lowerCAmelCase = CharacterTokenizer(vocab=lowerCAmelCase , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""こんにちは""" ) , ["""こ""", """ん""", """に""", """ち""", """は"""] ) self.assertListEqual(tokenizer.tokenize("""こんにちほ""" ) , ["""こ""", """ん""", """に""", """ち""", """[UNK]"""] ) def __lowercase ( self : Tuple ): lowerCAmelCase = self.tokenizer_class.from_pretrained("""cl-tohoku/bert-base-japanese-char""" ) lowerCAmelCase = tokenizer.encode("""ありがとう。""" , add_special_tokens=lowerCAmelCase ) lowerCAmelCase = tokenizer.encode("""どういたしまして。""" , add_special_tokens=lowerCAmelCase ) lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase ) lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase , lowerCAmelCase ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowercase ( self : Optional[int] ): lowerCAmelCase = """cl-tohoku/bert-base-japanese""" lowerCAmelCase = AutoTokenizer.from_pretrained(lowerCAmelCase ) self.assertIsInstance(lowerCAmelCase , lowerCAmelCase ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowercase ( self : List[str] ): lowerCAmelCase = """cl-tohoku/bert-base-japanese""" with self.assertLogs("""transformers""" , level="""WARNING""" ) as cm: BertTokenizer.from_pretrained(lowerCAmelCase ) self.assertTrue( cm.records[0].message.startswith( """The tokenizer class you load from this checkpoint is not the same type as the class this function""" """ is called from.""" ) ) lowerCAmelCase = """bert-base-cased""" with self.assertLogs("""transformers""" , level="""WARNING""" ) as cm: BertJapaneseTokenizer.from_pretrained(lowerCAmelCase ) self.assertTrue( cm.records[0].message.startswith( """The tokenizer class you load from this checkpoint is not the same type as the class this function""" """ is called from.""" ) )
169
0
'''simple docstring''' def snake_case_ ( __snake_case : int = 1000) -> int: lowerCAmelCase_ = -1 lowerCAmelCase_ = 0 for a in range(1 , n // 3): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c lowerCAmelCase_ = (n * n - 2 * a * n) // (2 * n - 2 * a) lowerCAmelCase_ = n - a - b if c * c == (a * a + b * b): lowerCAmelCase_ = a * b * c if candidate >= product: lowerCAmelCase_ = candidate return product if __name__ == "__main__": print(f'''{solution() = }''')
606
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def snake_case_ ( __snake_case : str = "laptop") -> DataFrame: lowerCAmelCase_ = F'''https://www.amazon.in/laptop/s?k={product}''' lowerCAmelCase_ = { '''User-Agent''': '''Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36''', '''Accept-Language''': '''en-US, en;q=0.5''', } lowerCAmelCase_ = BeautifulSoup(requests.get(__snake_case , headers=__snake_case).text) # Initialize a Pandas dataframe with the column titles lowerCAmelCase_ = DataFrame( columns=[ '''Product Title''', '''Product Link''', '''Current Price of the product''', '''Product Rating''', '''MRP of the product''', '''Discount''', ]) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( '''div''' , attrs={'''class''': '''s-result-item''', '''data-component-type''': '''s-search-result'''} , ) , soup.find_all('''div''' , attrs={'''class''': '''a-row a-size-base a-color-base'''}) , ): try: lowerCAmelCase_ = item.ha.text lowerCAmelCase_ = '''https://www.amazon.in/''' + item.ha.a['''href'''] lowerCAmelCase_ = item.find('''span''' , attrs={'''class''': '''a-offscreen'''}).text try: lowerCAmelCase_ = item.find('''span''' , attrs={'''class''': '''a-icon-alt'''}).text except AttributeError: lowerCAmelCase_ = '''Not available''' try: lowerCAmelCase_ = ( '''₹''' + item.find( '''span''' , attrs={'''class''': '''a-price a-text-price'''}).text.split('''₹''')[1] ) except AttributeError: lowerCAmelCase_ = '''''' try: lowerCAmelCase_ = float( ( ( float(product_mrp.strip('''₹''').replace(''',''' , '''''')) - float(product_price.strip('''₹''').replace(''',''' , '''''')) ) / float(product_mrp.strip('''₹''').replace(''',''' , '''''')) ) * 100) except ValueError: lowerCAmelCase_ = float('''nan''') except AttributeError: pass lowerCAmelCase_ = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] lowerCAmelCase_ = ''' ''' lowerCAmelCase_ = ''' ''' data_frame.index += 1 return data_frame if __name__ == "__main__": A_ : Optional[int] ='''headphones''' get_amazon_product_data(product).to_csv(f'''Amazon Product Data for {product}.csv''')
606
1
"""simple docstring""" from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): """simple docstring""" __snake_case = CustomTokenizer pass
434
'''simple docstring''' from __future__ import annotations def UpperCamelCase__ ( __magic_name__ : list ) -> float: '''simple docstring''' if not nums: raise ValueError("""List is empty""" ) return sum(__magic_name__ ) / len(__magic_name__ ) if __name__ == "__main__": import doctest doctest.testmod()
38
0
UpperCamelCase : str = """0.21.0""" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
719
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, TFAutoModelForSequenceClassification, TFTrainer, TFTrainingArguments, ) from transformers.utils import logging as hf_logging hf_logging.set_verbosity_info() hf_logging.enable_default_handler() hf_logging.enable_explicit_format() def UpperCamelCase_ ( __a , __a , __a , __a , __a , __a = None , ) -> Union[str, Any]: a__ : Optional[Any] = {} if train_file is not None: a__ : str = [train_file] if eval_file is not None: a__ : Dict = [eval_file] if test_file is not None: a__ : Tuple = [test_file] a__ : int = datasets.load_dataset("csv" , data_files=__a ) a__ : List[str] = list(ds[list(files.keys() )[0]].features.keys() ) a__ : Any = features_name.pop(__a ) a__ : Union[str, Any] = list(set(ds[list(files.keys() )[0]][label_name] ) ) a__ : Any = {label: i for i, label in enumerate(__a )} a__ : Union[str, Any] = tokenizer.model_input_names a__ : Optional[int] = {} if len(__a ) == 1: for k in files.keys(): a__ : Any = ds[k].map( lambda __a : tokenizer.batch_encode_plus( example[features_name[0]] , truncation=__a , max_length=__a , padding="max_length" ) , batched=__a , ) elif len(__a ) == 2: for k in files.keys(): a__ : Any = ds[k].map( lambda __a : tokenizer.batch_encode_plus( (example[features_name[0]], example[features_name[1]]) , truncation=__a , max_length=__a , padding="max_length" , ) , batched=__a , ) def gen_train(): for ex in transformed_ds[datasets.Split.TRAIN]: a__ : Union[str, Any] = {k: v for k, v in ex.items() if k in input_names} a__ : Union[str, Any] = labelaid[ex[label_name]] yield (d, label) def gen_val(): for ex in transformed_ds[datasets.Split.VALIDATION]: a__ : Tuple = {k: v for k, v in ex.items() if k in input_names} a__ : Tuple = labelaid[ex[label_name]] yield (d, label) def gen_test(): for ex in transformed_ds[datasets.Split.TEST]: a__ : List[Any] = {k: v for k, v in ex.items() if k in input_names} a__ : List[Any] = labelaid[ex[label_name]] yield (d, label) a__ : Tuple = ( tf.data.Dataset.from_generator( __a , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TRAIN in transformed_ds else None ) if train_ds is not None: a__ : Any = train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) ) a__ : str = ( tf.data.Dataset.from_generator( __a , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.VALIDATION in transformed_ds else None ) if val_ds is not None: a__ : Dict = val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) ) a__ : Optional[int] = ( tf.data.Dataset.from_generator( __a , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TEST in transformed_ds else None ) if test_ds is not None: a__ : Any = test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) ) return train_ds, val_ds, test_ds, labelaid UpperCamelCase : Tuple = logging.getLogger(__name__) @dataclass class A__ : """simple docstring""" _lowercase = field(metadata={'help': 'Which column contains the label'} ) _lowercase = field(default=A__ , metadata={'help': 'The path of the training file'} ) _lowercase = field(default=A__ , metadata={'help': 'The path of the development file'} ) _lowercase = field(default=A__ , metadata={'help': 'The path of the test file'} ) _lowercase = field( default=1_2_8 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) _lowercase = field( default=A__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) @dataclass class A__ : """simple docstring""" _lowercase = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) _lowercase = field( default=A__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) _lowercase = field( default=A__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) _lowercase = field(default=A__ , metadata={'help': 'Set this flag to use fast tokenization.'} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. _lowercase = field( default=A__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) def UpperCamelCase_ ( ) -> Optional[int]: # 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. a__ : str = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) ) a__, a__, a__ : Any = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' " --overwrite_output_dir to overcome." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.info( f'''n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, ''' f'''16-bits training: {training_args.fpaa}''' ) logger.info(f'''Training/evaluation parameters {training_args}''' ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. a__ : Dict = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) a__, a__, a__, a__ : Dict = get_tfds( train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=__a , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , ) a__ : int = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(__a ) , labelaid=__a , idalabel={id: label for label, id in labelaid.items()} , finetuning_task="text-classification" , cache_dir=model_args.cache_dir , ) with training_args.strategy.scope(): a__ : Optional[int] = TFAutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_pt=bool(".bin" in model_args.model_name_or_path ) , config=__a , cache_dir=model_args.cache_dir , ) def compute_metrics(__a ) -> Dict: a__ : List[str] = np.argmax(p.predictions , axis=1 ) return {"acc": (preds == p.label_ids).mean()} # Initialize our Trainer a__ : Optional[int] = TFTrainer( model=__a , args=__a , train_dataset=__a , eval_dataset=__a , compute_metrics=__a , ) # Training if training_args.do_train: trainer.train() trainer.save_model() tokenizer.save_pretrained(training_args.output_dir ) # Evaluation a__ : Union[str, Any] = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) a__ : str = trainer.evaluate() a__ : List[str] = os.path.join(training_args.output_dir , "eval_results.txt" ) with open(__a , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(f''' {key} = {value}''' ) writer.write(f'''{key} = {value}\n''' ) results.update(__a ) return results if __name__ == "__main__": main()
151
0
from collections import defaultdict from math import ceil, sqrt def a ( a = 100_0000 , a = 10 ) ->int: '''simple docstring''' SCREAMING_SNAKE_CASE = defaultdict(a ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: SCREAMING_SNAKE_CASE = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: SCREAMING_SNAKE_CASE = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(a , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(F'''{solution() = }''')
201
# Function to print upper half of diamond (pyramid) def a ( a ) ->Optional[Any]: '''simple docstring''' for i in range(0 , a ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1 ): # printing stars print('''* ''' , end='''''' ) print() def a ( a ) ->Union[str, Any]: '''simple docstring''' for i in range(a , 0 , -1 ): for _ in range(a , 0 , -1 ): # printing stars print('''* ''' , end='''''' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(''' ''' , end='''''' ) def a ( a ) ->Optional[int]: '''simple docstring''' if n <= 0: print(''' ... .... nothing printing :(''' ) return floyd(a ) # upper half reverse_floyd(a ) # lower half if __name__ == "__main__": print(R'| /\ | |- | |- |--| |\ /| |-') print(R'|/ \| |- |_ |_ |__| | \/ | |_') __lowerCAmelCase = 1 while K: __lowerCAmelCase = int(input('enter the number and , and see the magic : ')) print() pretty_print(user_number) __lowerCAmelCase = int(input('press 0 to exit... and 1 to continue...')) print('Good Bye...')
201
1
'''simple docstring''' from datetime import datetime import requests def lowerCamelCase ( UpperCAmelCase__ : str ) -> bytes: '''simple docstring''' SCREAMING_SNAKE_CASE__ :int = 'https://downloadgram.net/wp-json/wppress/video-downloader/video?url=' SCREAMING_SNAKE_CASE__ :Optional[int] = requests.get(base_url + url ).json()[0]['urls'][0]['src'] return requests.get(UpperCAmelCase__ ).content if __name__ == "__main__": UpperCamelCase_ = input('''Enter Video/IGTV url: ''').strip() UpperCamelCase_ = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4" with open(file_name, '''wb''') as fp: fp.write(download_video(url)) print(f"Done. Video saved to disk as {file_name}.")
320
'''simple docstring''' import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel UpperCamelCase_ = logging.getLogger(__name__) def lowerCamelCase ( UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: '''simple docstring''' if os.path.exists(UpperCAmelCase__ ): if os.path.exists(os.path.join(UpperCAmelCase__ , 'config.json' ) ) and os.path.isfile( os.path.join(UpperCAmelCase__ , 'config.json' ) ): os.remove(os.path.join(UpperCAmelCase__ , 'config.json' ) ) if os.path.exists(os.path.join(UpperCAmelCase__ , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(UpperCAmelCase__ , 'pytorch_model.bin' ) ): os.remove(os.path.join(UpperCAmelCase__ , 'pytorch_model.bin' ) ) else: os.makedirs(UpperCAmelCase__ ) model.save_pretrained(UpperCAmelCase__ ) def lowerCamelCase ( UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any]=False ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ :int = 2 if unlogit: SCREAMING_SNAKE_CASE__ :int = torch.pow(UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :Optional[Any] = p * torch.log(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :str = 0 return -plogp.sum(dim=-1 ) def lowerCamelCase ( UpperCAmelCase__ : Optional[int] ) -> List[str]: '''simple docstring''' logger.info('lv, h >\t' + '\t'.join(F'''{x + 1}''' for x in range(len(UpperCAmelCase__ ) ) ) ) for row in range(len(UpperCAmelCase__ ) ): if tensor.dtype != torch.long: logger.info(F'''layer {row + 1}:\t''' + '\t'.join(F'''{x:.5f}''' for x in tensor[row].cpu().data ) ) else: logger.info(F'''layer {row + 1}:\t''' + '\t'.join(F'''{x:d}''' for x in tensor[row].cpu().data ) ) def lowerCamelCase ( UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : str=False ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ :Tuple = model.config.num_hidden_layers, model.config.num_attention_heads SCREAMING_SNAKE_CASE__ :List[str] = torch.zeros(UpperCAmelCase__ , UpperCAmelCase__ ).to(args.device ) SCREAMING_SNAKE_CASE__ :Optional[int] = torch.zeros(UpperCAmelCase__ , UpperCAmelCase__ ).to(args.device ) if head_mask is None: SCREAMING_SNAKE_CASE__ :Any = torch.ones(UpperCAmelCase__ , UpperCAmelCase__ ).to(args.device ) head_mask.requires_grad_(requires_grad=UpperCAmelCase__ ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: SCREAMING_SNAKE_CASE__ :Optional[Any] = None SCREAMING_SNAKE_CASE__ :Dict = 0.0 SCREAMING_SNAKE_CASE__ :Any = 0.0 for step, inputs in enumerate(tqdm(UpperCAmelCase__ , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): SCREAMING_SNAKE_CASE__ :Union[str, Any] = tuple(t.to(args.device ) for t in inputs ) ((SCREAMING_SNAKE_CASE__) , ) :Dict = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) SCREAMING_SNAKE_CASE__ :Optional[Any] = model(UpperCAmelCase__ , labels=UpperCAmelCase__ , head_mask=UpperCAmelCase__ ) # (loss), lm_logits, presents, (all hidden_states), (attentions) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ :Union[str, Any] = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(UpperCAmelCase__ ): SCREAMING_SNAKE_CASE__ :Optional[int] = entropy(attn.detach() , UpperCAmelCase__ ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(UpperCAmelCase__ ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: SCREAMING_SNAKE_CASE__ :List[str] = 2 SCREAMING_SNAKE_CASE__ :Optional[int] = torch.pow(torch.pow(UpperCAmelCase__ , UpperCAmelCase__ ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: SCREAMING_SNAKE_CASE__ :Dict = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(UpperCAmelCase__ ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(UpperCAmelCase__ ) logger.info('Head ranked by importance scores' ) SCREAMING_SNAKE_CASE__ :str = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) SCREAMING_SNAKE_CASE__ :Any = torch.arange( head_importance.numel() , device=args.device ) SCREAMING_SNAKE_CASE__ :Optional[Any] = head_ranks.view_as(UpperCAmelCase__ ) print_ad_tensor(UpperCAmelCase__ ) return attn_entropy, head_importance, total_loss def lowerCamelCase ( UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ :Optional[int] = compute_heads_importance(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , compute_entropy=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :List[Any] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , UpperCAmelCase__ , original_score * args.masking_threshold ) SCREAMING_SNAKE_CASE__ :Optional[int] = torch.ones_like(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :Union[str, Any] = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) SCREAMING_SNAKE_CASE__ :str = original_score while current_score >= original_score * args.masking_threshold: SCREAMING_SNAKE_CASE__ :Any = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads SCREAMING_SNAKE_CASE__ :str = float('Inf' ) SCREAMING_SNAKE_CASE__ :str = head_importance.view(-1 ).sort()[1] if len(UpperCAmelCase__ ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads SCREAMING_SNAKE_CASE__ :Optional[int] = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) SCREAMING_SNAKE_CASE__ :List[Any] = new_head_mask.view(-1 ) SCREAMING_SNAKE_CASE__ :str = 0.0 SCREAMING_SNAKE_CASE__ :Any = new_head_mask.view_as(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :str = new_head_mask.clone().detach() print_ad_tensor(UpperCAmelCase__ ) # Compute metric and head importance again SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ :int = compute_heads_importance( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , compute_entropy=UpperCAmelCase__ , head_mask=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :Any = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , UpperCAmelCase__ , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_0_0 , ) logger.info('Final head mask' ) print_ad_tensor(UpperCAmelCase__ ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def lowerCamelCase ( UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = datetime.now() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ :str = compute_heads_importance( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , compute_entropy=UpperCAmelCase__ , compute_importance=UpperCAmelCase__ , head_mask=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :Any = 1 / loss SCREAMING_SNAKE_CASE__ :List[Any] = datetime.now() - before_time SCREAMING_SNAKE_CASE__ :Union[str, Any] = sum(p.numel() for p in model.parameters() ) SCREAMING_SNAKE_CASE__ :Dict = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(UpperCAmelCase__ ) ) } for k, v in heads_to_prune.items(): if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): SCREAMING_SNAKE_CASE__ :Any = [ v, ] assert sum(len(UpperCAmelCase__ ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :List[Any] = sum(p.numel() for p in model.parameters() ) SCREAMING_SNAKE_CASE__ :Optional[int] = datetime.now() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ :Optional[Any] = compute_heads_importance( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , compute_entropy=UpperCAmelCase__ , compute_importance=UpperCAmelCase__ , head_mask=UpperCAmelCase__ , actually_pruned=UpperCAmelCase__ , ) SCREAMING_SNAKE_CASE__ :List[Any] = 1 / loss SCREAMING_SNAKE_CASE__ :Optional[int] = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , UpperCAmelCase__ , UpperCAmelCase__ , pruned_num_params / original_num_params * 1_0_0 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , UpperCAmelCase__ , UpperCAmelCase__ ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 1_0_0 ) save_model(UpperCAmelCase__ , args.output_dir ) def lowerCamelCase ( ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ :str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=UpperCAmelCase__ , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=UpperCAmelCase__ , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=UpperCAmelCase__ , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=UpperCAmelCase__ , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=UpperCAmelCase__ , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=UpperCAmelCase__ , type=UpperCAmelCase__ , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=UpperCAmelCase__ , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=UpperCAmelCase__ , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=UpperCAmelCase__ , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=UpperCAmelCase__ , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=1_2_8 , type=UpperCAmelCase__ , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=UpperCAmelCase__ , help='Batch size.' ) parser.add_argument('--seed' , type=UpperCAmelCase__ , default=4_2 ) parser.add_argument('--local_rank' , type=UpperCAmelCase__ , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=UpperCAmelCase__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=UpperCAmelCase__ , default='' , help='Can be used for distant debugging.' ) SCREAMING_SNAKE_CASE__ :Union[str, Any] = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=UpperCAmelCase__ ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: SCREAMING_SNAKE_CASE__ :Tuple = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) SCREAMING_SNAKE_CASE__ :Tuple = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) SCREAMING_SNAKE_CASE__ :Optional[int] = torch.device('cuda' , args.local_rank ) SCREAMING_SNAKE_CASE__ :List[Any] = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) SCREAMING_SNAKE_CASE__ :Any = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: SCREAMING_SNAKE_CASE__ :Tuple = nn.parallel.DistributedDataParallel( UpperCAmelCase__ , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=UpperCAmelCase__ ) elif args.n_gpu > 1: SCREAMING_SNAKE_CASE__ :Optional[int] = nn.DataParallel(UpperCAmelCase__ ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=UpperCAmelCase__ ) torch.save(UpperCAmelCase__ , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , UpperCAmelCase__ ) # Prepare dataset SCREAMING_SNAKE_CASE__ :Optional[Any] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) SCREAMING_SNAKE_CASE__ :Optional[Any] = (torch.from_numpy(UpperCAmelCase__ ),) SCREAMING_SNAKE_CASE__ :List[str] = TensorDataset(*UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :Optional[Any] = RandomSampler(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE__ :int = DataLoader(UpperCAmelCase__ , sampler=UpperCAmelCase__ , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: SCREAMING_SNAKE_CASE__ :Tuple = mask_heads(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) prune_heads(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if __name__ == "__main__": main()
320
1
'''simple docstring''' from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) lowerCAmelCase : Dict = _symbol_database.Default() lowerCAmelCase : Union[str, Any] = _descriptor_pool.Default().AddSerializedFile( B'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03' ) lowerCAmelCase : Optional[Any] = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sentencepiece_model_pb2', _globals) if _descriptor._USE_C_DESCRIPTORS is False: lowerCAmelCase : Optional[int] = None lowerCAmelCase : str = B'H\003' # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" lowerCAmelCase : Optional[int] = 45 lowerCAmelCase : Tuple = 15_81 lowerCAmelCase : Tuple = 15_17 lowerCAmelCase : Tuple = 15_70 lowerCAmelCase : Union[str, Any] = 15_84 lowerCAmelCase : Optional[int] = 17_93 lowerCAmelCase : int = 17_95 lowerCAmelCase : Dict = 19_16 lowerCAmelCase : List[Any] = 18_64 lowerCAmelCase : Any = 19_05 lowerCAmelCase : Any = 19_19 lowerCAmelCase : str = 24_29 lowerCAmelCase : str = 22_08 lowerCAmelCase : Any = 24_18 lowerCAmelCase : Dict = 23_23 lowerCAmelCase : Optional[int] = 24_07 # @@protoc_insertion_point(module_scope)
3
'''simple docstring''' import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def A ( self : Optional[Any] ): """simple docstring""" __snake_case = mock.Mock() __snake_case = 500 __snake_case = {} __snake_case = HTTPError __snake_case = {} # Download this model to make sure it's in the cache. __snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head: __snake_case = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def A ( self : Optional[Any] ): """simple docstring""" __snake_case = mock.Mock() __snake_case = 500 __snake_case = {} __snake_case = HTTPError __snake_case = {} # Download this model to make sure it's in the cache. __snake_case = GPTaTokenizerFast.from_pretrained("gpt2" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=a_ ) as mock_head: __snake_case = GPTaTokenizerFast.from_pretrained("gpt2" ) # This check we did call the fake head request mock_head.assert_called() def A ( self : Optional[Any] ): """simple docstring""" try: __snake_case = tempfile.mktemp() with open(a_ , "wb" ) as f: http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" , a_ ) __snake_case = AlbertTokenizer.from_pretrained(a_ ) finally: os.remove(a_ ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile("tokenizer.json" ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open("tokenizer.json" , "wb" ) as f: http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json" , a_ ) __snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1_000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove("tokenizer.json" ) def A ( self : str ): """simple docstring""" __snake_case = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" ) @is_staging_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): __SCREAMING_SNAKE_CASE = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""] @classmethod def A ( cls : List[Any] ): """simple docstring""" __snake_case = TOKEN HfFolder.save_token(a_ ) @classmethod def A ( cls : List[Any] ): """simple docstring""" try: delete_repo(token=cls._token , repo_id="test-tokenizer" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-tokenizer-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-tokenizer" ) except HTTPError: pass def A ( self : int ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: __snake_case = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) __snake_case = BertTokenizer(a_ ) tokenizer.push_to_hub("test-tokenizer" , use_auth_token=self._token ) __snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id="test-tokenizer" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(a_ , repo_id="test-tokenizer" , push_to_hub=a_ , use_auth_token=self._token ) __snake_case = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def A ( self : int ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: __snake_case = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) __snake_case = BertTokenizer(a_ ) tokenizer.push_to_hub("valid_org/test-tokenizer-org" , use_auth_token=self._token ) __snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-tokenizer-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( a_ , repo_id="valid_org/test-tokenizer-org" , push_to_hub=a_ , use_auth_token=self._token ) __snake_case = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def A ( self : List[str] ): """simple docstring""" CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: __snake_case = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) __snake_case = CustomTokenizer(a_ ) # No fast custom tokenizer tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token ) __snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: __snake_case = os.path.join(a_ , "vocab.txt" ) with open(a_ , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) __snake_case = BertTokenizerFast.from_pretrained(a_ ) bert_tokenizer.save_pretrained(a_ ) __snake_case = CustomTokenizerFast.from_pretrained(a_ ) tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token ) __snake_case = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizerFast" ) __snake_case = AutoTokenizer.from_pretrained( f'''{USER}/test-dynamic-tokenizer''' , use_fast=a_ , trust_remote_code=a_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def A ( self : Optional[int] ): """simple docstring""" __snake_case = Trie() trie.add("Hello 友達" ) self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} ) trie.add("Hello" ) trie.data self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} ) def A ( self : str ): """simple docstring""" __snake_case = Trie() self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS] This is a extra_id_100"] ) trie.add("[CLS]" ) trie.add("extra_id_1" ) trie.add("extra_id_100" ) self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS]", " This is a ", "extra_id_100"] ) def A ( self : Optional[Any] ): """simple docstring""" __snake_case = Trie() trie.add("A" ) self.assertEqual(trie.split("ABC" ) , ["A", "BC"] ) self.assertEqual(trie.split("BCA" ) , ["BC", "A"] ) def A ( self : List[Any] ): """simple docstring""" __snake_case = Trie() trie.add("TOKEN]" ) trie.add("[SPECIAL_TOKEN]" ) self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] ) def A ( self : str ): """simple docstring""" __snake_case = Trie() trie.add("A" ) trie.add("P" ) trie.add("[SPECIAL_TOKEN]" ) self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] ) def A ( self : Optional[int] ): """simple docstring""" __snake_case = Trie() trie.add("AB" ) trie.add("B" ) trie.add("C" ) self.assertEqual(trie.split("ABC" ) , ["AB", "C"] ) def A ( self : Tuple ): """simple docstring""" __snake_case = Trie() trie.add("ABC" ) trie.add("B" ) trie.add("CD" ) self.assertEqual(trie.split("ABCD" ) , ["ABC", "D"] ) def A ( self : Any ): """simple docstring""" __snake_case = Trie() __snake_case = trie.cut_text("ABC" , [0, 0, 2, 1, 2, 3] ) self.assertEqual(a_ , ["AB", "C"] )
69
0
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class lowerCAmelCase_ ( unittest.TestCase): lowerCamelCase_ = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowerCamelCase_ = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def _snake_case ( self : Dict , __A : List[Any] , __A : Optional[int] , __A : int ) ->Dict: """simple docstring""" a__ :Tuple = TextaTextGenerationPipeline(model=__A , tokenizer=__A ) return generator, ["Something to write", "Something else"] def _snake_case ( self : Optional[int] , __A : Optional[Any] , __A : List[Any] ) ->Dict: """simple docstring""" a__ :Optional[int] = generator("Something there" ) self.assertEqual(__A , [{"generated_text": ANY(__A )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["generated_text"].startswith("Something there" ) ) a__ :Dict = generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=__A ) self.assertEqual( __A , [ [{"generated_text": ANY(__A )}, {"generated_text": ANY(__A )}], [{"generated_text": ANY(__A )}, {"generated_text": ANY(__A )}], ] , ) a__ :int = generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=__A ) self.assertEqual( __A , [ [{"generated_text": ANY(__A )}, {"generated_text": ANY(__A )}], [{"generated_text": ANY(__A )}, {"generated_text": ANY(__A )}], ] , ) with self.assertRaises(__A ): generator(4 ) @require_torch def _snake_case ( self : List[Any] ) ->Dict: """simple docstring""" a__ :int = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="pt" ) # do_sample=False necessary for reproducibility a__ :Dict = generator("Something there" , do_sample=__A ) self.assertEqual(__A , [{"generated_text": ""}] ) a__ :int = 3 a__ :str = generator( "Something there" , num_return_sequences=__A , num_beams=__A , ) a__ :int = [ {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": ""}, ] self.assertEqual(__A , __A ) a__ :str = generator("This is a test" , do_sample=__A , num_return_sequences=2 , return_tensors=__A ) self.assertEqual( __A , [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ] , ) a__ :Dict = generator.model.config.eos_token_id a__ :List[Any] = "<pad>" a__ :Optional[int] = generator( ["This is a test", "This is a second test"] , do_sample=__A , num_return_sequences=2 , batch_size=2 , return_tensors=__A , ) self.assertEqual( __A , [ [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], ] , ) @require_tf def _snake_case ( self : List[Any] ) ->Any: """simple docstring""" a__ :Optional[Any] = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="tf" ) # do_sample=False necessary for reproducibility a__ :Any = generator("Something there" , do_sample=__A ) self.assertEqual(__A , [{"generated_text": ""}] )
702
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case__ = logging.get_logger(__name__) snake_case__ = { '''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_ ( _a): lowerCamelCase_ = 'sew' def __init__( self : Any , __A : str=32 , __A : Dict=768 , __A : int=12 , __A : Dict=12 , __A : Dict=3072 , __A : int=2 , __A : Union[str, Any]="gelu" , __A : Union[str, Any]=0.1 , __A : Optional[Any]=0.1 , __A : Union[str, Any]=0.1 , __A : str=0.0 , __A : Union[str, Any]=0.1 , __A : Optional[Any]=0.1 , __A : Tuple=0.02 , __A : Any=1E-5 , __A : Optional[Any]="group" , __A : str="gelu" , __A : Dict=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , __A : Tuple=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , __A : int=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , __A : List[str]=False , __A : Tuple=128 , __A : Tuple=16 , __A : Optional[int]=True , __A : Union[str, Any]=0.05 , __A : List[str]=10 , __A : Optional[int]=2 , __A : List[Any]=0.0 , __A : Optional[Any]=10 , __A : Tuple=0 , __A : Tuple="mean" , __A : Any=False , __A : str=False , __A : Dict=256 , __A : Union[str, Any]=0 , __A : Optional[int]=1 , __A : Optional[Any]=2 , **__A : Tuple , ) ->Tuple: """simple docstring""" super().__init__(**__A , pad_token_id=__A , bos_token_id=__A , eos_token_id=__A ) a__ :List[Any] = hidden_size a__ :List[Any] = feat_extract_norm a__ :List[str] = feat_extract_activation a__ :Any = list(__A ) a__ :Dict = list(__A ) a__ :Optional[int] = list(__A ) a__ :Any = conv_bias a__ :List[str] = num_conv_pos_embeddings a__ :str = num_conv_pos_embedding_groups a__ :Optional[int] = len(self.conv_dim ) a__ :List[Any] = num_hidden_layers a__ :str = intermediate_size a__ :Dict = squeeze_factor a__ :List[Any] = hidden_act a__ :Optional[Any] = num_attention_heads a__ :Tuple = hidden_dropout a__ :Tuple = attention_dropout a__ :List[Any] = activation_dropout a__ :str = feat_proj_dropout a__ :Any = final_dropout a__ :Dict = layerdrop a__ :List[str] = layer_norm_eps a__ :Tuple = initializer_range a__ :Dict = 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 a__ :int = apply_spec_augment a__ :Optional[Any] = mask_time_prob a__ :List[Any] = mask_time_length a__ :Any = mask_time_min_masks a__ :Any = mask_feature_prob a__ :Dict = mask_feature_length a__ :Union[str, Any] = mask_feature_min_masks # ctc loss a__ :Dict = ctc_loss_reduction a__ :Any = ctc_zero_infinity # sequence classification a__ :Optional[int] = use_weighted_layer_sum a__ :Tuple = classifier_proj_size @property def _snake_case ( self : Dict ) ->Union[str, Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
373
0
import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( '''split_dict''' , [ SplitDict(), SplitDict({'''train''': SplitInfo(name='''train''' , num_bytes=13_37 , num_examples=42 , dataset_name='''my_dataset''' )} ), SplitDict({'''train''': SplitInfo(name='''train''' , num_bytes=13_37 , num_examples=42 )} ), SplitDict({'''train''': SplitInfo()} ), ] , ) def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = split_dict._to_yaml_list() assert len(SCREAMING_SNAKE_CASE ) == len(SCREAMING_SNAKE_CASE ) lowercase__ = SplitDict._from_yaml_list(SCREAMING_SNAKE_CASE ) for split_name, split_info in split_dict.items(): # dataset_name field is deprecated, and is therefore not part of the YAML dump lowercase__ = None # the split name of split_dict takes over the name of the split info object lowercase__ = split_name assert split_dict == reloaded @pytest.mark.parametrize( '''split_info''' , [SplitInfo(), SplitInfo(dataset_name=SCREAMING_SNAKE_CASE ), SplitInfo(dataset_name='''my_dataset''' )] ) def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase__ = asdict(SplitDict({'''train''': split_info} ) ) assert "dataset_name" in split_dict_asdict["train"] assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
43
"""simple docstring""" import json import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from transformers import OneFormerImageProcessor from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput if is_vision_available(): from PIL import Image def __snake_case ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any]="shi-labs/oneformer_demo" ) -> Tuple: '''simple docstring''' with open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type="dataset" ) , "r" ) as f: _UpperCAmelCase : Optional[int] = json.load(SCREAMING_SNAKE_CASE__ ) _UpperCAmelCase : int = {} _UpperCAmelCase : Union[str, Any] = [] _UpperCAmelCase : List[Any] = [] for key, info in class_info.items(): _UpperCAmelCase : List[str] = info["name"] class_names.append(info["name"] ) if info["isthing"]: thing_ids.append(int(SCREAMING_SNAKE_CASE__ ) ) _UpperCAmelCase : Tuple = thing_ids _UpperCAmelCase : str = class_names return metadata class UpperCAmelCase_ ( unittest.TestCase ): def __init__( self : Optional[Any] , A : Tuple , A : str=7 , A : Union[str, Any]=3 , A : Union[str, Any]=3_0 , A : Dict=4_0_0 , A : List[str]=None , A : str=True , A : Union[str, Any]=True , A : Optional[Any]=[0.5, 0.5, 0.5] , A : str=[0.5, 0.5, 0.5] , A : Optional[Any]=1_0 , A : Optional[int]=False , A : int=2_5_5 , A : List[Any]="shi-labs/oneformer_demo" , A : int="ade20k_panoptic.json" , A : str=1_0 , ): _UpperCAmelCase : int = parent _UpperCAmelCase : Any = batch_size _UpperCAmelCase : str = num_channels _UpperCAmelCase : str = min_resolution _UpperCAmelCase : List[str] = max_resolution _UpperCAmelCase : List[Any] = do_resize _UpperCAmelCase : List[Any] = {"shortest_edge": 3_2, "longest_edge": 1_3_3_3} if size is None else size _UpperCAmelCase : Optional[Any] = do_normalize _UpperCAmelCase : Optional[int] = image_mean _UpperCAmelCase : Dict = image_std _UpperCAmelCase : Any = class_info_file _UpperCAmelCase : Optional[int] = prepare_metadata(A , A ) _UpperCAmelCase : Any = num_text _UpperCAmelCase : Dict = repo_path # for the post_process_functions _UpperCAmelCase : str = 2 _UpperCAmelCase : Any = 1_0 _UpperCAmelCase : Optional[int] = 1_0 _UpperCAmelCase : Tuple = 3 _UpperCAmelCase : List[str] = 4 _UpperCAmelCase : int = num_labels _UpperCAmelCase : Optional[Any] = do_reduce_labels _UpperCAmelCase : Any = ignore_index def snake_case_ ( self : Optional[int] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "num_labels": self.num_labels, "do_reduce_labels": self.do_reduce_labels, "ignore_index": self.ignore_index, "class_info_file": self.class_info_file, "metadata": self.metadata, "num_text": self.num_text, } def snake_case_ ( self : str , A : int , A : Optional[Any]=False ): if not batched: _UpperCAmelCase : List[str] = image_inputs[0] if isinstance(A , Image.Image ): _UpperCAmelCase , _UpperCAmelCase : Union[str, Any] = image.size else: _UpperCAmelCase , _UpperCAmelCase : Any = image.shape[1], image.shape[2] if w < h: _UpperCAmelCase : Optional[int] = int(self.size["shortest_edge"] * h / w ) _UpperCAmelCase : Tuple = self.size["shortest_edge"] elif w > h: _UpperCAmelCase : Dict = self.size["shortest_edge"] _UpperCAmelCase : Dict = int(self.size["shortest_edge"] * w / h ) else: _UpperCAmelCase : Optional[int] = self.size["shortest_edge"] _UpperCAmelCase : Optional[int] = self.size["shortest_edge"] else: _UpperCAmelCase : List[str] = [] for image in image_inputs: _UpperCAmelCase , _UpperCAmelCase : int = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _UpperCAmelCase : int = max(A , key=lambda A : item[0] )[0] _UpperCAmelCase : Dict = max(A , key=lambda A : item[1] )[1] return expected_height, expected_width def snake_case_ ( self : List[str] ): return OneFormerForUniversalSegmentationOutput( # +1 for null class class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , ) @require_torch @require_vision class UpperCAmelCase_ ( _UpperCamelCase , unittest.TestCase ): __SCREAMING_SNAKE_CASE : str = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string __SCREAMING_SNAKE_CASE : Tuple = image_processing_class def snake_case_ ( self : Tuple ): _UpperCAmelCase : Optional[Any] = OneFormerImageProcessorTester(self ) @property def snake_case_ ( self : Optional[Any] ): return self.image_processing_tester.prepare_image_processor_dict() def snake_case_ ( self : Union[str, Any] ): _UpperCAmelCase : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A , "image_mean" ) ) self.assertTrue(hasattr(A , "image_std" ) ) self.assertTrue(hasattr(A , "do_normalize" ) ) self.assertTrue(hasattr(A , "do_resize" ) ) self.assertTrue(hasattr(A , "size" ) ) self.assertTrue(hasattr(A , "ignore_index" ) ) self.assertTrue(hasattr(A , "class_info_file" ) ) self.assertTrue(hasattr(A , "num_text" ) ) self.assertTrue(hasattr(A , "repo_path" ) ) self.assertTrue(hasattr(A , "metadata" ) ) self.assertTrue(hasattr(A , "do_reduce_labels" ) ) def snake_case_ ( self : List[Any] ): pass def snake_case_ ( self : Union[str, Any] ): # Initialize image_processor _UpperCAmelCase : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase : Optional[int] = prepare_image_inputs(self.image_processing_tester , equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A , Image.Image ) # Test not batched input _UpperCAmelCase : Optional[Any] = image_processor(image_inputs[0] , ["semantic"] , return_tensors="pt" ).pixel_values _UpperCAmelCase , _UpperCAmelCase : Optional[Any] = self.image_processing_tester.get_expected_values(A ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCAmelCase , _UpperCAmelCase : Dict = self.image_processing_tester.get_expected_values(A , batched=A ) _UpperCAmelCase : Optional[Any] = image_processor( A , ["semantic"] * len(A ) , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def snake_case_ ( self : str ): # Initialize image_processor _UpperCAmelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase : Any = prepare_image_inputs(self.image_processing_tester , equal_resolution=A , numpify=A ) for image in image_inputs: self.assertIsInstance(A , np.ndarray ) # Test not batched input _UpperCAmelCase : int = image_processor(image_inputs[0] , ["semantic"] , return_tensors="pt" ).pixel_values _UpperCAmelCase , _UpperCAmelCase : List[Any] = self.image_processing_tester.get_expected_values(A ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCAmelCase , _UpperCAmelCase : int = self.image_processing_tester.get_expected_values(A , batched=A ) _UpperCAmelCase : List[str] = image_processor( A , ["semantic"] * len(A ) , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def snake_case_ ( self : Optional[int] ): # Initialize image_processor _UpperCAmelCase : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase : str = prepare_image_inputs(self.image_processing_tester , equal_resolution=A , torchify=A ) for image in image_inputs: self.assertIsInstance(A , torch.Tensor ) # Test not batched input _UpperCAmelCase : Tuple = image_processor(image_inputs[0] , ["semantic"] , return_tensors="pt" ).pixel_values _UpperCAmelCase , _UpperCAmelCase : Any = self.image_processing_tester.get_expected_values(A ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCAmelCase , _UpperCAmelCase : List[str] = self.image_processing_tester.get_expected_values(A , batched=A ) _UpperCAmelCase : Optional[int] = image_processor( A , ["semantic"] * len(A ) , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def snake_case_ ( self : Optional[int] , A : Tuple=False , A : Optional[Any]=False , A : int="np" ): _UpperCAmelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) # prepare image and target _UpperCAmelCase : List[str] = self.image_processing_tester.num_labels _UpperCAmelCase : Any = None _UpperCAmelCase : List[Any] = None _UpperCAmelCase : Dict = prepare_image_inputs(self.image_processing_tester , equal_resolution=A ) if with_segmentation_maps: _UpperCAmelCase : Union[str, Any] = num_labels if is_instance_map: _UpperCAmelCase : Optional[int] = list(range(A ) ) * 2 _UpperCAmelCase : Union[str, Any] = dict(enumerate(A ) ) _UpperCAmelCase : Tuple = [ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": _UpperCAmelCase : Optional[int] = [Image.fromarray(A ) for annotation in annotations] _UpperCAmelCase : int = image_processor( A , ["semantic"] * len(A ) , A , return_tensors="pt" , instance_id_to_semantic_id=A , pad_and_return_pixel_mask=A , ) return inputs def snake_case_ ( self : Any ): pass def snake_case_ ( self : Dict ): def common(A : List[Any]=False , A : List[str]=None ): _UpperCAmelCase : str = self.comm_get_image_processor_inputs( with_segmentation_maps=A , is_instance_map=A , segmentation_type=A ) _UpperCAmelCase : Optional[int] = inputs["mask_labels"] _UpperCAmelCase : str = inputs["class_labels"] _UpperCAmelCase : List[str] = inputs["pixel_values"] _UpperCAmelCase : Any = inputs["text_inputs"] # check the batch_size for mask_label, class_label, text_input in zip(A , A , A ): self.assertEqual(mask_label.shape[0] , class_label.shape[0] ) # this ensure padding has happened self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] ) self.assertEqual(len(A ) , self.image_processing_tester.num_text ) common() common(is_instance_map=A ) common(is_instance_map=A , segmentation_type="pil" ) common(is_instance_map=A , segmentation_type="pil" ) def snake_case_ ( self : int ): _UpperCAmelCase : Optional[Any] = np.zeros((2_0, 5_0) ) _UpperCAmelCase : Dict = 1 _UpperCAmelCase : Optional[int] = 1 _UpperCAmelCase : Optional[int] = 1 _UpperCAmelCase : List[str] = binary_mask_to_rle(A ) self.assertEqual(len(A ) , 4 ) self.assertEqual(rle[0] , 2_1 ) self.assertEqual(rle[1] , 4_5 ) def snake_case_ ( self : Optional[Any] ): _UpperCAmelCase : Optional[Any] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file="ade20k_panoptic.json" , num_text=self.image_processing_tester.num_text , repo_path="shi-labs/oneformer_demo" , ) _UpperCAmelCase : int = self.image_processing_tester.get_fake_oneformer_outputs() _UpperCAmelCase : List[str] = fature_extractor.post_process_semantic_segmentation(A ) self.assertEqual(len(A ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) _UpperCAmelCase : Tuple = [(1, 4) for i in range(self.image_processing_tester.batch_size )] _UpperCAmelCase : Optional[Any] = fature_extractor.post_process_semantic_segmentation(A , target_sizes=A ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def snake_case_ ( self : Dict ): _UpperCAmelCase : Tuple = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file="ade20k_panoptic.json" , num_text=self.image_processing_tester.num_text , repo_path="shi-labs/oneformer_demo" , ) _UpperCAmelCase : Union[str, Any] = self.image_processing_tester.get_fake_oneformer_outputs() _UpperCAmelCase : Tuple = image_processor.post_process_instance_segmentation(A , threshold=0 ) self.assertTrue(len(A ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("segmentation" in el ) self.assertTrue("segments_info" in el ) self.assertEqual(type(el["segments_info"] ) , A ) self.assertEqual( el["segmentation"].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def snake_case_ ( self : Any ): _UpperCAmelCase : Optional[int] = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=7_7 , task_seq_length=7_7 , class_info_file="ade20k_panoptic.json" , num_text=self.image_processing_tester.num_text , repo_path="shi-labs/oneformer_demo" , ) _UpperCAmelCase : Optional[Any] = self.image_processing_tester.get_fake_oneformer_outputs() _UpperCAmelCase : Tuple = image_processor.post_process_panoptic_segmentation(A , threshold=0 ) self.assertTrue(len(A ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("segmentation" in el ) self.assertTrue("segments_info" in el ) self.assertEqual(type(el["segments_info"] ) , A ) self.assertEqual( el["segmentation"].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
289
0
'''simple docstring''' def lowerCamelCase ( lowerCamelCase : int = 100): A_ : Any = n * (n + 1) * (2 * n + 1) / 6 A_ : str = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares) if __name__ == "__main__": print(f"""{solution() = }""")
27
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging __magic_name__ = logging.get_logger(__name__) if is_vision_available(): import PIL class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a_ = ["""pixel_values"""] def __init__( self : Optional[Any] ,_a : bool = True ,_a : Dict[str, int] = None ,_a : PILImageResampling = PILImageResampling.BICUBIC ,_a : bool = True ,_a : Dict[str, int] = None ,_a : bool = True ,_a : Union[int, float] = 1 / 255 ,_a : bool = True ,_a : Optional[Union[float, List[float]]] = None ,_a : Optional[Union[float, List[float]]] = None ,_a : bool = True ,**_a : Dict ,): '''simple docstring''' super().__init__(**_a ) A_ : Tuple = size if size is not None else {"""shortest_edge""": 224} A_ : Optional[Any] = get_size_dict(_a ,default_to_square=_a ) A_ : Tuple = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} A_ : Optional[Any] = get_size_dict(_a ,default_to_square=_a ,param_name="""crop_size""" ) A_ : Any = do_resize A_ : List[str] = size A_ : Union[str, Any] = resample A_ : Dict = do_center_crop A_ : List[str] = crop_size A_ : Any = do_rescale A_ : Union[str, Any] = rescale_factor A_ : Any = do_normalize A_ : List[str] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A_ : List[Any] = image_std if image_std is not None else OPENAI_CLIP_STD A_ : Tuple = do_convert_rgb def _a ( self : Optional[int] ,_a : np.ndarray ,_a : Dict[str, int] ,_a : PILImageResampling = PILImageResampling.BICUBIC ,_a : Optional[Union[str, ChannelDimension]] = None ,**_a : Optional[Any] ,): '''simple docstring''' A_ : Optional[Any] = get_size_dict(_a ,default_to_square=_a ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) A_ : Tuple = get_resize_output_image_size(_a ,size=size["""shortest_edge"""] ,default_to_square=_a ) return resize(_a ,size=_a ,resample=_a ,data_format=_a ,**_a ) def _a ( self : List[Any] ,_a : np.ndarray ,_a : Dict[str, int] ,_a : Optional[Union[str, ChannelDimension]] = None ,**_a : Optional[int] ,): '''simple docstring''' A_ : Optional[int] = get_size_dict(_a ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(_a ,size=(size["""height"""], size["""width"""]) ,data_format=_a ,**_a ) def _a ( self : Any ,_a : np.ndarray ,_a : Union[int, float] ,_a : Optional[Union[str, ChannelDimension]] = None ,**_a : Any ,): '''simple docstring''' return rescale(_a ,scale=_a ,data_format=_a ,**_a ) def _a ( self : Any ,_a : np.ndarray ,_a : Union[float, List[float]] ,_a : Union[float, List[float]] ,_a : Optional[Union[str, ChannelDimension]] = None ,**_a : List[str] ,): '''simple docstring''' return normalize(_a ,mean=_a ,std=_a ,data_format=_a ,**_a ) def _a ( self : Optional[Any] ,_a : ImageInput ,_a : bool = None ,_a : Dict[str, int] = None ,_a : PILImageResampling = None ,_a : bool = None ,_a : int = None ,_a : bool = None ,_a : float = None ,_a : bool = None ,_a : Optional[Union[float, List[float]]] = None ,_a : Optional[Union[float, List[float]]] = None ,_a : bool = None ,_a : Optional[Union[str, TensorType]] = None ,_a : Optional[ChannelDimension] = ChannelDimension.FIRST ,**_a : int ,): '''simple docstring''' A_ : Union[str, Any] = do_resize if do_resize is not None else self.do_resize A_ : Tuple = size if size is not None else self.size A_ : Optional[int] = get_size_dict(_a ,param_name="""size""" ,default_to_square=_a ) A_ : List[str] = resample if resample is not None else self.resample A_ : int = do_center_crop if do_center_crop is not None else self.do_center_crop A_ : Any = crop_size if crop_size is not None else self.crop_size A_ : int = get_size_dict(_a ,param_name="""crop_size""" ,default_to_square=_a ) A_ : List[Any] = do_rescale if do_rescale is not None else self.do_rescale A_ : int = rescale_factor if rescale_factor is not None else self.rescale_factor A_ : Any = do_normalize if do_normalize is not None else self.do_normalize A_ : int = image_mean if image_mean is not None else self.image_mean A_ : int = image_std if image_std is not None else self.image_std A_ : List[str] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A_ : int = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) 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.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: A_ : Optional[int] = [convert_to_rgb(_a ) for image in images] # All transformations expect numpy arrays. A_ : Dict = [to_numpy_array(_a ) for image in images] if do_resize: A_ : int = [self.resize(image=_a ,size=_a ,resample=_a ) for image in images] if do_center_crop: A_ : Tuple = [self.center_crop(image=_a ,size=_a ) for image in images] if do_rescale: A_ : List[str] = [self.rescale(image=_a ,scale=_a ) for image in images] if do_normalize: A_ : Any = [self.normalize(image=_a ,mean=_a ,std=_a ) for image in images] A_ : List[str] = [to_channel_dimension_format(_a ,_a ) for image in images] A_ : List[str] = {"""pixel_values""": images} return BatchFeature(data=_a ,tensor_type=_a )
27
1
"""simple docstring""" import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class A( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None ) -> Optional[Any]: """simple docstring""" super().__init__() _UpperCamelCase :Optional[int] = pad_token_id _UpperCamelCase :Optional[Any] = max_length _UpperCamelCase :Any = vocab _UpperCamelCase :Union[str, Any] = merges _UpperCamelCase :int = BytePairTokenizer(__UpperCamelCase , __UpperCamelCase , sequence_length=__UpperCamelCase ) @classmethod def _UpperCamelCase( cls , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" _UpperCamelCase :Dict = [''' '''.join(__UpperCamelCase ) for m in tokenizer.bpe_ranks.keys()] _UpperCamelCase :Union[str, Any] = tokenizer.get_vocab() return cls(__UpperCamelCase , __UpperCamelCase , *__UpperCamelCase , **__UpperCamelCase ) @classmethod def _UpperCamelCase( cls , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> str: """simple docstring""" _UpperCamelCase :str = GPTaTokenizer.from_pretrained(__UpperCamelCase , *__UpperCamelCase , **__UpperCamelCase ) return cls.from_tokenizer(__UpperCamelCase , *__UpperCamelCase , **__UpperCamelCase ) @classmethod def _UpperCamelCase( cls , SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" return cls(**__UpperCamelCase ) def _UpperCamelCase( self ) -> List[str]: """simple docstring""" return { "vocab": self.vocab, "merges": self.merges, "max_length": self.max_length, "pad_token_id": self.pad_token_id, } def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ) -> Optional[Any]: """simple docstring""" _UpperCamelCase :Tuple = self.tf_tokenizer(__UpperCamelCase ) _UpperCamelCase :Optional[int] = tf.ones_like(__UpperCamelCase ) if self.pad_token_id is not None: # pad the tokens up to max length _UpperCamelCase :List[Any] = max_length if max_length is not None else self.max_length if max_length is not None: _UpperCamelCase :Tuple = pad_model_inputs( __UpperCamelCase , max_seq_length=__UpperCamelCase , pad_value=self.pad_token_id ) return {"attention_mask": attention_mask, "input_ids": input_ids}
355
def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> bool: A__ : List[Any] =len(snake_case_ ) + 1 A__ : List[Any] =len(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. A__ : Dict =[[0 for i in range(snake_case_ )] for j in range(snake_case_ )] # since string of zero length match pattern of zero length A__ : Dict =1 # since pattern of zero length will never match with string of non-zero length for i in range(1, snake_case_ ): A__ : Optional[Any] =0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1, snake_case_ ): A__ : str =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, snake_case_ ): for j in range(1, snake_case_ ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": A__ : str =dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: A__ : str =1 elif pattern[j - 2] in (input_string[i - 1], "."): A__ : Union[str, Any] =dp[i - 1][j] else: A__ : Optional[int] =0 else: A__ : str =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 :") __lowerCamelCase : int = "aab" __lowerCamelCase : Dict = "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}")
416
0
from __future__ import annotations __UpperCamelCase : List[Any] = 1.6021E-19 # units = C def __UpperCAmelCase ( _snake_case : float, _snake_case : float, _snake_case : float, ): if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("You cannot supply more or less than 2 values" ) elif conductivity < 0: raise ValueError("Conductivity cannot be negative" ) elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative" ) elif mobility < 0: raise ValueError("mobility cannot be negative" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
703
"""simple docstring""" import math from collections.abc import Callable def __UpperCAmelCase ( _snake_case : Callable[[float], float], _snake_case : float, _snake_case : float ): _lowercase = xa _lowercase = xa while True: if x_n == x_na or function(_snake_case ) == function(_snake_case ): raise ZeroDivisionError("float division by zero, could not find root" ) _lowercase = x_na - ( function(_snake_case ) / ((function(_snake_case ) - function(_snake_case )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 1_0**-5: return x_na _lowercase = x_na _lowercase = x_na def __UpperCAmelCase ( _snake_case : float ): return math.pow(_snake_case, 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
227
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _a : str = logging.get_logger(__name__) _a : int = { "google/vivit-b-16x2-kinetics400": ( "https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class _lowercase ( __lowercase ): _SCREAMING_SNAKE_CASE : List[str] = "vivit" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any]=224 , SCREAMING_SNAKE_CASE_ : List[str]=32 , SCREAMING_SNAKE_CASE_ : List[Any]=[2, 16, 16] , SCREAMING_SNAKE_CASE_ : Optional[int]=3 , SCREAMING_SNAKE_CASE_ : List[Any]=768 , SCREAMING_SNAKE_CASE_ : Any=12 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=12 , SCREAMING_SNAKE_CASE_ : Optional[Any]=3072 , SCREAMING_SNAKE_CASE_ : List[str]="gelu_fast" , SCREAMING_SNAKE_CASE_ : Any=0.0 , SCREAMING_SNAKE_CASE_ : int=0.0 , SCREAMING_SNAKE_CASE_ : int=0.0_2 , SCREAMING_SNAKE_CASE_ : List[Any]=1e-06 , SCREAMING_SNAKE_CASE_ : int=True , **SCREAMING_SNAKE_CASE_ : Optional[int] , ) -> Optional[int]: __snake_case = hidden_size __snake_case = num_hidden_layers __snake_case = num_attention_heads __snake_case = intermediate_size __snake_case = hidden_act __snake_case = hidden_dropout_prob __snake_case = attention_probs_dropout_prob __snake_case = initializer_range __snake_case = layer_norm_eps __snake_case = image_size __snake_case = num_frames __snake_case = tubelet_size __snake_case = num_channels __snake_case = qkv_bias super().__init__(**SCREAMING_SNAKE_CASE_ )
56
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _a : str = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine" def _a () -> Dict: """simple docstring""" __snake_case = _ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: __snake_case = get_sagemaker_input() else: __snake_case = get_cluster_input() return config def _a (lowercase__ : Union[str, Any]=None ) -> int: """simple docstring""" if subparsers is not None: __snake_case = subparsers.add_parser('config' , description=lowercase__ ) else: __snake_case = argparse.ArgumentParser('Accelerate config command' , description=lowercase__ ) parser.add_argument( '--config_file' , default=lowercase__ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=lowercase__ ) return parser def _a (lowercase__ : List[str] ) -> Union[str, Any]: """simple docstring""" __snake_case = get_user_input() if args.config_file is not None: __snake_case = args.config_file else: if not os.path.isdir(lowercase__ ): os.makedirs(lowercase__ ) __snake_case = default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase__ ) else: config.to_yaml_file(lowercase__ ) print(f'accelerate configuration saved at {config_file}' ) def _a () -> int: """simple docstring""" __snake_case = config_command_parser() __snake_case = parser.parse_args() config_command(lowercase__ ) if __name__ == "__main__": main()
56
1
"""simple docstring""" from __future__ import annotations from math import pi def lowercase ( a__ : float , a__ : float , a__ : float ) -> dict[str, 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()
342
"""simple docstring""" from datetime import datetime as dt import os from github import Github UpperCAmelCase = [ """good first issue""", """good second issue""", """good difficult issue""", """feature request""", """new model""", """wip""", ] def lowercase ( ) -> int: _UpperCamelCase = Github(os.environ['''GITHUB_TOKEN'''] ) _UpperCamelCase = g.get_repo('''huggingface/transformers''' ) _UpperCamelCase = repo.get_issues(state='''open''' ) for issue in open_issues: _UpperCamelCase = sorted([comment for comment in issue.get_comments()] , key=lambda a__ : i.created_at , reverse=a__ ) _UpperCamelCase = comments[0] if len(a__ ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state='''closed''' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( '''This issue has been automatically marked as stale because it has not had ''' '''recent activity. If you think this still needs to be addressed ''' '''please comment on this thread.\n\nPlease note that issues that do not follow the ''' '''[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) ''' '''are likely to be ignored.''' ) if __name__ == "__main__": main()
342
1
import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : List[Any] = {"vocab_file": "vocab.txt", "emoji_file": "emoji.json"} SCREAMING_SNAKE_CASE : List[str] = { "vocab_file": { "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt", }, "emoji_file": { "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json", }, } SCREAMING_SNAKE_CASE : Any = { "abeja/gpt-neox-japanese-2.7b": 2048, } def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Dict: with open(lowerCamelCase_ , 'r' , encoding='utf-8' ) as f: _lowercase : int = json.loads(f.read() ) _lowercase : Optional[Any] = collections.OrderedDict() _lowercase : Any = collections.OrderedDict() _lowercase : Optional[Any] = collections.OrderedDict() with open(lowerCamelCase_ , 'r' , encoding='utf-8' ) as f: _lowercase : List[str] = f.readlines() _lowercase : List[str] = [[t.rstrip('\n' )] if (t == ',' or ',' not in t) else t.rstrip('\n' ).split(',' ) for t in token] for idx, b in enumerate(lowerCamelCase_ ): _lowercase : Optional[Any] = b _lowercase : Dict = idx for wd in b: _lowercase : Optional[int] = idx return vocab, raw_vocab, ids_to_tokens, emoji class _lowerCamelCase( _a ): lowercase_ : str = VOCAB_FILES_NAMES lowercase_ : List[str] = PRETRAINED_VOCAB_FILES_MAP lowercase_ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ : Union[str, Any] = ["""input_ids""", """attention_mask"""] def __init__( self, lowerCamelCase, lowerCamelCase, lowerCamelCase="<|endoftext|>", lowerCamelCase="<|endoftext|>", lowerCamelCase="<|startoftext|>", lowerCamelCase="<|endoftext|>", lowerCamelCase=False, **lowerCamelCase, ) -> Optional[int]: """simple docstring""" super().__init__( unk_token=lowerCamelCase, pad_token=lowerCamelCase, bos_token=lowerCamelCase, eos_token=lowerCamelCase, do_clean_text=lowerCamelCase, **lowerCamelCase, ) if not os.path.isfile(lowerCamelCase): raise ValueError( F'''Can\'t find a vocabulary file at path \'{vocab_file}\'. To load the vocabulary from a Google pretrained''' ' model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`') if not os.path.isfile(lowerCamelCase): raise ValueError( F'''Can\'t find a emoji file at path \'{emoji_file}\'. To load the emoji information from a Google''' ' pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`') _lowercase : Tuple = do_clean_text _lowercase , _lowercase , _lowercase , _lowercase : Dict = load_vocab_and_emoji(lowerCamelCase, lowerCamelCase) _lowercase : str = SubWordJapaneseTokenizer( vocab=self.vocab, ids_to_tokens=self.ids_to_tokens, emoji=self.emoji) @property def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" return len(self.raw_vocab) def UpperCamelCase ( self) -> List[str]: """simple docstring""" return dict(self.raw_vocab, **self.added_tokens_encoder) def UpperCamelCase ( self, lowerCamelCase) -> Optional[Any]: """simple docstring""" return self.subword_tokenizer.tokenize(lowerCamelCase, clean=self.do_clean_text) def UpperCamelCase ( self, lowerCamelCase) -> Tuple: """simple docstring""" return self.vocab.get(lowerCamelCase, self.vocab.get(self.unk_token)) def UpperCamelCase ( self, lowerCamelCase) -> Tuple: """simple docstring""" return self.subword_tokenizer.convert_id_to_token(lowerCamelCase) def UpperCamelCase ( self, lowerCamelCase) -> Optional[int]: """simple docstring""" _lowercase : str = ''.join(lowerCamelCase).strip() return out_string def UpperCamelCase ( self, lowerCamelCase) -> List[int]: """simple docstring""" _lowercase : str = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase, add_special_tokens=lowerCamelCase) + [self.eos_token_id]) if len(lowerCamelCase) > self.model_max_length: _lowercase : List[str] = input_ids[-self.model_max_length :] return input_ids def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None) -> Tuple[str]: """simple docstring""" _lowercase : Tuple = 0 if os.path.isdir(lowerCamelCase): _lowercase : int = os.path.join( lowerCamelCase, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) _lowercase : Union[str, Any] = os.path.join( lowerCamelCase, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['emoji_file']) else: _lowercase : Dict = ( (filename_prefix + '-' if filename_prefix else '') + save_directory + VOCAB_FILES_NAMES['vocab_file'] ) _lowercase : str = ( (filename_prefix + '-' if filename_prefix else '') + save_directory + VOCAB_FILES_NAMES['emoji_file'] ) with open(lowerCamelCase, 'w', encoding='utf-8') as writer: for token_index, token in self.ids_to_tokens.items(): if index != token_index: logger.warning( F'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.''' ' Please check that the vocabulary is not corrupted!') _lowercase : Union[str, Any] = token_index writer.write(','.join(lowerCamelCase) + '\n') index += 1 with open(lowerCamelCase, 'w', encoding='utf-8') as writer: json.dump(self.emoji, lowerCamelCase) return vocab_file, emoji_file class _lowerCamelCase( _a ): def __init__( self, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> List[Any]: """simple docstring""" _lowercase : List[Any] = vocab # same as swe _lowercase : int = ids_to_tokens # same as bpe _lowercase : Tuple = emoji _lowercase : Tuple = np.max([len(lowerCamelCase) for w in self.vocab.keys()]) _lowercase : Dict = re.compile(R'(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)') _lowercase : Tuple = re.compile(R'[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*') _lowercase : List[Any] = re.compile(R'[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}') _lowercase : Union[str, Any] = re.compile( R'([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*') _lowercase : List[Any] = re.compile( R'(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*') _lowercase : Optional[Any] = re.compile( R'((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*') _lowercase : List[str] = '─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿' _lowercase : int = '▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟' _lowercase : str = str.maketrans({k: '<BLOCK>' for k in keisen + blocks}) def __len__( self) -> List[str]: """simple docstring""" return len(self.ids_to_tokens) def UpperCamelCase ( self, lowerCamelCase) -> Tuple: """simple docstring""" _lowercase : Union[str, Any] = self.content_repattera.sub('<URL>', lowerCamelCase) _lowercase : Dict = self.content_repattera.sub('<EMAIL>', lowerCamelCase) _lowercase : List[str] = self.content_repattera.sub('<TEL>', lowerCamelCase) _lowercase : Optional[int] = self.content_repattera.sub('<DATE>', lowerCamelCase) _lowercase : Tuple = self.content_repattera.sub('<DATE>', lowerCamelCase) _lowercase : str = self.content_repattera.sub('<PRICE>', lowerCamelCase) _lowercase : int = content.translate(self.content_transa) while "<BLOCK><BLOCK>" in content: _lowercase : Optional[Any] = content.replace('<BLOCK><BLOCK>', '<BLOCK>') return content def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase=False) -> List[Any]: """simple docstring""" _lowercase : int = text.replace(' ', '<SP>') _lowercase : Optional[Any] = text.replace(' ', '<SP>') _lowercase : Tuple = text.replace('\r\n', '<BR>') _lowercase : Tuple = text.replace('\n', '<BR>') _lowercase : Dict = text.replace('\r', '<BR>') _lowercase : str = text.replace('\t', '<TAB>') _lowercase : Optional[Any] = text.replace('—', 'ー') _lowercase : Union[str, Any] = text.replace('−', 'ー') for k, v in self.emoji["emoji"].items(): if k in text: _lowercase : Optional[int] = text.replace(lowerCamelCase, lowerCamelCase) if clean: _lowercase : Tuple = self.clean_text(lowerCamelCase) def check_simbol(lowerCamelCase): _lowercase : Optional[int] = x.encode() if len(lowerCamelCase) == 1 and len(lowerCamelCase) == 2: _lowercase : List[Any] = (int(e[0]) << 8) + int(e[1]) if ( (c >= 0xC2A1 and c <= 0xC2BF) or (c >= 0xC780 and c <= 0xC783) or (c >= 0xCAB9 and c <= 0xCBBF) or (c >= 0xCC80 and c <= 0xCDA2) ): return True return False def checkuae(lowerCamelCase): _lowercase : int = x.encode() if len(lowerCamelCase) == 1 and len(lowerCamelCase) == 3: _lowercase : Optional[Any] = (int(e[0]) << 16) + (int(e[1]) << 8) + int(e[2]) if c >= 0xE28080 and c <= 0xE2B07F: return True return False _lowercase : Dict = 0 _lowercase : Optional[int] = [] while pos < len(lowerCamelCase): _lowercase : Optional[Any] = min(len(lowerCamelCase), pos + self.maxlen + 1) if text[pos] == '<' else pos + 3 _lowercase : Optional[int] = [] # (token_id, token, pos) for e in range(lowerCamelCase, lowerCamelCase, -1): _lowercase : Optional[Any] = text[pos:e] if wd in self.vocab: if wd[0] == "<" and len(lowerCamelCase) > 2: _lowercase : List[Any] = [(self.vocab[wd], wd, e)] break else: candidates.append((self.vocab[wd], wd, e)) if len(lowerCamelCase) > 0: # the smallest token_id is adopted _lowercase , _lowercase , _lowercase : List[str] = sorted(lowerCamelCase, key=lambda lowerCamelCase: x[0])[0] result.append(lowerCamelCase) _lowercase : List[str] = e else: _lowercase : Optional[int] = pos + 1 _lowercase : int = text[pos:end] if check_simbol(lowerCamelCase): result.append('<KIGOU>') elif checkuae(lowerCamelCase): result.append('<U2000U2BFF>') else: for i in wd.encode('utf-8'): result.append('<|byte%d|>' % i) _lowercase : Optional[Any] = end return result def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase="\n") -> List[str]: """simple docstring""" _lowercase : List[Any] = [] _lowercase : str = [] _lowercase : str = self.ids_to_tokens[index][0] if word[:6] == "<|byte" and word[-2:] == "|>": byte_tokens.append(int(word[6:-2])) else: if len(lowerCamelCase) > 0: words.append(bytearray(lowerCamelCase).decode('utf-8', errors='replace')) _lowercase : Optional[Any] = [] if word[:7] == "<|emoji" and word[-2:] == "|>": words.append(self.emoji['emoji_inv'][word]) elif word == "<SP>": words.append(' ') elif word == "<BR>": words.append(lowerCamelCase) elif word == "<TAB>": words.append('\t') elif word == "<BLOCK>": words.append('▀') elif word == "<KIGOU>": words.append('ǀ') elif word == "<U2000U2BFF>": words.append('‖') else: words.append(lowerCamelCase) if len(lowerCamelCase) > 0: words.append(bytearray(lowerCamelCase).decode('utf-8', errors='replace')) _lowercase : Union[str, Any] = ''.join(lowerCamelCase) return text
89
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = {"vocab_file": "spiece.model"} _snake_case = { "vocab_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model", } } _snake_case = { "albert-base-v1": 512, "albert-large-v1": 512, "albert-xlarge-v1": 512, "albert-xxlarge-v1": 512, "albert-base-v2": 512, "albert-large-v2": 512, "albert-xlarge-v2": 512, "albert-xxlarge-v2": 512, } _snake_case = "▁" class lowercase ( UpperCamelCase__ ): _a = VOCAB_FILES_NAMES _a = PRETRAINED_VOCAB_FILES_MAP _a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _a , _a=True , _a=True , _a=False , _a="[CLS]" , _a="[SEP]" , _a="<unk>" , _a="[SEP]" , _a="<pad>" , _a="[CLS]" , _a="[MASK]" , _a = None , **_a , ) -> None: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. _A : Dict = ( AddedToken(_a , lstrip=_a , rstrip=_a , normalized=_a ) if isinstance(_a , _a ) else mask_token ) _A : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) _A : Optional[int] = do_lower_case _A : List[Any] = remove_space _A : Dict = keep_accents _A : int = vocab_file _A : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) @property def a__ ( self ) -> List[str]: return len(self.sp_model ) def a__ ( self ) -> Optional[Any]: _A : Dict = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> Any: _A : List[str] = self.__dict__.copy() _A : Dict = None return state def __setstate__( self , _a ) -> Any: _A : Optional[Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): _A : int = {} _A : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a__ ( self , _a ) -> Union[str, Any]: if self.remove_space: _A : List[str] = """ """.join(inputs.strip().split() ) else: _A : Any = inputs _A : List[str] = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: _A : Optional[int] = unicodedata.normalize("""NFKD""" , _a ) _A : Tuple = """""".join([c for c in outputs if not unicodedata.combining(_a )] ) if self.do_lower_case: _A : Optional[Any] = outputs.lower() return outputs def a__ ( self , _a ) -> List[str]: _A : Any = self.preprocess_text(_a ) _A : int = self.sp_model.encode(_a , out_type=_a ) _A : int = [] for piece in pieces: if len(_a ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): _A : Optional[int] = self.sp_model.EncodeAsPieces(piece[:-1].replace(_a , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: _A : List[Any] = cur_pieces[1:] else: _A : Optional[Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_a ) else: new_pieces.append(_a ) return new_pieces def a__ ( self , _a ) -> Any: return self.sp_model.PieceToId(_a ) def a__ ( self , _a ) -> int: return self.sp_model.IdToPiece(_a ) def a__ ( self , _a ) -> str: _A : Optional[Any] = [] _A : Union[str, Any] = """""" _A : Any = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token _A : Union[str, Any] = True _A : Optional[Any] = [] else: current_sub_tokens.append(_a ) _A : Optional[int] = False out_string += self.sp_model.decode(_a ) return out_string.strip() def a__ ( self , _a , _a = None ) -> List[int]: _A : Dict = [self.sep_token_id] _A : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a__ ( self , _a , _a = None , _a = False ) -> List[int]: 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 not None: return [1] + ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1] def a__ ( self , _a , _a = None ) -> List[int]: _A : str = [self.sep_token_id] _A : List[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 a__ ( self , _a , _a = None ) -> Tuple[str]: if not os.path.isdir(_a ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return _A : Any = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _a ) elif not os.path.isfile(self.vocab_file ): with open(_a , """wb""" ) as fi: _A : str = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
307
0
import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class UpperCAmelCase__ ( unittest.TestCase ): def __init__( self ,A__ ): _A : str = parent def A__ ( self ): return {} def a__ () -> int: _A : Union[str, Any] = """<HTML> <HEAD> <TITLE>sample document</TITLE> </HEAD> <BODY BGCOLOR=\"FFFFFF\"> <HR> <a href=\"http://google.com\">Goog</a> <H1>This is one header</H1> <H2>This is a another Header</H2> <P>Travel from <P> <B>SFO to JFK</B> <BR> <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B> <HR> <div style=\"color:#0000FF\"> <h3>Traveler <b> name </b> is <p> John Doe </p> </div>""" _A : Optional[Any] = """ <!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html> """ return [html_string_a, html_string_a] @require_bsa class UpperCAmelCase__ ( _UpperCAmelCase , unittest.TestCase ): __snake_case : str = MarkupLMFeatureExtractor if is_bsa_available() else None def A__ ( self ): _A : List[Any] = MarkupLMFeatureExtractionTester(self ) @property def A__ ( self ): return self.feature_extract_tester.prepare_feat_extract_dict() def A__ ( self ): # Initialize feature_extractor _A : List[Any] = self.feature_extraction_class() # Test not batched input _A : Union[str, Any] = get_html_strings()[0] _A : Tuple = feature_extractor(lowercase_ ) # fmt: off _A : List[Any] = [["""sample document""", """Goog""", """This is one header""", """This is a another Header""", """Travel from""", """SFO to JFK""", """on May 2, 2015 at 2:00 pm. For details go to confirm.com""", """Traveler""", """name""", """is""", """John Doe"""]] _A : Union[str, Any] = [["""/html/head/title""", """/html/body/a""", """/html/body/h1""", """/html/body/h2""", """/html/body/p""", """/html/body/p/p/b[1]""", """/html/body/p/p/b[2]/i""", """/html/body/p/p/div/h3""", """/html/body/p/p/div/h3/b""", """/html/body/p/p/div/h3""", """/html/body/p/p/div/h3/p"""]] # fmt: on self.assertEqual(encoding.nodes ,lowercase_ ) self.assertEqual(encoding.xpaths ,lowercase_ ) # Test batched _A : Tuple = get_html_strings() _A : Optional[Any] = feature_extractor(lowercase_ ) # fmt: off _A : List[str] = expected_nodes + [["""My First Heading""", """My first paragraph."""]] _A : int = expected_xpaths + [["""/html/body/h1""", """/html/body/p"""]] self.assertEqual(len(encoding.nodes ) ,2 ) self.assertEqual(len(encoding.xpaths ) ,2 ) self.assertEqual(encoding.nodes ,lowercase_ ) self.assertEqual(encoding.xpaths ,lowercase_ )
708
from pathlib import Path import numpy as np from PIL import Image def a__ (__lowercase :np.ndarray ) -> np.ndarray: _A , _A , _A : Optional[int] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def a__ (__lowercase :np.ndarray ) -> np.ndarray: return (gray > 127) & (gray <= 255) def a__ (__lowercase :np.ndarray , __lowercase :np.ndarray ) -> np.ndarray: _A : Optional[int] = np.zeros_like(__lowercase ) _A : str = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image _A : Optional[int] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): _A : List[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() _A : List[Any] = int(summation > 0 ) return output if __name__ == "__main__": # read original image _UpperCamelCase : Optional[Any] =Path(__file__).resolve().parent / 'image_data' / 'lena.jpg' _UpperCamelCase : List[Any] =np.array(Image.open(lena_path)) # kernel to be applied _UpperCamelCase : Dict =np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) _UpperCamelCase : Optional[Any] =dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image _UpperCamelCase : Any =Image.fromarray(output).convert('RGB') pil_img.save('result_dilation.png')
332
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A : Any = { '''configuration_pix2struct''': [ '''PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Pix2StructConfig''', '''Pix2StructTextConfig''', '''Pix2StructVisionConfig''', ], '''processing_pix2struct''': ['''Pix2StructProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[int] = ['''Pix2StructImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ '''PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Pix2StructPreTrainedModel''', '''Pix2StructForConditionalGeneration''', '''Pix2StructVisionModel''', '''Pix2StructTextModel''', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
343
import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' def wrapper(*_UpperCAmelCase, **_UpperCAmelCase ): lowerCAmelCase : str = timeit.default_timer() lowerCAmelCase : str = func(*_UpperCAmelCase, **_UpperCAmelCase ) lowerCAmelCase : Optional[int] = timeit.default_timer() - starttime return delta lowerCAmelCase : Union[str, Any] = func.__name__ return wrapper def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase=100, _UpperCAmelCase=None ) -> Any: '''simple docstring''' lowerCAmelCase : Dict = [] lowerCAmelCase : Optional[int] = seq_shapes or {} for i in range(_UpperCAmelCase ): lowerCAmelCase : Any = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(_UpperCAmelCase, _ArrayXD ): lowerCAmelCase : Dict = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(_UpperCAmelCase, datasets.Value ): if v.dtype == "string": lowerCAmelCase : Any = 'The small grey turtle was surprisingly fast when challenged.' else: lowerCAmelCase : Optional[Any] = np.random.randint(10, size=1 ).astype(v.dtype ).item() elif isinstance(_UpperCAmelCase, datasets.Sequence ): while isinstance(_UpperCAmelCase, datasets.Sequence ): lowerCAmelCase : int = v.feature lowerCAmelCase : Optional[int] = seq_shapes[k] lowerCAmelCase : str = np.random.rand(*_UpperCAmelCase ).astype(v.dtype ) lowerCAmelCase : Any = data dummy_data.append((i, example) ) return dummy_data def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase=100, _UpperCAmelCase=None ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase : Any = generate_examples(_UpperCAmelCase, num_examples=_UpperCAmelCase, seq_shapes=_UpperCAmelCase ) with ArrowWriter(features=_UpperCAmelCase, path=_UpperCAmelCase ) as writer: for key, record in dummy_data: lowerCAmelCase : Any = features.encode_example(_UpperCAmelCase ) writer.write(_UpperCAmelCase ) lowerCAmelCase , lowerCAmelCase : Optional[int] = writer.finalize() if not num_final_examples == num_examples: raise ValueError( f"Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}." ) lowerCAmelCase : int = datasets.Dataset.from_file(filename=_UpperCAmelCase, info=datasets.DatasetInfo(features=_UpperCAmelCase ) ) return dataset
343
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase : Union[str, Any] = logging.get_logger(__name__) lowercase : Tuple = { 'sail/poolformer_s12': 'https://huggingface.co/sail/poolformer_s12/resolve/main/config.json', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class A ( __snake_case ): __magic_name__ = '''poolformer''' def __init__( self , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=4.0 , SCREAMING_SNAKE_CASE=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE=[64, 128, 320, 512] , SCREAMING_SNAKE_CASE=[7, 3, 3, 3] , SCREAMING_SNAKE_CASE=[4, 2, 2, 2] , SCREAMING_SNAKE_CASE=[2, 1, 1, 1] , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE=0.02 , **SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" A : str = num_channels A : Any = patch_size A : Union[str, Any] = stride A : List[Any] = padding A : Any = pool_size A : Tuple = hidden_sizes A : Any = mlp_ratio A : List[str] = depths A : Optional[Any] = patch_sizes A : Union[str, Any] = strides A : Optional[Any] = num_encoder_blocks A : Optional[Any] = drop_path_rate A : List[Any] = hidden_act A : Any = use_layer_scale A : List[str] = layer_scale_init_value A : List[str] = initializer_range super().__init__(**SCREAMING_SNAKE_CASE ) class A ( __snake_case ): __magic_name__ = version.parse('''1.11''' ) @property def __lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __lowerCAmelCase ( self ) -> float: """simple docstring""" return 2e-3
705
'''simple docstring''' import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets lowercase : Tuple = '\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n' lowercase : List[str] = '\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy.\n' lowercase : Any = R'\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting "1/2" to "\\frac{1}{2}")\n\nExamples:\n >>> metric = datasets.load_metric("competition_math")\n >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"])\n >>> print(results)\n {\'accuracy\': 1.0}\n' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A ( datasets.Metric ): def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' ), '''references''': datasets.Value('''string''' ), } ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" A : int = 0.0 for i, j in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else 0.0 A : Tuple = n_correct / len(SCREAMING_SNAKE_CASE ) return { "accuracy": accuracy, }
343
0
"""simple docstring""" SCREAMING_SNAKE_CASE__:int = [ 999, 800, 799, 600, 599, 500, 400, 399, 377, 355, 333, 311, 288, 266, 244, 222, 200, 199, 177, 155, 133, 111, 88, 66, 44, 22, 0, ] SCREAMING_SNAKE_CASE__:Tuple = [ 999, 976, 952, 928, 905, 882, 858, 857, 810, 762, 715, 714, 572, 429, 428, 286, 285, 238, 190, 143, 142, 118, 95, 71, 47, 24, 0, ] SCREAMING_SNAKE_CASE__:Dict = [ 999, 988, 977, 966, 955, 944, 933, 922, 911, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 350, 300, 299, 266, 233, 200, 199, 179, 159, 140, 120, 100, 99, 88, 77, 66, 55, 44, 33, 22, 11, 0, ] SCREAMING_SNAKE_CASE__:List[Any] = [ 999, 995, 992, 989, 985, 981, 978, 975, 971, 967, 964, 961, 957, 956, 951, 947, 942, 937, 933, 928, 923, 919, 914, 913, 908, 903, 897, 892, 887, 881, 876, 871, 870, 864, 858, 852, 846, 840, 834, 828, 827, 820, 813, 806, 799, 792, 785, 784, 777, 770, 763, 756, 749, 742, 741, 733, 724, 716, 707, 699, 698, 688, 677, 666, 656, 655, 645, 634, 623, 613, 612, 598, 584, 570, 569, 555, 541, 527, 526, 505, 484, 483, 462, 440, 439, 396, 395, 352, 351, 308, 307, 264, 263, 220, 219, 176, 132, 88, 44, 0, ] SCREAMING_SNAKE_CASE__:Any = [ 999, 997, 995, 992, 990, 988, 986, 984, 981, 979, 977, 975, 972, 970, 968, 966, 964, 961, 959, 957, 956, 954, 951, 949, 946, 944, 941, 939, 936, 934, 931, 929, 926, 924, 921, 919, 916, 914, 913, 910, 907, 905, 902, 899, 896, 893, 891, 888, 885, 882, 879, 877, 874, 871, 870, 867, 864, 861, 858, 855, 852, 849, 846, 843, 840, 837, 834, 831, 828, 827, 824, 821, 817, 814, 811, 808, 804, 801, 798, 795, 791, 788, 785, 784, 780, 777, 774, 770, 766, 763, 760, 756, 752, 749, 746, 742, 741, 737, 733, 730, 726, 722, 718, 714, 710, 707, 703, 699, 698, 694, 690, 685, 681, 677, 673, 669, 664, 660, 656, 655, 650, 646, 641, 636, 632, 627, 622, 618, 613, 612, 607, 602, 596, 591, 586, 580, 575, 570, 569, 563, 557, 551, 545, 539, 533, 527, 526, 519, 512, 505, 498, 491, 484, 483, 474, 466, 457, 449, 440, 439, 428, 418, 407, 396, 395, 381, 366, 352, 351, 330, 308, 307, 286, 264, 263, 242, 220, 219, 176, 175, 132, 131, 88, 44, 0, ] SCREAMING_SNAKE_CASE__:int = [ 999, 991, 982, 974, 966, 958, 950, 941, 933, 925, 916, 908, 900, 899, 874, 850, 825, 800, 799, 700, 600, 500, 400, 300, 200, 100, 0, ] SCREAMING_SNAKE_CASE__:Optional[int] = [ 999, 992, 985, 978, 971, 964, 957, 949, 942, 935, 928, 921, 914, 907, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 300, 299, 200, 199, 100, 99, 0, ] SCREAMING_SNAKE_CASE__:Dict = [ 999, 996, 992, 989, 985, 982, 979, 975, 972, 968, 965, 961, 958, 955, 951, 948, 944, 941, 938, 934, 931, 927, 924, 920, 917, 914, 910, 907, 903, 900, 899, 891, 884, 876, 869, 861, 853, 846, 838, 830, 823, 815, 808, 800, 799, 788, 777, 766, 755, 744, 733, 722, 711, 700, 699, 688, 677, 666, 655, 644, 633, 622, 611, 600, 599, 585, 571, 557, 542, 528, 514, 500, 499, 485, 471, 457, 442, 428, 414, 400, 399, 379, 359, 340, 320, 300, 299, 279, 259, 240, 220, 200, 199, 166, 133, 100, 99, 66, 33, 0, ]
528
"""simple docstring""" import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor SCREAMING_SNAKE_CASE__:Dict = logging.get_logger(__name__) class snake_case__ ( snake_case_ ): def __init__( self , *lowerCamelCase , **lowerCamelCase ): warnings.warn( "The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DonutImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
528
1
from math import isqrt def _SCREAMING_SNAKE_CASE ( snake_case ) -> bool: return all(number % divisor != 0 for divisor in range(2 , isqrt(snake_case ) + 1 ) ) def _SCREAMING_SNAKE_CASE ( snake_case = 1_0**6 ) -> int: _UpperCAmelCase = 0 _UpperCAmelCase = 1 _UpperCAmelCase = 7 while prime_candidate < max_prime: primes_count += is_prime(snake_case ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F'{solution() = }')
175
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( snake_case , snake_case ) -> float: _UpperCAmelCase = sorted(numsa + numsa ) _UpperCAmelCase , _UpperCAmelCase = divmod(len(snake_case ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() a = [float(x) for x in input("Enter the elements of first array: ").split()] a = [float(x) for x in input("Enter the elements of second array: ").split()] print(F'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
175
1
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase_ ( unittest.TestCase ): @property def __UpperCAmelCase ( self ): torch.manual_seed(0 ) UpperCAmelCase__ : List[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def __UpperCAmelCase ( self ): UpperCAmelCase__ : int = self.dummy_uncond_unet UpperCAmelCase__ : Union[str, Any] = ScoreSdeVeScheduler() UpperCAmelCase__ : Union[str, Any] = ScoreSdeVePipeline(unet=_lowerCAmelCase , scheduler=_lowerCAmelCase ) sde_ve.to(_lowerCAmelCase ) sde_ve.set_progress_bar_config(disable=_lowerCAmelCase ) UpperCAmelCase__ : Any = torch.manual_seed(0 ) UpperCAmelCase__ : Union[str, Any] = sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=_lowerCAmelCase ).images UpperCAmelCase__ : Tuple = torch.manual_seed(0 ) UpperCAmelCase__ : Any = sde_ve(num_inference_steps=2 , output_type="""numpy""" , generator=_lowerCAmelCase , return_dict=_lowerCAmelCase )[ 0 ] UpperCAmelCase__ : Any = image[0, -3:, -3:, -1] UpperCAmelCase__ : List[str] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase__ : Optional[Any] = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class UpperCAmelCase_ ( unittest.TestCase ): def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = """google/ncsnpp-church-256""" UpperCAmelCase__ : str = UNetaDModel.from_pretrained(_lowerCAmelCase ) UpperCAmelCase__ : int = ScoreSdeVeScheduler.from_pretrained(_lowerCAmelCase ) UpperCAmelCase__ : Tuple = ScoreSdeVePipeline(unet=_lowerCAmelCase , scheduler=_lowerCAmelCase ) sde_ve.to(_lowerCAmelCase ) sde_ve.set_progress_bar_config(disable=_lowerCAmelCase ) UpperCAmelCase__ : List[str] = torch.manual_seed(0 ) UpperCAmelCase__ : List[str] = sde_ve(num_inference_steps=10 , output_type="""numpy""" , generator=_lowerCAmelCase ).images UpperCAmelCase__ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) UpperCAmelCase__ : List[Any] = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
79
"""simple docstring""" import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets UpperCAmelCase : Dict = '\\n@inproceedings{snover-etal-2006-study,\n title = "A Study of Translation Edit Rate with Targeted Human Annotation",\n author = "Snover, Matthew and\n Dorr, Bonnie and\n Schwartz, Rich and\n Micciulla, Linnea and\n Makhoul, John",\n booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",\n month = aug # " 8-12",\n year = "2006",\n address = "Cambridge, Massachusetts, USA",\n publisher = "Association for Machine Translation in the Americas",\n url = "https://aclanthology.org/2006.amta-papers.25",\n pages = "223--231",\n}\n@inproceedings{post-2018-call,\n title = "A Call for Clarity in Reporting {BLEU} Scores",\n author = "Post, Matt",\n booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6319",\n pages = "186--191",\n}\n' UpperCAmelCase : List[Any] = '\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n' UpperCAmelCase : int = '\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n predictions (list of str): The system stream (a sequence of segments).\n references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n Only applies if `normalized = True`. Defaults to `False`.\n case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)\n \'num_edits\' (int): The cumulative number of edits\n \'ref_length\' (float): The cumulative average reference length\n\nExamples:\n Example 1:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?",\n ... "What did the TER metric user say to the developer?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n ... ["Your jokes are...", "...TERrible"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}\n\n Example 2:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}\n\n Example 3:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... normalized=True,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}\n\n Example 4:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}\n\n Example 5:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?",\n ... "What did the TER metric user say to the developer?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n ... ["Your jokes are...", "...TERrible"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase__ ( datasets.Metric ): """simple docstring""" def lowerCamelCase__ ( self : str ): '''simple docstring''' if version.parse(scb.__version__ ) < version.parse("""1.4.12""" ): raise ImportWarning( """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n""" """You can install it with `pip install \"sacrebleu>=1.4.12\"`.""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""http://www.cs.umd.edu/~snover/tercom/""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ), } ) , codebase_urls=["""https://github.com/mjpost/sacreBLEU#ter"""] , reference_urls=[ """https://github.com/jhclark/tercom""", ] , ) def lowerCamelCase__ ( self : List[Any] , UpperCamelCase : int , UpperCamelCase : Dict , UpperCamelCase : bool = False , UpperCamelCase : bool = False , UpperCamelCase : bool = False , UpperCamelCase : bool = False , ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = len(references[0] ) if any(len(UpperCamelCase ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) __UpperCAmelCase : Any = [[refs[i] for refs in references] for i in range(UpperCamelCase )] __UpperCAmelCase : List[str] = TER( normalized=UpperCamelCase , no_punct=UpperCamelCase , asian_support=UpperCamelCase , case_sensitive=UpperCamelCase , ) __UpperCAmelCase : Tuple = sb_ter.corpus_score(UpperCamelCase , UpperCamelCase ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
139
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel 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 enable_full_determinism() class UpperCAmelCase ( unittest.TestCase ): def __lowerCAmelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __lowerCAmelCase ( self ): _lowerCAmelCase = 1 _lowerCAmelCase = 3 _lowerCAmelCase = (32, 32) _lowerCAmelCase = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_lowerCAmelCase ) return image @property def __lowerCAmelCase ( self ): torch.manual_seed(0 ) _lowerCAmelCase = UNetaDConditionModel( block_out_channels=(32, 32, 64) , layers_per_block=2 , sample_size=32 , in_channels=7 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=8 , use_linear_projection=_lowerCAmelCase , only_cross_attention=(True, True, False) , num_class_embeds=100 , ) return model @property def __lowerCAmelCase ( self ): torch.manual_seed(0 ) _lowerCAmelCase = AutoencoderKL( block_out_channels=[32, 32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) return model @property def __lowerCAmelCase ( self ): torch.manual_seed(0 ) _lowerCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act='''gelu''' , projection_dim=512 , ) return CLIPTextModel(_lowerCAmelCase ) def __lowerCAmelCase ( self ): _lowerCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _lowerCAmelCase = self.dummy_cond_unet_upscale _lowerCAmelCase = DDPMScheduler() _lowerCAmelCase = DDIMScheduler(prediction_type='''v_prediction''' ) _lowerCAmelCase = self.dummy_vae _lowerCAmelCase = self.dummy_text_encoder _lowerCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) _lowerCAmelCase = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase = Image.fromarray(np.uinta(_lowerCAmelCase ) ).convert('''RGB''' ).resize((64, 64) ) # make sure here that pndm scheduler skips prk _lowerCAmelCase = StableDiffusionUpscalePipeline( unet=_lowerCAmelCase , low_res_scheduler=_lowerCAmelCase , scheduler=_lowerCAmelCase , vae=_lowerCAmelCase , text_encoder=_lowerCAmelCase , tokenizer=_lowerCAmelCase , max_noise_level=350 , ) _lowerCAmelCase = sd_pipe.to(_lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase ) _lowerCAmelCase = '''A painting of a squirrel eating a burger''' _lowerCAmelCase = torch.Generator(device=_lowerCAmelCase ).manual_seed(0 ) _lowerCAmelCase = sd_pipe( [prompt] , image=_lowerCAmelCase , generator=_lowerCAmelCase , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , ) _lowerCAmelCase = output.images _lowerCAmelCase = torch.Generator(device=_lowerCAmelCase ).manual_seed(0 ) _lowerCAmelCase = sd_pipe( [prompt] , image=_lowerCAmelCase , generator=_lowerCAmelCase , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , return_dict=_lowerCAmelCase , )[0] _lowerCAmelCase = image[0, -3:, -3:, -1] _lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1] _lowerCAmelCase = low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) _lowerCAmelCase = np.array([0.3_113, 0.3_910, 0.4_272, 0.4_859, 0.5_061, 0.4_652, 0.5_362, 0.5_715, 0.5_661] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCAmelCase ( self ): _lowerCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _lowerCAmelCase = self.dummy_cond_unet_upscale _lowerCAmelCase = DDPMScheduler() _lowerCAmelCase = DDIMScheduler(prediction_type='''v_prediction''' ) _lowerCAmelCase = self.dummy_vae _lowerCAmelCase = self.dummy_text_encoder _lowerCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) _lowerCAmelCase = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase = Image.fromarray(np.uinta(_lowerCAmelCase ) ).convert('''RGB''' ).resize((64, 64) ) # make sure here that pndm scheduler skips prk _lowerCAmelCase = StableDiffusionUpscalePipeline( unet=_lowerCAmelCase , low_res_scheduler=_lowerCAmelCase , scheduler=_lowerCAmelCase , vae=_lowerCAmelCase , text_encoder=_lowerCAmelCase , tokenizer=_lowerCAmelCase , max_noise_level=350 , ) _lowerCAmelCase = sd_pipe.to(_lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase ) _lowerCAmelCase = '''A painting of a squirrel eating a burger''' _lowerCAmelCase = sd_pipe( 2 * [prompt] , image=2 * [low_res_image] , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , ) _lowerCAmelCase = output.images assert image.shape[0] == 2 _lowerCAmelCase = torch.Generator(device=_lowerCAmelCase ).manual_seed(0 ) _lowerCAmelCase = sd_pipe( [prompt] , image=_lowerCAmelCase , generator=_lowerCAmelCase , num_images_per_prompt=2 , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='''np''' , ) _lowerCAmelCase = output.images assert image.shape[0] == 2 @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def __lowerCAmelCase ( self ): _lowerCAmelCase = self.dummy_cond_unet_upscale _lowerCAmelCase = DDPMScheduler() _lowerCAmelCase = DDIMScheduler(prediction_type='''v_prediction''' ) _lowerCAmelCase = self.dummy_vae _lowerCAmelCase = self.dummy_text_encoder _lowerCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) _lowerCAmelCase = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase = Image.fromarray(np.uinta(_lowerCAmelCase ) ).convert('''RGB''' ).resize((64, 64) ) # put models in fp16, except vae as it overflows in fp16 _lowerCAmelCase = unet.half() _lowerCAmelCase = text_encoder.half() # make sure here that pndm scheduler skips prk _lowerCAmelCase = StableDiffusionUpscalePipeline( unet=_lowerCAmelCase , low_res_scheduler=_lowerCAmelCase , scheduler=_lowerCAmelCase , vae=_lowerCAmelCase , text_encoder=_lowerCAmelCase , tokenizer=_lowerCAmelCase , max_noise_level=350 , ) _lowerCAmelCase = sd_pipe.to(_lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase ) _lowerCAmelCase = '''A painting of a squirrel eating a burger''' _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = sd_pipe( [prompt] , image=_lowerCAmelCase , generator=_lowerCAmelCase , num_inference_steps=2 , output_type='''np''' , ).images _lowerCAmelCase = low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): def __lowerCAmelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ): _lowerCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-upscale/low_res_cat.png''' ) _lowerCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale''' '''/upsampled_cat.npy''' ) _lowerCAmelCase = '''stabilityai/stable-diffusion-x4-upscaler''' _lowerCAmelCase = StableDiffusionUpscalePipeline.from_pretrained(_lowerCAmelCase ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) pipe.enable_attention_slicing() _lowerCAmelCase = '''a cat sitting on a park bench''' _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = pipe( prompt=_lowerCAmelCase , image=_lowerCAmelCase , generator=_lowerCAmelCase , output_type='''np''' , ) _lowerCAmelCase = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-3 def __lowerCAmelCase ( self ): _lowerCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-upscale/low_res_cat.png''' ) _lowerCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale''' '''/upsampled_cat_fp16.npy''' ) _lowerCAmelCase = '''stabilityai/stable-diffusion-x4-upscaler''' _lowerCAmelCase = StableDiffusionUpscalePipeline.from_pretrained( _lowerCAmelCase , torch_dtype=torch.floataa , ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) pipe.enable_attention_slicing() _lowerCAmelCase = '''a cat sitting on a park bench''' _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = pipe( prompt=_lowerCAmelCase , image=_lowerCAmelCase , generator=_lowerCAmelCase , output_type='''np''' , ) _lowerCAmelCase = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def __lowerCAmelCase ( self ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _lowerCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-upscale/low_res_cat.png''' ) _lowerCAmelCase = '''stabilityai/stable-diffusion-x4-upscaler''' _lowerCAmelCase = StableDiffusionUpscalePipeline.from_pretrained( _lowerCAmelCase , torch_dtype=torch.floataa , ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _lowerCAmelCase = '''a cat sitting on a park bench''' _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = pipe( prompt=_lowerCAmelCase , image=_lowerCAmelCase , generator=_lowerCAmelCase , num_inference_steps=5 , output_type='''np''' , ) _lowerCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 2.9 GB is allocated assert mem_bytes < 2.9 * 10**9
664
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm UpperCAmelCase_ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex UpperCAmelCase_ = 1_0 UpperCAmelCase_ = 2_5_6 def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] )->Optional[MinHash]: if len(_SCREAMING_SNAKE_CASE ) < MIN_NUM_TOKENS: return None _lowerCAmelCase = MinHash(num_perm=_SCREAMING_SNAKE_CASE ) for token in set(_SCREAMING_SNAKE_CASE ): min_hash.update(token.encode() ) return min_hash def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : str )->Set[str]: return {t for t in NON_ALPHA.split(_SCREAMING_SNAKE_CASE ) if len(t.strip() ) > 0} class UpperCAmelCase : def __init__( self , *, _lowerCAmelCase = 0.85 , ): _lowerCAmelCase = duplication_jaccard_threshold _lowerCAmelCase = NUM_PERM _lowerCAmelCase = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) _lowerCAmelCase = defaultdict(_lowerCAmelCase ) def __lowerCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): _lowerCAmelCase = self._index.query(_lowerCAmelCase ) if code_key in self._index.keys: print(F'''Duplicate key {code_key}''' ) return self._index.insert(_lowerCAmelCase , _lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_lowerCAmelCase ) break else: self._duplicate_clusters[close_duplicates[0]].add(_lowerCAmelCase ) def __lowerCAmelCase ( self ): _lowerCAmelCase = [] for base, duplicates in self._duplicate_clusters.items(): _lowerCAmelCase = [base] + list(_lowerCAmelCase ) # reformat the cluster to be a list of dict _lowerCAmelCase = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_lowerCAmelCase ) return duplicate_clusters def __lowerCAmelCase ( self , _lowerCAmelCase ): _lowerCAmelCase = self.get_duplicate_clusters() with open(_lowerCAmelCase , '''w''' ) as f: json.dump(_lowerCAmelCase , _lowerCAmelCase ) def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : str )->Optional[Any]: _lowerCAmelCase , _lowerCAmelCase = element _lowerCAmelCase = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : Type[Dataset] )->Any: with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(_SCREAMING_SNAKE_CASE , max_queue_size=1_0_0_0_0 ) , chunksize=1_0_0 , ): if data is not None: yield data def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : Type[Dataset] , _SCREAMING_SNAKE_CASE : float )->str: _lowerCAmelCase = DuplicationIndex(duplication_jaccard_threshold=_SCREAMING_SNAKE_CASE ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(_SCREAMING_SNAKE_CASE ) ) , max_queue_size=1_0_0 ) ): di.add(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str )->float: _lowerCAmelCase = get_tokens(_SCREAMING_SNAKE_CASE ) _lowerCAmelCase = get_tokens(_SCREAMING_SNAKE_CASE ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) UpperCAmelCase_ = None def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Any )->List[Any]: _lowerCAmelCase = [] for elementa in cluster: _lowerCAmelCase = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: _lowerCAmelCase = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) >= jaccard_threshold: elementa["copies"] += 1 break else: _lowerCAmelCase = 1 extremes.append(_SCREAMING_SNAKE_CASE ) return extremes def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : str )->Tuple: global _shared_dataset _lowerCAmelCase = dataset _lowerCAmelCase = [] _lowerCAmelCase = partial(_find_cluster_extremes_shared , jaccard_threshold=_SCREAMING_SNAKE_CASE ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) , total=len(_SCREAMING_SNAKE_CASE ) , ): extremes_list.append(_SCREAMING_SNAKE_CASE ) return extremes_list def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE : Type[Dataset] , _SCREAMING_SNAKE_CASE : float = 0.85 )->Tuple[Type[Dataset], List[List[Dict]]]: _lowerCAmelCase = make_duplicate_clusters(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _lowerCAmelCase = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} _lowerCAmelCase = {} _lowerCAmelCase = find_extremes(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for extremes in extremes_clusters: for element in extremes: _lowerCAmelCase = element _lowerCAmelCase = duplicate_indices - set(extreme_dict.keys() ) _lowerCAmelCase = dataset.filter(lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : idx not in remove_indices , with_indices=_SCREAMING_SNAKE_CASE ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: _lowerCAmelCase = element['''base_index'''] in extreme_dict if element["is_extreme"]: _lowerCAmelCase = extreme_dict[element['''base_index''']]['''copies'''] print(f'''Original dataset size: {len(_SCREAMING_SNAKE_CASE )}''' ) print(f'''Number of duplicate clusters: {len(_SCREAMING_SNAKE_CASE )}''' ) print(f'''Files in duplicate cluster: {len(_SCREAMING_SNAKE_CASE )}''' ) print(f'''Unique files in duplicate cluster: {len(_SCREAMING_SNAKE_CASE )}''' ) print(f'''Filtered dataset size: {len(_SCREAMING_SNAKE_CASE )}''' ) return ds_filter, duplicate_clusters
664
1
"""simple docstring""" import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def snake_case__ ( _snake_case : List[Any]=32 , _snake_case : Tuple=10 , _snake_case : str=1_00 , _snake_case : Optional[int]=10_26 , _snake_case : Any=True , _snake_case : str="data/tokenized_stories_train_wikitext103.jbl" , _snake_case : Any="igf_context_pairs.jbl" , ): """simple docstring""" set_seed(3 ) # generate train_data and objective_set UpperCamelCase__ , UpperCamelCase__ = generate_datasets( _snake_case , _snake_case , number=_snake_case , min_len=10_26 , trim=_snake_case ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? UpperCamelCase__ = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # load pretrained model UpperCamelCase__ = load_gpta("gpt2" ).to(_snake_case ) print("computing perplexity on objective set" ) UpperCamelCase__ = compute_perplexity(_snake_case , _snake_case , _snake_case ).item() print("perplexity on objective set:" , _snake_case ) # collect igf pairs and save to file demo.jbl collect_objective_set(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def snake_case__ ( _snake_case : Any , _snake_case : str=15 , _snake_case : str=1_28 , _snake_case : int=1_00 , _snake_case : Tuple="igf_model.pt" , ): """simple docstring""" set_seed(42 ) # Load pre-trained model UpperCamelCase__ = GPTaLMHeadModel.from_pretrained("gpt2" ) # Initialize secondary learner to use embedding weights of model UpperCamelCase__ = SecondaryLearner(_snake_case ) # Train secondary learner UpperCamelCase__ = train_secondary_learner( _snake_case , _snake_case , max_epochs=_snake_case , batch_size=_snake_case , eval_freq=1_00 , igf_model_path=_snake_case , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def snake_case__ ( _snake_case : List[Any] , _snake_case : Optional[int] , _snake_case : Optional[int] , _snake_case : List[str]=32 , _snake_case : Tuple=10_00 , _snake_case : List[Any]=16 , _snake_case : str=1.0 , _snake_case : List[str]=recopy_gpta , _snake_case : Optional[int]=None , _snake_case : Optional[int]=10 , _snake_case : Optional[int]="gpt2_finetuned.pt" , ): """simple docstring""" UpperCamelCase__ = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) UpperCamelCase__ = RandomSampler(_snake_case ) UpperCamelCase__ = DataLoader(_snake_case , sampler=_snake_case ) UpperCamelCase__ = max_steps // (len(_snake_case )) + 1 UpperCamelCase__ = 0 UpperCamelCase__ = torch.zeros((1, context_len) , dtype=torch.long , device=_snake_case ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = recopy_model(_snake_case , _snake_case , _snake_case ) model.train() if secondary_learner is not None: secondary_learner.to(_snake_case ) secondary_learner.eval() UpperCamelCase__ = [] UpperCamelCase__ = 0 UpperCamelCase__ = [] UpperCamelCase__ = [] # Compute the performance of the transformer model at the beginning UpperCamelCase__ = compute_perplexity(_snake_case , _snake_case , _snake_case ) test_perps.append(_snake_case ) print("Test perplexity, step" , _snake_case , ":" , _snake_case ) for epoch in range(int(_snake_case ) ): for step, example in enumerate(_snake_case ): torch.cuda.empty_cache() UpperCamelCase__ = random.randint(0 , example.size(2 ) - context_len - 1 ) UpperCamelCase__ = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() UpperCamelCase__ = model(_snake_case , labels=_snake_case ) UpperCamelCase__ = True if secondary_learner is not None: UpperCamelCase__ = secondary_learner.forward( torch.tensor(_snake_case , dtype=torch.long , device=_snake_case ).unsqueeze(0 ) )[0].item() observed_qs.append(float(_snake_case ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: UpperCamelCase__ = -1 if predicted_q < threshold: UpperCamelCase__ = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) UpperCamelCase__ = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() UpperCamelCase__ = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: UpperCamelCase__ = compute_perplexity(_snake_case , _snake_case , _snake_case ) test_perps.append(_snake_case ) print("Test perplexity, step" , _snake_case , ":" , _snake_case ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , _snake_case ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def snake_case__ ( ): """simple docstring""" UpperCamelCase__ = argparse.ArgumentParser(description="Fine-tune a transformer model with IGF on a language modeling task" ) # Required parameters parser.add_argument( "--data_dir" , default=_snake_case , type=_snake_case , required=_snake_case , help="The input data dir. Should contain data files for WikiText." , ) parser.add_argument( "--model_name_or_path" , default=_snake_case , type=_snake_case , required=_snake_case , help="Path to pretrained model or model identifier from huggingface.co/models" , ) parser.add_argument( "--data_file" , type=_snake_case , default=_snake_case , help=( "A jbl file containing tokenized data which can be split as objective dataset, " "train_dataset and test_dataset." ) , ) parser.add_argument( "--igf_data_file" , type=_snake_case , default=_snake_case , help="A jbl file containing the context and information gain pairs to train secondary learner." , ) parser.add_argument( "--output_dir" , default=_snake_case , type=_snake_case , required=_snake_case , help="The output directory where the final fine-tuned model is stored." , ) parser.add_argument( "--tokenizer_name" , default=_snake_case , type=_snake_case , help="Pretrained tokenizer name or path if not the same as model_name" , ) parser.add_argument("--seed" , type=_snake_case , default=_snake_case , help="A seed for reproducible training." ) parser.add_argument( "--context_len" , default=32 , type=_snake_case , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--size_objective_set" , default=1_00 , type=_snake_case , help="number of articles that are long enough to be used as our objective set" , ) parser.add_argument( "--eval_freq" , default=1_00 , type=_snake_case , help="secondary model evaluation is triggered at eval_freq" ) parser.add_argument("--max_steps" , default=10_00 , type=_snake_case , help="To calculate training epochs" ) parser.add_argument( "--secondary_learner_batch_size" , default=1_28 , type=_snake_case , help="batch size of training data for secondary learner" , ) parser.add_argument( "--batch_size" , default=16 , type=_snake_case , help="batch size of training data of language model(gpt2) " ) parser.add_argument( "--eval_interval" , default=10 , type=_snake_case , help=( "decay the selectivity of our secondary learner filter from" "1 standard deviation above average to 1 below average after 10 batches" ) , ) parser.add_argument( "--number" , default=1_00 , type=_snake_case , help="The number of examples split to be used as objective_set/test_data" ) parser.add_argument( "--min_len" , default=10_26 , type=_snake_case , help="The minimum length of the article to be used as objective set" ) parser.add_argument( "--secondary_learner_max_epochs" , default=15 , type=_snake_case , help="number of epochs to train secondary learner" ) parser.add_argument("--trim" , default=_snake_case , type=_snake_case , help="truncate the example if it exceeds context length" ) parser.add_argument( "--threshold" , default=1.0 , type=_snake_case , help=( "The threshold value used by secondary learner to filter the train_data and allow only" " informative data as input to the model" ) , ) parser.add_argument("--finetuned_model_name" , default="gpt2_finetuned.pt" , type=_snake_case , help="finetuned_model_name" ) parser.add_argument( "--recopy_model" , default=_snake_case , type=_snake_case , help="Reset the model to the original pretrained GPT-2 weights after each iteration" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=1_00 , min_len=10_26 , trim=_snake_case , data_file="data/tokenized_stories_train_wikitext103.jbl" , igf_data_file="igf_context_pairs.jbl" , ) # Load train data for secondary learner UpperCamelCase__ = joblib.load("data/IGF_values.jbl" ) # Train secondary learner UpperCamelCase__ = training_secondary_learner( _snake_case , secondary_learner_max_epochs=15 , secondary_learner_batch_size=1_28 , eval_freq=1_00 , igf_model_path="igf_model.pt" , ) # load pretrained gpt2 model UpperCamelCase__ = GPTaLMHeadModel.from_pretrained("gpt2" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model UpperCamelCase__ , UpperCamelCase__ = generate_datasets( context_len=32 , file="data/tokenized_stories_train_wikitext103.jbl" , number=1_00 , min_len=10_26 , trim=_snake_case ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( _snake_case , _snake_case , _snake_case , context_len=32 , max_steps=10_00 , batch_size=16 , threshold=1.0 , recopy_model=_snake_case , secondary_learner=_snake_case , eval_interval=10 , finetuned_model_name="gpt2_finetuned.pt" , ) if __name__ == "__main__": main()
516
"""simple docstring""" import math from numpy import inf from scipy.integrate import quad def snake_case__ ( _snake_case : float ): """simple docstring""" if num <= 0: raise ValueError("math domain error" ) return quad(_snake_case , 0 , _snake_case , args=(_snake_case) )[0] def snake_case__ ( _snake_case : float , _snake_case : float ): """simple docstring""" return math.pow(_snake_case , z - 1 ) * math.exp(-x ) if __name__ == "__main__": from doctest import testmod testmod()
516
1
"""simple docstring""" # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class a ( _SCREAMING_SNAKE_CASE ): """simple docstring""" A__ : torch.FloatTensor A__ : Optional[torch.FloatTensor] = None def A__ ( A__ , A__=0.999 , A__="cosine" , ) -> str: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(A__ ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(A__ ): return math.exp(t * -12.0 ) else: raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) _UpperCAmelCase = [] for i in range(A__ ): _UpperCAmelCase = i / num_diffusion_timesteps _UpperCAmelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(A__ ) / alpha_bar_fn(A__ ) , A__ ) ) return torch.tensor(A__ , dtype=torch.floataa ) class a ( _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ): """simple docstring""" A__ : Tuple = 1 @register_to_config def __init__( self , snake_case_ = 1000 , snake_case_ = 0.00_01 , snake_case_ = 0.02 , snake_case_ = "linear" , snake_case_ = None , snake_case_ = True , snake_case_ = True , snake_case_ = 0 , snake_case_ = "epsilon" , snake_case_ = 1.0 , **snake_case_ , ) -> Union[str, Any]: if kwargs.get("set_alpha_to_one" , snake_case_ ) is not None: _UpperCAmelCase = ( "The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead." ) deprecate("set_alpha_to_one" , "1.0.0" , snake_case_ , standard_warn=snake_case_ ) _UpperCAmelCase = kwargs["set_alpha_to_one"] if trained_betas is not None: _UpperCAmelCase = torch.tensor(snake_case_ , dtype=torch.floataa ) elif beta_schedule == "linear": _UpperCAmelCase = torch.linspace(snake_case_ , snake_case_ , snake_case_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _UpperCAmelCase = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , snake_case_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _UpperCAmelCase = betas_for_alpha_bar(snake_case_ ) else: raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""" ) _UpperCAmelCase = 1.0 - self.betas _UpperCAmelCase = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. _UpperCAmelCase = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution _UpperCAmelCase = 1.0 # setable values _UpperCAmelCase = None _UpperCAmelCase = torch.from_numpy(np.arange(0 , snake_case_ ).copy().astype(np.intaa ) ) def __A ( self , snake_case_ , snake_case_ = None ) -> torch.FloatTensor: return sample def __A ( self , snake_case_ , snake_case_ = None ) -> List[str]: if num_inference_steps > self.config.num_train_timesteps: raise ValueError( F"""`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:""" F""" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle""" F""" maximal {self.config.num_train_timesteps} timesteps.""" ) _UpperCAmelCase = num_inference_steps _UpperCAmelCase = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _UpperCAmelCase = (np.arange(0 , snake_case_ ) * step_ratio).round().copy().astype(np.intaa ) _UpperCAmelCase = torch.from_numpy(snake_case_ ).to(snake_case_ ) self.timesteps += self.config.steps_offset def __A ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ = 0.0 , snake_case_ = False , snake_case_ = None , snake_case_ = True , ) -> Union[DDIMSchedulerOutput, Tuple]: # 1. get previous step value (=t+1) _UpperCAmelCase = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process _UpperCAmelCase = self.alphas_cumprod[timestep] _UpperCAmelCase = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) _UpperCAmelCase = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": _UpperCAmelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 _UpperCAmelCase = model_output elif self.config.prediction_type == "sample": _UpperCAmelCase = model_output _UpperCAmelCase = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": _UpperCAmelCase = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output _UpperCAmelCase = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or""" " `v_prediction`" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: _UpperCAmelCase = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _UpperCAmelCase = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _UpperCAmelCase = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=snake_case_ , pred_original_sample=snake_case_ ) def __len__( self ) -> Optional[Any]: return self.config.num_train_timesteps
579
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { '''edbeeching/decision-transformer-gym-hopper-medium''': ( '''https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json''' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class a ( _SCREAMING_SNAKE_CASE ): """simple docstring""" A__ : Optional[int] = "decision_transformer" A__ : List[Any] = ["past_key_values"] A__ : Optional[int] = { "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , snake_case_=17 , snake_case_=4 , snake_case_=128 , snake_case_=4096 , snake_case_=True , snake_case_=1 , snake_case_=1024 , snake_case_=3 , snake_case_=1 , snake_case_=None , snake_case_="relu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=0.1 , snake_case_=1e-5 , snake_case_=0.02 , snake_case_=True , snake_case_=True , snake_case_=50256 , snake_case_=50256 , snake_case_=False , snake_case_=False , **snake_case_ , ) -> Union[str, Any]: _UpperCAmelCase = state_dim _UpperCAmelCase = act_dim _UpperCAmelCase = hidden_size _UpperCAmelCase = max_ep_len _UpperCAmelCase = action_tanh _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = n_inner _UpperCAmelCase = activation_function _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = attn_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = scale_attn_weights _UpperCAmelCase = use_cache _UpperCAmelCase = scale_attn_by_inverse_layer_idx _UpperCAmelCase = reorder_and_upcast_attn _UpperCAmelCase = bos_token_id _UpperCAmelCase = eos_token_id super().__init__(bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ )
579
1
"""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 snake_case__ : @staticmethod def __lowerCAmelCase ( *lowercase : Any , **lowercase : str ): '''simple docstring''' pass def lowercase_ ( _lowercase : Image ): '''simple docstring''' UpperCAmelCase : str = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def lowercase_ ( _lowercase : Image ): '''simple docstring''' UpperCAmelCase : int = np.array(_lowercase ) UpperCAmelCase : Union[str, Any] = npimg.shape return {"hash": hashimage(_lowercase ), "shape": shape} @is_pipeline_test @require_vision @require_torch class snake_case__ ( 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 __lowerCAmelCase ( self : List[Any] , lowercase : List[str] , lowercase : Dict , lowercase : str ): '''simple docstring''' UpperCAmelCase : Optional[Any] = MaskGenerationPipeline(model=lowercase , image_processor=lowercase ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def __lowerCAmelCase ( self : Optional[Any] , lowercase : Dict , lowercase : Dict ): '''simple docstring''' pass @require_tf @unittest.skip("Image segmentation not implemented in TF" ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' pass @slow @require_torch def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' UpperCAmelCase : Any = pipeline("mask-generation" , model="facebook/sam-vit-huge" ) UpperCAmelCase : str = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg" , points_per_batch=2_56 ) # Shortening by hashing UpperCAmelCase : Optional[Any] = [] 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": (4_80, 6_40)}, "scores": 1.0_4_4_4}, {"mask": {"hash": "6affa964c6", "shape": (4_80, 6_40)}, "scores": 1.0_2_1}, {"mask": {"hash": "dfe28a0388", "shape": (4_80, 6_40)}, "scores": 1.0_1_6_7}, {"mask": {"hash": "c0a5f4a318", "shape": (4_80, 6_40)}, "scores": 1.0_1_3_2}, {"mask": {"hash": "fe8065c197", "shape": (4_80, 6_40)}, "scores": 1.0_0_5_3}, {"mask": {"hash": "e2d0b7a0b7", "shape": (4_80, 6_40)}, "scores": 0.9_9_6_7}, {"mask": {"hash": "453c7844bd", "shape": (4_80, 6_40)}, "scores": 0.9_9_3}, {"mask": {"hash": "3d44f2926d", "shape": (4_80, 6_40)}, "scores": 0.9_9_0_9}, {"mask": {"hash": "64033ddc3f", "shape": (4_80, 6_40)}, "scores": 0.9_8_7_9}, {"mask": {"hash": "801064ff79", "shape": (4_80, 6_40)}, "scores": 0.9_8_3_4}, {"mask": {"hash": "6172f276ef", "shape": (4_80, 6_40)}, "scores": 0.9_7_1_6}, {"mask": {"hash": "b49e60e084", "shape": (4_80, 6_40)}, "scores": 0.9_6_1_2}, {"mask": {"hash": "a811e775fd", "shape": (4_80, 6_40)}, "scores": 0.9_5_9_9}, {"mask": {"hash": "a6a8ebcf4b", "shape": (4_80, 6_40)}, "scores": 0.9_5_5_2}, {"mask": {"hash": "9d8257e080", "shape": (4_80, 6_40)}, "scores": 0.9_5_3_2}, {"mask": {"hash": "32de6454a8", "shape": (4_80, 6_40)}, "scores": 0.9_5_1_6}, {"mask": {"hash": "af3d4af2c8", "shape": (4_80, 6_40)}, "scores": 0.9_4_9_9}, {"mask": {"hash": "3c6db475fb", "shape": (4_80, 6_40)}, "scores": 0.9_4_8_3}, {"mask": {"hash": "c290813fb9", "shape": (4_80, 6_40)}, "scores": 0.9_4_6_4}, {"mask": {"hash": "b6f0b8f606", "shape": (4_80, 6_40)}, "scores": 0.9_4_3}, {"mask": {"hash": "92ce16bfdf", "shape": (4_80, 6_40)}, "scores": 0.9_4_3}, {"mask": {"hash": "c749b25868", "shape": (4_80, 6_40)}, "scores": 0.9_4_0_8}, {"mask": {"hash": "efb6cab859", "shape": (4_80, 6_40)}, "scores": 0.9_3_3_5}, {"mask": {"hash": "1ff2eafb30", "shape": (4_80, 6_40)}, "scores": 0.9_3_2_6}, {"mask": {"hash": "788b798e24", "shape": (4_80, 6_40)}, "scores": 0.9_2_6_2}, {"mask": {"hash": "abea804f0e", "shape": (4_80, 6_40)}, "scores": 0.8_9_9_9}, {"mask": {"hash": "7b9e8ddb73", "shape": (4_80, 6_40)}, "scores": 0.8_9_8_6}, {"mask": {"hash": "cd24047c8a", "shape": (4_80, 6_40)}, "scores": 0.8_9_8_4}, {"mask": {"hash": "6943e6bcbd", "shape": (4_80, 6_40)}, "scores": 0.8_8_7_3}, {"mask": {"hash": "b5f47c9191", "shape": (4_80, 6_40)}, "scores": 0.8_8_7_1} ] , ) # fmt: on @require_torch @slow def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' UpperCAmelCase : List[Any] = "facebook/sam-vit-huge" UpperCAmelCase : Optional[int] = pipeline("mask-generation" , model=lowercase ) UpperCAmelCase : Dict = image_segmenter( "http://images.cocodataset.org/val2017/000000039769.jpg" , pred_iou_thresh=1 , points_per_batch=2_56 ) # Shortening by hashing UpperCAmelCase : str = [] 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": (4_80, 6_40)}, "scores": 1.0_4_4_4}, {"mask": {"hash": "6affa964c6", "shape": (4_80, 6_40)}, "scores": 1.0_2_1_0}, {"mask": {"hash": "dfe28a0388", "shape": (4_80, 6_40)}, "scores": 1.0_1_6_7}, {"mask": {"hash": "c0a5f4a318", "shape": (4_80, 6_40)}, "scores": 1.0_1_3_2}, {"mask": {"hash": "fe8065c197", "shape": (4_80, 6_40)}, "scores": 1.0_0_5_3}, ] , )
595
"""simple docstring""" import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( """The `inpainting.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionInpaintPipeline` instead.""" )
595
1
from __future__ import annotations def _snake_case ( lowerCAmelCase : list[float] , lowerCAmelCase : list[float] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = sorted(numsa + numsa ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = divmod(len(lowerCAmelCase ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() __lowerCamelCase : Tuple = [float(x) for x in input('''Enter the elements of first array: ''').split()] __lowerCamelCase : List[Any] = [float(x) for x in input('''Enter the elements of second array: ''').split()] print(f'''The median of two arrays is: {median_of_two_arrays(array_a, array_a)}''')
316
from typing import Any import numpy as np def _snake_case ( lowerCAmelCase : np.ndarray ): """simple docstring""" return np.array_equal(lowerCAmelCase , matrix.conjugate().T ) def _snake_case ( lowerCAmelCase : np.ndarray , lowerCAmelCase : np.ndarray ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = v.conjugate().T SCREAMING_SNAKE_CASE_ : int = v_star.dot(lowerCAmelCase ) assert isinstance(lowerCAmelCase , np.ndarray ) return (v_star_dot.dot(lowerCAmelCase )) / (v_star.dot(lowerCAmelCase )) def _snake_case ( ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = np.array([[2, 2 + 1J, 4], [2 - 1J, 3, 1J], [4, -1J, 1]] ) SCREAMING_SNAKE_CASE_ : Dict = np.array([[1], [2], [3]] ) assert is_hermitian(lowerCAmelCase ), f'{a} is not hermitian.' print(rayleigh_quotient(lowerCAmelCase , lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_ : int = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(lowerCAmelCase ), f'{a} is not hermitian.' assert rayleigh_quotient(lowerCAmelCase , lowerCAmelCase ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
316
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCAmelCase ( lowercase_ ): lowerCAmelCase__ = 4_2 lowerCAmelCase__ = 4_2 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.26.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version(""">=""", """0.0.12""") ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCAmelCase ( lowercase_ ): lowerCAmelCase__ = 4_2 lowerCAmelCase__ = 4_2 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
175
'''simple docstring''' __snake_case : Optional[Any] = 8.314462 # Unit - J mol-1 K-1 def __lowerCamelCase ( __snake_case : float, __snake_case : float, __snake_case : float ) -> float: """simple docstring""" if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def __lowerCamelCase ( __snake_case : float, __snake_case : float, __snake_case : float ) -> float: """simple docstring""" if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("""Invalid inputs. Enter positive value.""" ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
215
0
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class snake_case ( __a ): '''simple docstring''' @staticmethod @abstractmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : ArgumentParser ): '''simple docstring''' raise NotImplementedError() @abstractmethod def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' raise NotImplementedError()
706
"""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() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
215
0
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency lowerCAmelCase__ : int ={ '''E''': 12.70, '''T''': 9.06, '''A''': 8.17, '''O''': 7.51, '''I''': 6.97, '''N''': 6.75, '''S''': 6.33, '''H''': 6.09, '''R''': 5.99, '''D''': 4.25, '''L''': 4.03, '''C''': 2.78, '''U''': 2.76, '''M''': 2.41, '''W''': 2.36, '''F''': 2.23, '''G''': 2.02, '''Y''': 1.97, '''P''': 1.93, '''B''': 1.29, '''V''': 0.98, '''K''': 0.77, '''J''': 0.15, '''X''': 0.15, '''Q''': 0.10, '''Z''': 0.07, } lowerCAmelCase__ : Dict ='''ETAOINSHRDLCUMWFGYPBVKJXQZ''' lowerCAmelCase__ : Any ='''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' def __lowercase ( a__ ) -> dict[str, int]: __SCREAMING_SNAKE_CASE = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def __lowercase ( a__ ) -> str: return x[0] def __lowercase ( a__ ) -> str: __SCREAMING_SNAKE_CASE = get_letter_count(a__ ) __SCREAMING_SNAKE_CASE = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(a__ ) __SCREAMING_SNAKE_CASE = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=a__ ) __SCREAMING_SNAKE_CASE = ''.join(freq_to_letter[freq] ) __SCREAMING_SNAKE_CASE = list(freq_to_letter_str.items() ) freq_pairs.sort(key=a__ , reverse=a__ ) __SCREAMING_SNAKE_CASE = [freq_pair[1] for freq_pair in freq_pairs] return "".join(a__ ) def __lowercase ( a__ ) -> int: __SCREAMING_SNAKE_CASE = get_frequency_order(a__ ) __SCREAMING_SNAKE_CASE = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
148
import argparse from collections import defaultdict import yaml lowerCAmelCase__ : Optional[int] ='''docs/source/en/_toctree.yml''' def __lowercase ( a__ ) -> List[Any]: __SCREAMING_SNAKE_CASE = defaultdict(a__ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] 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__ ) __SCREAMING_SNAKE_CASE = new_doc_list __SCREAMING_SNAKE_CASE = [key for key, value in counts.items() if value > 1] __SCREAMING_SNAKE_CASE = [] for duplicate_key in duplicates: __SCREAMING_SNAKE_CASE = 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] ) __SCREAMING_SNAKE_CASE = 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 __lowercase ( a__=False ) -> List[Any]: with open(a__ , encoding='utf-8' ) as f: __SCREAMING_SNAKE_CASE = yaml.safe_load(f.read() ) # Get to the API doc __SCREAMING_SNAKE_CASE = 0 while content[api_idx]["title"] != "API": api_idx += 1 __SCREAMING_SNAKE_CASE = content[api_idx]['sections'] # Then to the model doc __SCREAMING_SNAKE_CASE = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 __SCREAMING_SNAKE_CASE = api_doc[scheduler_idx]['sections'] __SCREAMING_SNAKE_CASE = clean_doc_toc(a__ ) __SCREAMING_SNAKE_CASE = False if new_scheduler_doc != scheduler_doc: __SCREAMING_SNAKE_CASE = True if overwrite: __SCREAMING_SNAKE_CASE = new_scheduler_doc if diff: if overwrite: __SCREAMING_SNAKE_CASE = 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 __lowercase ( a__=False ) -> Union[str, Any]: with open(a__ , encoding='utf-8' ) as f: __SCREAMING_SNAKE_CASE = yaml.safe_load(f.read() ) # Get to the API doc __SCREAMING_SNAKE_CASE = 0 while content[api_idx]["title"] != "API": api_idx += 1 __SCREAMING_SNAKE_CASE = content[api_idx]['sections'] # Then to the model doc __SCREAMING_SNAKE_CASE = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = api_doc[pipeline_idx]['sections'] __SCREAMING_SNAKE_CASE = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: __SCREAMING_SNAKE_CASE = pipeline_doc['section'] __SCREAMING_SNAKE_CASE = clean_doc_toc(a__ ) if overwrite: __SCREAMING_SNAKE_CASE = new_sub_pipeline_doc new_pipeline_docs.append(a__ ) # sort overall pipeline doc __SCREAMING_SNAKE_CASE = clean_doc_toc(a__ ) if new_pipeline_docs != pipeline_docs: __SCREAMING_SNAKE_CASE = True if overwrite: __SCREAMING_SNAKE_CASE = new_pipeline_docs if diff: if overwrite: __SCREAMING_SNAKE_CASE = 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__": lowerCAmelCase__ : str =argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') lowerCAmelCase__ : Optional[int] =parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
148
1
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging lowercase_: Union[str, Any] = logging.get_logger(__name__) def _lowercase ( UpperCAmelCase_): """simple docstring""" if isinstance(UpperCAmelCase_ , np.ndarray): return list(tensor.shape) snake_case__ : List[Any] = tf.shape(UpperCAmelCase_) if tensor.shape == tf.TensorShape(UpperCAmelCase_): return dynamic snake_case__ : Tuple = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(UpperCAmelCase_)] def _lowercase ( UpperCAmelCase_ , UpperCAmelCase_ = None , UpperCAmelCase_ = None): """simple docstring""" return tf.nn.softmax(logits=logits + 1e-9 , axis=UpperCAmelCase_ , name=UpperCAmelCase_) def _lowercase ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_=1e-5 , UpperCAmelCase_=-1): """simple docstring""" if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(UpperCAmelCase_ , UpperCAmelCase_): raise NotImplementedError("""Only 1D weight and bias tensors are supported for now, with only a single axis.""") # Get mean and variance on the axis to be normalized snake_case__ , snake_case__ : Any = tf.nn.moments(UpperCAmelCase_ , axes=[axis] , keepdims=UpperCAmelCase_) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis snake_case__ : Optional[Any] = [1] * inputs.shape.rank snake_case__ : Optional[int] = shape_list(UpperCAmelCase_)[axis] snake_case__ : Tuple = tf.reshape(UpperCAmelCase_ , UpperCAmelCase_) snake_case__ : Tuple = tf.reshape(UpperCAmelCase_ , UpperCAmelCase_) # Compute layer normalization using the batch_normalization # function. snake_case__ : List[str] = tf.nn.batch_normalization( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , offset=UpperCAmelCase_ , scale=UpperCAmelCase_ , variance_epsilon=UpperCAmelCase_ , ) return outputs def _lowercase ( UpperCAmelCase_ , UpperCAmelCase_=0 , UpperCAmelCase_=-1): """simple docstring""" if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input snake_case__ : Optional[int] = tf.shape(UpperCAmelCase_) snake_case__ : List[Any] = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]) snake_case__ : Optional[Any] = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0) return tf.reshape(UpperCAmelCase_ , UpperCAmelCase_) def _lowercase ( UpperCAmelCase_): """simple docstring""" if not isinstance(UpperCAmelCase_ , tf.Tensor): snake_case__ : int = tf.convert_to_tensor(UpperCAmelCase_) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: snake_case__ : Dict = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: snake_case__ : List[Any] = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) snake_case__ : Dict = ( tf.cast(1 , encoder_attention_mask.dtype) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def _lowercase ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = "input_ids"): """simple docstring""" tf.debugging.assert_less( UpperCAmelCase_ , tf.cast(UpperCAmelCase_ , dtype=tensor.dtype) , message=( F'The maximum value of {tensor_name} ({tf.math.reduce_max(UpperCAmelCase_)}) must be smaller than the embedding ' F'layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.' ) , ) def _lowercase ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_): """simple docstring""" snake_case__ : List[str] = 64_512 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. snake_case__ : Tuple = [x for x in data if len(UpperCAmelCase_) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( """The following attributes cannot be saved to HDF5 file because """ F'they are larger than {HDF5_OBJECT_HEADER_LIMIT} ' F'bytes: {bad_attributes}') snake_case__ : Optional[int] = np.asarray(UpperCAmelCase_) snake_case__ : Tuple = 1 snake_case__ : Optional[Any] = np.array_split(UpperCAmelCase_ , UpperCAmelCase_) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data): num_chunks += 1 snake_case__ : Tuple = np.array_split(UpperCAmelCase_ , UpperCAmelCase_) if num_chunks > 1: for chunk_id, chunk_data in enumerate(UpperCAmelCase_): snake_case__ : List[str] = chunk_data else: snake_case__ : Union[str, Any] = data def _lowercase ( UpperCAmelCase_ , UpperCAmelCase_): """simple docstring""" if name in group.attrs: snake_case__ : int = [n.decode("""utf8""") if hasattr(UpperCAmelCase_ , """decode""") else n for n in group.attrs[name]] else: snake_case__ : Tuple = [] snake_case__ : Optional[Any] = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode("""utf8""") if hasattr(UpperCAmelCase_ , """decode""") else n for n in group.attrs["""%s%d""" % (name, chunk_id)]]) chunk_id += 1 return data def _lowercase ( UpperCAmelCase_): """simple docstring""" def _expand_single_ad_tensor(UpperCAmelCase_): if isinstance(UpperCAmelCase_ , tf.Tensor) and t.shape.rank == 1: return tf.expand_dims(UpperCAmelCase_ , axis=-1) return t return tf.nest.map_structure(_expand_single_ad_tensor , UpperCAmelCase_)
127
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_: str = logging.get_logger(__name__) lowercase_: List[str] = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class lowercase__ (__snake_case ): """simple docstring""" __UpperCamelCase : Any = 'vit_msn' def __init__( self : Optional[int] , __a : List[str]=7_6_8 , __a : Union[str, Any]=1_2 , __a : Dict=1_2 , __a : Union[str, Any]=3_0_7_2 , __a : int="gelu" , __a : int=0.0 , __a : Dict=0.0 , __a : Optional[int]=0.02 , __a : Any=1e-06 , __a : Any=2_2_4 , __a : Tuple=1_6 , __a : List[Any]=3 , __a : Tuple=True , **__a : Optional[Any] , ): super().__init__(**__a ) snake_case__ : str = hidden_size snake_case__ : Union[str, Any] = num_hidden_layers snake_case__ : Tuple = num_attention_heads snake_case__ : Optional[int] = intermediate_size snake_case__ : int = hidden_act snake_case__ : List[str] = hidden_dropout_prob snake_case__ : List[Any] = attention_probs_dropout_prob snake_case__ : Tuple = initializer_range snake_case__ : Dict = layer_norm_eps snake_case__ : Union[str, Any] = image_size snake_case__ : Optional[int] = patch_size snake_case__ : Optional[int] = num_channels snake_case__ : Dict = qkv_bias
127
1
'''simple docstring''' from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def lowerCamelCase__ ( ): '''simple docstring''' UpperCAmelCase = HfArgumentParser(UpperCamelCase__ ) UpperCAmelCase = parser.parse_args_into_dataclasses()[0] UpperCAmelCase = TensorFlowBenchmark(args=UpperCamelCase__ ) try: UpperCAmelCase = parser.parse_args_into_dataclasses()[0] except ValueError as e: UpperCAmelCase = '''Arg --no_{0} is no longer used, please use --no-{0} instead.''' UpperCAmelCase = ''' '''.join(str(UpperCamelCase__ ).split(''' ''' )[:-1] ) UpperCAmelCase = '''''' UpperCAmelCase = eval(str(UpperCamelCase__ ).split(''' ''' )[-1] ) UpperCAmelCase = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: UpperCAmelCase = full_error_msg + begin_error_msg + str(UpperCamelCase__ ) raise ValueError(UpperCamelCase__ ) benchmark.run() if __name__ == "__main__": main()
210
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable __magic_name__ = {'''configuration_gpt_neox''': ['''GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXConfig''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['''GPTNeoXTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ '''GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXForCausalLM''', '''GPTNeoXForQuestionAnswering''', '''GPTNeoXForSequenceClassification''', '''GPTNeoXForTokenClassification''', '''GPTNeoXLayer''', '''GPTNeoXModel''', '''GPTNeoXPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
657
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A__ : int = {"""configuration_deit""": ["""DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DeiTConfig""", """DeiTOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = ["""DeiTFeatureExtractor"""] A__ : Union[str, Any] = ["""DeiTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ """DEIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """DeiTForImageClassification""", """DeiTForImageClassificationWithTeacher""", """DeiTForMaskedImageModeling""", """DeiTModel""", """DeiTPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Union[str, Any] = [ """TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFDeiTForImageClassification""", """TFDeiTForImageClassificationWithTeacher""", """TFDeiTForMaskedImageModeling""", """TFDeiTModel""", """TFDeiTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys A__ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
660
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING A__ : Union[str, Any] = logging.get_logger(__name__) A__ : Optional[int] = { """microsoft/table-transformer-detection""": ( """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json""" ), } class _lowercase ( lowerCAmelCase_ ): '''simple docstring''' _A = 'table-transformer' _A = ['past_key_values'] _A = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self , __UpperCamelCase=True , __UpperCamelCase=None , __UpperCamelCase=3 , __UpperCamelCase=1_00 , __UpperCamelCase=6 , __UpperCamelCase=20_48 , __UpperCamelCase=8 , __UpperCamelCase=6 , __UpperCamelCase=20_48 , __UpperCamelCase=8 , __UpperCamelCase=0.0 , __UpperCamelCase=0.0 , __UpperCamelCase=True , __UpperCamelCase="relu" , __UpperCamelCase=2_56 , __UpperCamelCase=0.1 , __UpperCamelCase=0.0 , __UpperCamelCase=0.0 , __UpperCamelCase=0.02 , __UpperCamelCase=1.0 , __UpperCamelCase=False , __UpperCamelCase="sine" , __UpperCamelCase="resnet50" , __UpperCamelCase=True , __UpperCamelCase=False , __UpperCamelCase=1 , __UpperCamelCase=5 , __UpperCamelCase=2 , __UpperCamelCase=1 , __UpperCamelCase=1 , __UpperCamelCase=5 , __UpperCamelCase=2 , __UpperCamelCase=0.1 , **__UpperCamelCase , )-> List[Any]: 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__ : Any = CONFIG_MAPPING["resnet"](out_features=["stage4"] ) elif isinstance(__UpperCamelCase , __UpperCamelCase ): UpperCAmelCase__ : int = backbone_config.get("model_type" ) UpperCAmelCase__ : Optional[Any] = CONFIG_MAPPING[backbone_model_type] UpperCAmelCase__ : int = config_class.from_dict(__UpperCamelCase ) # set timm attributes to None UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : List[str] = None, None, None UpperCAmelCase__ : Optional[int] = use_timm_backbone UpperCAmelCase__ : Dict = backbone_config UpperCAmelCase__ : List[Any] = num_channels UpperCAmelCase__ : Any = num_queries UpperCAmelCase__ : int = d_model UpperCAmelCase__ : Optional[int] = encoder_ffn_dim UpperCAmelCase__ : str = encoder_layers UpperCAmelCase__ : Dict = encoder_attention_heads UpperCAmelCase__ : Optional[Any] = decoder_ffn_dim UpperCAmelCase__ : Tuple = decoder_layers UpperCAmelCase__ : Optional[Any] = decoder_attention_heads UpperCAmelCase__ : List[str] = dropout UpperCAmelCase__ : Tuple = attention_dropout UpperCAmelCase__ : List[Any] = activation_dropout UpperCAmelCase__ : Dict = activation_function UpperCAmelCase__ : Optional[Any] = init_std UpperCAmelCase__ : List[str] = init_xavier_std UpperCAmelCase__ : int = encoder_layerdrop UpperCAmelCase__ : Tuple = decoder_layerdrop UpperCAmelCase__ : int = encoder_layers UpperCAmelCase__ : Dict = auxiliary_loss UpperCAmelCase__ : Union[str, Any] = position_embedding_type UpperCAmelCase__ : List[str] = backbone UpperCAmelCase__ : List[Any] = use_pretrained_backbone UpperCAmelCase__ : List[str] = dilation # Hungarian matcher UpperCAmelCase__ : Dict = class_cost UpperCAmelCase__ : Any = bbox_cost UpperCAmelCase__ : Tuple = giou_cost # Loss coefficients UpperCAmelCase__ : Any = mask_loss_coefficient UpperCAmelCase__ : Dict = dice_loss_coefficient UpperCAmelCase__ : Any = bbox_loss_coefficient UpperCAmelCase__ : Tuple = giou_loss_coefficient UpperCAmelCase__ : List[Any] = eos_coefficient super().__init__(is_encoder_decoder=__UpperCamelCase , **__UpperCamelCase ) @property def lowerCAmelCase__ ( self )-> int: return self.encoder_attention_heads @property def lowerCAmelCase__ ( self )-> int: return self.d_model class _lowercase ( lowerCAmelCase_ ): '''simple docstring''' _A = version.parse('1.11' ) @property def lowerCAmelCase__ ( self )-> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ("pixel_mask", {0: "batch"}), ] ) @property def lowerCAmelCase__ ( self )-> float: return 1E-5 @property def lowerCAmelCase__ ( self )-> int: return 12
660
1
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class UpperCamelCase__ (SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): '''simple docstring''' @register_to_config def __init__( self , UpperCamelCase__ = 128 , UpperCamelCase__ = 256 , UpperCamelCase__ = 2000.0 , UpperCamelCase__ = 768 , UpperCamelCase__ = 12 , UpperCamelCase__ = 12 , UpperCamelCase__ = 64 , UpperCamelCase__ = 2048 , UpperCamelCase__ = 0.1 , ) -> List[Any]: super().__init__() lowerCamelCase : int = nn.Sequential( nn.Linear(UpperCamelCase__ , d_model * 4 , bias=UpperCamelCase__ ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=UpperCamelCase__ ) , nn.SiLU() , ) lowerCamelCase : Any = nn.Embedding(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : str = False lowerCamelCase : Any = nn.Linear(UpperCamelCase__ , UpperCamelCase__ , bias=UpperCamelCase__ ) lowerCamelCase : Any = nn.Dropout(p=UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = nn.ModuleList() for lyr_num in range(UpperCamelCase__ ): # FiLM conditional T5 decoder lowerCamelCase : int = DecoderLayer(d_model=UpperCamelCase__ , d_kv=UpperCamelCase__ , num_heads=UpperCamelCase__ , d_ff=UpperCamelCase__ , dropout_rate=UpperCamelCase__ ) self.decoders.append(UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = TaLayerNorm(UpperCamelCase__ ) lowerCamelCase : Dict = nn.Dropout(p=UpperCamelCase__ ) lowerCamelCase : int = nn.Linear(UpperCamelCase__ , UpperCamelCase__ , bias=UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> int: lowerCamelCase : str = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: lowerCamelCase : List[Any] = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. lowerCamelCase : Any = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) lowerCamelCase : str = self.conditioning_emb(UpperCamelCase__ ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) lowerCamelCase : Optional[Any] = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. lowerCamelCase : List[Any] = torch.broadcast_to( torch.arange(UpperCamelCase__ , device=decoder_input_tokens.device ) , (batch, seq_length) , ) lowerCamelCase : int = self.position_encoding(UpperCamelCase__ ) lowerCamelCase : str = self.continuous_inputs_projection(UpperCamelCase__ ) inputs += position_encodings lowerCamelCase : List[Any] = self.dropout(UpperCamelCase__ ) # decoder: No padding present. lowerCamelCase : Union[str, Any] = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. lowerCamelCase : Dict = [(x, self.encoder_decoder_mask(UpperCamelCase__ , UpperCamelCase__ )) for x, y in encodings_and_masks] # cross attend style: concat encodings lowerCamelCase : Optional[int] = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) lowerCamelCase : Union[str, Any] = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: lowerCamelCase : int = lyr( UpperCamelCase__ , conditioning_emb=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , )[0] lowerCamelCase : Dict = self.decoder_norm(UpperCamelCase__ ) lowerCamelCase : Optional[Any] = self.post_dropout(UpperCamelCase__ ) lowerCamelCase : Dict = self.spec_out(UpperCamelCase__ ) return spec_out class UpperCamelCase__ (nn.Module ): '''simple docstring''' def __init__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=1e-6 ) -> Optional[int]: super().__init__() lowerCamelCase : str = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=UpperCamelCase__ , d_kv=UpperCamelCase__ , num_heads=UpperCamelCase__ , dropout_rate=UpperCamelCase__ ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=UpperCamelCase__ , d_kv=UpperCamelCase__ , num_heads=UpperCamelCase__ , dropout_rate=UpperCamelCase__ , layer_norm_epsilon=UpperCamelCase__ , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=UpperCamelCase__ , d_ff=UpperCamelCase__ , dropout_rate=UpperCamelCase__ , layer_norm_epsilon=UpperCamelCase__ ) ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , ) -> List[str]: lowerCamelCase : Optional[int] = self.layer[0]( UpperCamelCase__ , conditioning_emb=UpperCamelCase__ , attention_mask=UpperCamelCase__ , ) if encoder_hidden_states is not None: lowerCamelCase : Dict = torch.where(encoder_attention_mask > 0 , 0 , -1e10 ).to( encoder_hidden_states.dtype ) lowerCamelCase : Any = self.layer[1]( UpperCamelCase__ , key_value_states=UpperCamelCase__ , attention_mask=UpperCamelCase__ , ) # Apply Film Conditional Feed Forward layer lowerCamelCase : Dict = self.layer[-1](UpperCamelCase__ , UpperCamelCase__ ) return (hidden_states,) class UpperCamelCase__ (nn.Module ): '''simple docstring''' def __init__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Any: super().__init__() lowerCamelCase : Union[str, Any] = TaLayerNorm(UpperCamelCase__ ) lowerCamelCase : Dict = TaFiLMLayer(in_features=d_model * 4 , out_features=UpperCamelCase__ ) lowerCamelCase : Optional[int] = Attention(query_dim=UpperCamelCase__ , heads=UpperCamelCase__ , dim_head=UpperCamelCase__ , out_bias=UpperCamelCase__ , scale_qk=UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = nn.Dropout(UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=None , ) -> Dict: lowerCamelCase : Tuple = self.layer_norm(UpperCamelCase__ ) if conditioning_emb is not None: lowerCamelCase : Dict = self.FiLMLayer(UpperCamelCase__ , UpperCamelCase__ ) # Self-attention block lowerCamelCase : str = self.attention(UpperCamelCase__ ) lowerCamelCase : Dict = hidden_states + self.dropout(UpperCamelCase__ ) return hidden_states class UpperCamelCase__ (nn.Module ): '''simple docstring''' def __init__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: super().__init__() lowerCamelCase : int = Attention(query_dim=UpperCamelCase__ , heads=UpperCamelCase__ , dim_head=UpperCamelCase__ , out_bias=UpperCamelCase__ , scale_qk=UpperCamelCase__ ) lowerCamelCase : Dict = TaLayerNorm(UpperCamelCase__ , eps=UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = nn.Dropout(UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=None , ) -> Optional[int]: lowerCamelCase : str = self.layer_norm(UpperCamelCase__ ) lowerCamelCase : Dict = self.attention( UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , attention_mask=attention_mask.squeeze(1 ) , ) lowerCamelCase : List[str] = hidden_states + self.dropout(UpperCamelCase__ ) return layer_output class UpperCamelCase__ (nn.Module ): '''simple docstring''' def __init__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Dict: super().__init__() lowerCamelCase : Dict = TaDenseGatedActDense(d_model=UpperCamelCase__ , d_ff=UpperCamelCase__ , dropout_rate=UpperCamelCase__ ) lowerCamelCase : List[str] = TaFiLMLayer(in_features=d_model * 4 , out_features=UpperCamelCase__ ) lowerCamelCase : str = TaLayerNorm(UpperCamelCase__ , eps=UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = nn.Dropout(UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__=None ) -> int: lowerCamelCase : Tuple = self.layer_norm(UpperCamelCase__ ) if conditioning_emb is not None: lowerCamelCase : Union[str, Any] = self.film(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : Any = self.DenseReluDense(UpperCamelCase__ ) lowerCamelCase : List[Any] = hidden_states + self.dropout(UpperCamelCase__ ) return hidden_states class UpperCamelCase__ (nn.Module ): '''simple docstring''' def __init__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: super().__init__() lowerCamelCase : List[Any] = nn.Linear(UpperCamelCase__ , UpperCamelCase__ , bias=UpperCamelCase__ ) lowerCamelCase : int = nn.Linear(UpperCamelCase__ , UpperCamelCase__ , bias=UpperCamelCase__ ) lowerCamelCase : Optional[int] = nn.Linear(UpperCamelCase__ , UpperCamelCase__ , bias=UpperCamelCase__ ) lowerCamelCase : List[str] = nn.Dropout(UpperCamelCase__ ) lowerCamelCase : List[str] = NewGELUActivation() def _lowercase ( self , UpperCamelCase__ ) -> int: lowerCamelCase : Tuple = self.act(self.wi_a(UpperCamelCase__ ) ) lowerCamelCase : Any = self.wi_a(UpperCamelCase__ ) lowerCamelCase : Any = hidden_gelu * hidden_linear lowerCamelCase : Union[str, Any] = self.dropout(UpperCamelCase__ ) lowerCamelCase : int = self.wo(UpperCamelCase__ ) return hidden_states class UpperCamelCase__ (nn.Module ): '''simple docstring''' def __init__( self , UpperCamelCase__ , UpperCamelCase__=1e-6 ) -> List[str]: super().__init__() lowerCamelCase : Optional[Any] = nn.Parameter(torch.ones(UpperCamelCase__ ) ) lowerCamelCase : Optional[int] = eps def _lowercase ( self , UpperCamelCase__ ) -> List[str]: lowerCamelCase : List[str] = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=UpperCamelCase__ ) lowerCamelCase : List[Any] = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: lowerCamelCase : List[Any] = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class UpperCamelCase__ (nn.Module ): '''simple docstring''' def _lowercase ( self , UpperCamelCase__ ) -> int: return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.044715 * torch.pow(UpperCamelCase__ , 3.0 )) )) class UpperCamelCase__ (nn.Module ): '''simple docstring''' def __init__( self , UpperCamelCase__ , UpperCamelCase__ ) -> Dict: super().__init__() lowerCamelCase : int = nn.Linear(UpperCamelCase__ , out_features * 2 , bias=UpperCamelCase__ ) def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> str: lowerCamelCase : Tuple = self.scale_bias(UpperCamelCase__ ) lowerCamelCase : Optional[int] = torch.chunk(UpperCamelCase__ , 2 , -1 ) lowerCamelCase : Optional[int] = x * (1 + scale) + shift return x
311
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class lowercase ( unittest.TestCase): '''simple docstring''' def __init__( self : int , snake_case : Optional[Any] , snake_case : Optional[Any]=13 , snake_case : str=7 , snake_case : Optional[Any]=True , snake_case : int=True , snake_case : str=True , snake_case : List[str]=True , snake_case : Optional[Any]=99 , snake_case : Optional[int]=32 , snake_case : Optional[int]=5 , snake_case : Optional[Any]=4 , snake_case : Optional[Any]=37 , snake_case : str="gelu" , snake_case : List[str]=0.1 , snake_case : List[str]=0.1 , snake_case : int=512 , snake_case : Union[str, Any]=16 , snake_case : Optional[Any]=2 , snake_case : int=0.02 , snake_case : str=4 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : Union[str, Any] = seq_length SCREAMING_SNAKE_CASE : int = is_training SCREAMING_SNAKE_CASE : List[str] = use_attention_mask SCREAMING_SNAKE_CASE : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE : Optional[int] = use_labels SCREAMING_SNAKE_CASE : Optional[int] = vocab_size SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Any = num_hidden_layers SCREAMING_SNAKE_CASE : Tuple = num_attention_heads SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : Tuple = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE : Any = type_vocab_size SCREAMING_SNAKE_CASE : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : List[str] = num_choices def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_attention_mask: SCREAMING_SNAKE_CASE : Any = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Tuple = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , tie_weights_=snake_case , ) return config, input_ids, attention_mask def lowerCamelCase_ ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE : int = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class lowercase ( SCREAMING_SNAKE_CASE_ , unittest.TestCase): '''simple docstring''' UpperCAmelCase : int = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = FlaxDistilBertModelTester(self ) @slow def lowerCamelCase_ ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE : Dict = model_class_name.from_pretrained('distilbert-base-uncased' ) SCREAMING_SNAKE_CASE : Dict = model(np.ones((1, 1) ) ) self.assertIsNotNone(snake_case ) @require_flax class lowercase ( unittest.TestCase): '''simple docstring''' @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased' ) SCREAMING_SNAKE_CASE : List[str] = np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) SCREAMING_SNAKE_CASE : Dict = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) SCREAMING_SNAKE_CASE : str = model(snake_case , attention_mask=snake_case )[0] SCREAMING_SNAKE_CASE : int = (1, 11, 768) self.assertEqual(output.shape , snake_case ) SCREAMING_SNAKE_CASE : Optional[int] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , snake_case , atol=1E-4 ) )
352
0
import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' self.assertEqual(len(__UpperCAmelCase ) , len(__UpperCAmelCase ) ) for a, b in zip(__UpperCAmelCase , __UpperCAmelCase ): self.assertAlmostEqual(__UpperCAmelCase , __UpperCAmelCase , delta=__UpperCAmelCase ) def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(__UpperCAmelCase ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1E-2 ) def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = None ops.enable_eager_execution_internal() __lowerCamelCase = tf.config.list_physical_devices('''CPU''' ) if len(__UpperCAmelCase ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __lowerCamelCase = tf.config.list_logical_devices(device_type='''CPU''' ) __lowerCamelCase = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __lowerCamelCase = GradientAccumulator() __lowerCamelCase = tf.Variable([4.0, 3.0] ) __lowerCamelCase ,__lowerCamelCase = create_optimizer(5E-5 , 10 , 5 ) __lowerCamelCase = tf.Variable([0.0, 0.0] , trainable=__UpperCAmelCase ) def accumulate_on_replica(__UpperCAmelCase ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(__UpperCAmelCase , __UpperCAmelCase ): with strategy.scope(): __lowerCamelCase = strategy.experimental_local_results(__UpperCAmelCase ) local_variables[0].assign(__UpperCAmelCase ) local_variables[1].assign(__UpperCAmelCase ) strategy.run(__UpperCAmelCase , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(__UpperCAmelCase ) def _check_local_values(__UpperCAmelCase , __UpperCAmelCase ): __lowerCamelCase = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , __UpperCAmelCase , tol=1E-2 ) self.assertListAlmostEqual(values[1].value() , __UpperCAmelCase , tol=1E-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
622
import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a_ = """true""" def a__ ( _UpperCamelCase : Union[str, Any] ,_UpperCamelCase : List[str]=82 ,_UpperCamelCase : Optional[Any]=16 ): set_seed(42 ) __lowerCamelCase = RegressionModel() __lowerCamelCase = deepcopy(_UpperCamelCase ) __lowerCamelCase = RegressionDataset(length=_UpperCamelCase ) __lowerCamelCase = DataLoader(_UpperCamelCase ,batch_size=_UpperCamelCase ) model.to(accelerator.device ) __lowerCamelCase ,__lowerCamelCase = accelerator.prepare(_UpperCamelCase ,_UpperCamelCase ) return model, ddp_model, dataloader def a__ ( _UpperCamelCase : Accelerator ,_UpperCamelCase : str=False ): __lowerCamelCase = AutoTokenizer.from_pretrained('''hf-internal-testing/mrpc-bert-base-cased''' ) __lowerCamelCase = load_dataset('''glue''' ,'''mrpc''' ,split='''validation''' ) def tokenize_function(_UpperCamelCase : int ): __lowerCamelCase = tokenizer(examples['''sentence1'''] ,examples['''sentence2'''] ,truncation=_UpperCamelCase ,max_length=_UpperCamelCase ) return outputs with accelerator.main_process_first(): __lowerCamelCase = dataset.map( _UpperCamelCase ,batched=_UpperCamelCase ,remove_columns=['''idx''', '''sentence1''', '''sentence2'''] ,) __lowerCamelCase = tokenized_datasets.rename_column('''label''' ,'''labels''' ) def collate_fn(_UpperCamelCase : Any ): if use_longest: return tokenizer.pad(_UpperCamelCase ,padding='''longest''' ,return_tensors='''pt''' ) return tokenizer.pad(_UpperCamelCase ,padding='''max_length''' ,max_length=1_28 ,return_tensors='''pt''' ) return DataLoader(_UpperCamelCase ,shuffle=_UpperCamelCase ,collate_fn=_UpperCamelCase ,batch_size=16 ) def a__ ( _UpperCamelCase : Dict ,_UpperCamelCase : List[str] ): __lowerCamelCase = Accelerator(dispatch_batches=_UpperCamelCase ,split_batches=_UpperCamelCase ) __lowerCamelCase = get_dataloader(_UpperCamelCase ,not dispatch_batches ) __lowerCamelCase = AutoModelForSequenceClassification.from_pretrained( '''hf-internal-testing/mrpc-bert-base-cased''' ,return_dict=_UpperCamelCase ) __lowerCamelCase ,__lowerCamelCase = accelerator.prepare(_UpperCamelCase ,_UpperCamelCase ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def a__ ( _UpperCamelCase : Dict ,_UpperCamelCase : Optional[Any] ,_UpperCamelCase : Union[str, Any] ): __lowerCamelCase = [] for batch in dataloader: __lowerCamelCase ,__lowerCamelCase = batch.values() with torch.no_grad(): __lowerCamelCase = model(_UpperCamelCase ) __lowerCamelCase ,__lowerCamelCase = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) __lowerCamelCase ,__lowerCamelCase = [], [] for logit, targ in logits_and_targets: logits.append(_UpperCamelCase ) targs.append(_UpperCamelCase ) __lowerCamelCase ,__lowerCamelCase = torch.cat(_UpperCamelCase ), torch.cat(_UpperCamelCase ) return logits, targs def a__ ( _UpperCamelCase : Accelerator ,_UpperCamelCase : List[Any]=82 ,_UpperCamelCase : str=False ,_UpperCamelCase : List[str]=False ,_UpperCamelCase : Optional[int]=16 ): __lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = get_basic_setup(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) __lowerCamelCase ,__lowerCamelCase = generate_predictions(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ) assert ( len(_UpperCamelCase ) == num_samples ), F"""Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(_UpperCamelCase )}""" def a__ ( _UpperCamelCase : bool = False ,_UpperCamelCase : bool = False ): __lowerCamelCase = evaluate.load('''glue''' ,'''mrpc''' ) __lowerCamelCase ,__lowerCamelCase = get_mrpc_setup(_UpperCamelCase ,_UpperCamelCase ) # First do baseline __lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = setup['''no'''] model.to(_UpperCamelCase ) model.eval() for batch in dataloader: batch.to(_UpperCamelCase ) with torch.inference_mode(): __lowerCamelCase = model(**_UpperCamelCase ) __lowerCamelCase = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=_UpperCamelCase ,references=batch['''labels'''] ) __lowerCamelCase = metric.compute() # Then do distributed __lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = setup['''ddp'''] model.eval() for batch in dataloader: with torch.inference_mode(): __lowerCamelCase = model(**_UpperCamelCase ) __lowerCamelCase = outputs.logits.argmax(dim=-1 ) __lowerCamelCase = batch['''labels'''] __lowerCamelCase ,__lowerCamelCase = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=_UpperCamelCase ,references=_UpperCamelCase ) __lowerCamelCase = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] ,distributed[key] ), F"""Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n""" def a__ ( ): __lowerCamelCase = Accelerator(split_batches=_UpperCamelCase ,dispatch_batches=_UpperCamelCase ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('''**Testing gather_for_metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F"""With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`""" ) test_mrpc(_UpperCamelCase ,_UpperCamelCase ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test torch metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: __lowerCamelCase = Accelerator(split_batches=_UpperCamelCase ,dispatch_batches=_UpperCamelCase ) if accelerator.is_local_main_process: print(F"""With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99""" ) test_torch_metrics(_UpperCamelCase ,99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test last batch is not dropped when perfectly divisible**''' ) __lowerCamelCase = Accelerator() test_torch_metrics(_UpperCamelCase ,5_12 ) accelerator.state._reset_state() def a__ ( _UpperCamelCase : Optional[int] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
622
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 lowercase_ ( _UpperCamelCase , unittest.TestCase ): """simple docstring""" __lowerCAmelCase = KandinskyVaaPriorPipeline __lowerCAmelCase = ["prompt"] __lowerCAmelCase = ["prompt", "negative_prompt"] __lowerCAmelCase = [ "num_images_per_prompt", "generator", "num_inference_steps", "latents", "negative_prompt", "guidance_scale", "output_type", "return_dict", ] __lowerCAmelCase = False @property def __UpperCAmelCase ( self : Dict ) -> Tuple: return 32 @property def __UpperCAmelCase ( self : Optional[int] ) -> Any: return 32 @property def __UpperCAmelCase ( self : Optional[Any] ) -> str: return self.time_input_dim @property def __UpperCAmelCase ( self : Optional[Any] ) -> Optional[Any]: return self.time_input_dim * 4 @property def __UpperCAmelCase ( self : str ) -> Union[str, Any]: return 1_00 @property def __UpperCAmelCase ( self : List[Any] ) -> Optional[int]: _A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def __UpperCAmelCase ( self : Dict ) -> Optional[Any]: torch.manual_seed(0 ) _A = 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-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=10_00, ) return CLIPTextModelWithProjection(UpperCamelCase__ ) @property def __UpperCAmelCase ( self : Optional[Any] ) -> Any: torch.manual_seed(0 ) _A = { 'num_attention_heads': 2, 'attention_head_dim': 12, 'embedding_dim': self.text_embedder_hidden_size, 'num_layers': 1, } _A = PriorTransformer(**UpperCamelCase__ ) # 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 _A = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def __UpperCAmelCase ( self : Dict ) -> Tuple: torch.manual_seed(0 ) _A = 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, ) _A = CLIPVisionModelWithProjection(UpperCamelCase__ ) return model @property def __UpperCAmelCase ( self : Dict ) -> List[Any]: _A = CLIPImageProcessor( crop_size=2_24, do_center_crop=UpperCamelCase__, do_normalize=UpperCamelCase__, do_resize=UpperCamelCase__, image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073], image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711], resample=3, size=2_24, ) return image_processor def __UpperCAmelCase ( self : List[Any] ) -> Optional[int]: _A = self.dummy_prior _A = self.dummy_image_encoder _A = self.dummy_text_encoder _A = self.dummy_tokenizer _A = self.dummy_image_processor _A = UnCLIPScheduler( variance_type='fixed_small_log', prediction_type='sample', num_train_timesteps=10_00, clip_sample=UpperCamelCase__, clip_sample_range=10.0, ) _A = { 'prior': prior, 'image_encoder': image_encoder, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'scheduler': scheduler, 'image_processor': image_processor, } return components def __UpperCAmelCase ( self : List[Any], UpperCamelCase__ : List[Any], UpperCamelCase__ : Tuple=0 ) -> Optional[Any]: if str(UpperCamelCase__ ).startswith('mps' ): _A = torch.manual_seed(UpperCamelCase__ ) else: _A = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) _A = { 'prompt': 'horse', 'generator': generator, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def __UpperCAmelCase ( self : Dict ) -> str: _A = 'cpu' _A = self.get_dummy_components() _A = self.pipeline_class(**UpperCamelCase__ ) _A = pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) _A = pipe(**self.get_dummy_inputs(UpperCamelCase__ ) ) _A = output.image_embeds _A = pipe( **self.get_dummy_inputs(UpperCamelCase__ ), return_dict=UpperCamelCase__, )[0] _A = image[0, -10:] _A = image_from_tuple[0, -10:] assert image.shape == (1, 32) _A = np.array( [-0.0_532, 1.7_120, 0.3_656, -1.0_852, -0.8_946, -1.1_756, 0.4_348, 0.2_482, 0.5_146, -0.1_156] ) 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 __UpperCAmelCase ( self : Union[str, Any] ) -> Dict: _A = torch_device == 'cpu' _A = True _A = False self._test_inference_batch_single_identical( test_max_difference=UpperCamelCase__, relax_max_difference=UpperCamelCase__, test_mean_pixel_difference=UpperCamelCase__, ) @skip_mps def __UpperCAmelCase ( self : Optional[int] ) -> Union[str, Any]: _A = torch_device == 'cpu' _A = False self._test_attention_slicing_forward_pass( test_max_difference=UpperCamelCase__, test_mean_pixel_difference=UpperCamelCase__, )
107
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def _a ( _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" for attribute in key.split(""".""" ): UpperCAmelCase = getattr(_snake_case , _snake_case ) if weight_type is not None: UpperCAmelCase = getattr(_snake_case , _snake_case ).shape else: UpperCAmelCase = hf_pointer.shape assert hf_shape == value.shape, ( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": UpperCAmelCase = value elif weight_type == "weight_g": UpperCAmelCase = value elif weight_type == "weight_v": UpperCAmelCase = value elif weight_type == "bias": UpperCAmelCase = value else: UpperCAmelCase = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def _a ( _snake_case , _snake_case , _snake_case ): """simple docstring""" UpperCAmelCase = [] UpperCAmelCase = fairseq_model.state_dict() UpperCAmelCase = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): UpperCAmelCase = False if "conv_layers" in name: load_conv_layer( _snake_case , _snake_case , _snake_case , _snake_case , hf_model.config.feat_extract_norm == """group""" , ) UpperCAmelCase = True else: for key, mapped_key in MAPPING.items(): UpperCAmelCase = """hubert.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key if key in name or (key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0] and not is_finetuned): UpperCAmelCase = True if "*" in mapped_key: UpperCAmelCase = name.split(_snake_case )[0].split(""".""" )[-2] UpperCAmelCase = mapped_key.replace("""*""" , _snake_case ) if "weight_g" in name: UpperCAmelCase = """weight_g""" elif "weight_v" in name: UpperCAmelCase = """weight_v""" elif "weight" in name: UpperCAmelCase = """weight""" elif "bias" in name: UpperCAmelCase = """bias""" else: UpperCAmelCase = None set_recursively(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) continue if not is_used: unused_weights.append(_snake_case ) logger.warning(F'''Unused weights: {unused_weights}''' ) def _a ( _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" UpperCAmelCase = full_name.split("""conv_layers.""" )[-1] UpperCAmelCase = name.split(""".""" ) UpperCAmelCase = int(items[0] ) UpperCAmelCase = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) UpperCAmelCase = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) UpperCAmelCase = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) UpperCAmelCase = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) UpperCAmelCase = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(_snake_case ) @torch.no_grad() def _a ( _snake_case , _snake_case , _snake_case=None , _snake_case=None , _snake_case=True ): """simple docstring""" if config_path is not None: UpperCAmelCase = HubertConfig.from_pretrained(_snake_case ) else: UpperCAmelCase = HubertConfig() if is_finetuned: if dict_path: UpperCAmelCase = Dictionary.load(_snake_case ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCAmelCase = target_dict.pad_index UpperCAmelCase = target_dict.bos_index UpperCAmelCase = target_dict.eos_index UpperCAmelCase = len(target_dict.symbols ) UpperCAmelCase = os.path.join(_snake_case , """vocab.json""" ) if not os.path.isdir(_snake_case ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(_snake_case ) ) return os.makedirs(_snake_case , exist_ok=_snake_case ) with open(_snake_case , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(target_dict.indices , _snake_case ) UpperCAmelCase = WavaVecaCTCTokenizer( _snake_case , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=_snake_case , ) UpperCAmelCase = True if config.feat_extract_norm == """layer""" else False UpperCAmelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=_snake_case , return_attention_mask=_snake_case , ) UpperCAmelCase = WavaVecaProcessor(feature_extractor=_snake_case , tokenizer=_snake_case ) processor.save_pretrained(_snake_case ) UpperCAmelCase = HubertForCTC(_snake_case ) else: UpperCAmelCase = HubertModel(_snake_case ) if is_finetuned: UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) UpperCAmelCase = model[0].eval() recursively_load_weights(_snake_case , _snake_case , _snake_case ) hf_wavavec.save_pretrained(_snake_case ) if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) _UpperCamelCase = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
341
0
'''simple docstring''' def lowercase_ ( lowercase__ , lowercase__ ) ->str: _snake_case: list[list[str]] = [[] for _ in range(lowercase__ )] _snake_case: Dict = key - 1 if key <= 0: raise ValueError('Height of grid can\'t be 0 or negative' ) if key == 1 or len(lowercase__ ) <= key: return input_string for position, character in enumerate(lowercase__ ): _snake_case: int = position % (lowest * 2) # puts it in bounds _snake_case: Union[str, Any] = min(lowercase__ , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(lowercase__ ) _snake_case: int = [''.join(lowercase__ ) for row in temp_grid] _snake_case: List[Any] = ''.join(lowercase__ ) return output_string def lowercase_ ( lowercase__ , lowercase__ ) ->str: _snake_case: Union[str, Any] = [] _snake_case: Tuple = key - 1 if key <= 0: raise ValueError('Height of grid can\'t be 0 or negative' ) if key == 1: return input_string _snake_case: list[list[str]] = [[] for _ in range(lowercase__ )] # generates template for position in range(len(lowercase__ ) ): _snake_case: str = position % (lowest * 2) # puts it in bounds _snake_case: Optional[Any] = min(lowercase__ , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append('*' ) _snake_case: Any = 0 for row in temp_grid: # fills in the characters _snake_case: Dict = input_string[counter : counter + len(lowercase__ )] grid.append(list(lowercase__ ) ) counter += len(lowercase__ ) _snake_case: Optional[Any] = '' # reads as zigzag for position in range(len(lowercase__ ) ): _snake_case: Any = position % (lowest * 2) # puts it in bounds _snake_case: str = min(lowercase__ , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def lowercase_ ( lowercase__ ) ->dict[int, str]: _snake_case: Dict = {} for key_guess in range(1 , len(lowercase__ ) ): # tries every key _snake_case: Optional[Any] = decrypt(lowercase__ , lowercase__ ) return results if __name__ == "__main__": import doctest doctest.testmod()
721
'''simple docstring''' from sklearn.metrics import matthews_corrcoef import datasets A : Dict = '\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction. The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n' A : int = '\nArgs:\n predictions (list of int): Predicted labels, as returned by a model.\n references (list of int): Ground truth labels.\n sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n Example 1, a basic example with only predictions and references as inputs:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.54\n\n Example 2, the same example as above, but also including sample weights:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 3, 1, 1, 1, 2])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.1\n\n Example 3, the same example as above, but with sample weights that cause a negative correlation:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 1, 0, 0, 0, 1])\n >>> print(round(results[\'matthews_correlation\'], 2))\n -0.25\n' A : Dict = '\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase ( datasets.Metric ): def SCREAMING_SNAKE_CASE_ ( self : List[Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=[ 'https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html' ] , ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , __snake_case : int , __snake_case : List[Any] , __snake_case : Union[str, Any]=None ): '''simple docstring''' return { "matthews_correlation": float(matthews_corrcoef(__snake_case , __snake_case , sample_weight=__snake_case ) ), }
273
0