code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" from typing import Any import numpy as np def lowercase__ ( lowercase_ ) -> Dict: """simple docstring""" return np.array_equal(lowercase__ ,matrix.conjugate().T ) def lowercase__ ( lowercase_ ,lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : Tuple = v.conjugate().T _UpperCamelCase : Optional[Any] = v_star.dot(lowercase__ ) assert isinstance(lowercase__ ,np.ndarray ) return (v_star_dot.dot(lowercase__ )) / (v_star.dot(lowercase__ )) def lowercase__ ( ) -> Tuple: """simple docstring""" _UpperCamelCase : int = np.array([[2, 2 + 1J, 4], [2 - 1J, 3, 1J], [4, -1J, 1]] ) _UpperCamelCase : Any = np.array([[1], [2], [3]] ) assert is_hermitian(lowercase__ ), F'''{a} is not hermitian.''' print(rayleigh_quotient(lowercase__ ,lowercase__ ) ) _UpperCamelCase : str = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(lowercase__ ), F'''{a} is not hermitian.''' assert rayleigh_quotient(lowercase__ ,lowercase__ ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
719
"""simple docstring""" import argparse import collections import os import re 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/check_table.py lowerCamelCase__ = "src/transformers" lowerCamelCase__ = "docs/source/en" lowerCamelCase__ = "." def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> List[str]: """simple docstring""" with open(lowercase_ ,"r" ,encoding="utf-8" ,newline="\n" ) as f: _UpperCamelCase : Union[str, Any] = f.readlines() # Find the start prompt. _UpperCamelCase : Dict = 0 while not lines[start_index].startswith(lowercase_ ): start_index += 1 start_index += 1 _UpperCamelCase : Optional[int] = start_index while not lines[end_index].startswith(lowercase_ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | lowerCamelCase__ = "Model|Encoder|Decoder|ForConditionalGeneration" # 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)") # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase__ = direct_transformers_import(TRANSFORMERS_PATH) def lowercase__ ( lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Tuple = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)" ,lowercase_ ) return [m.group(0 ) for m in matches] def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : str = 2 if text == "✅" or text == "❌" else len(lowercase_ ) _UpperCamelCase : Union[str, Any] = (width - text_length) // 2 _UpperCamelCase : Dict = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def lowercase__ ( ) -> str: """simple docstring""" _UpperCamelCase : Optional[Any] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _UpperCamelCase : str = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } _UpperCamelCase : Dict = {name: config.replace("Config" ,"" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. _UpperCamelCase : int = collections.defaultdict(lowercase_ ) _UpperCamelCase : Dict = collections.defaultdict(lowercase_ ) _UpperCamelCase : Dict = collections.defaultdict(lowercase_ ) _UpperCamelCase : int = collections.defaultdict(lowercase_ ) _UpperCamelCase : str = collections.defaultdict(lowercase_ ) # Let's lookup through all transformers object (once). for attr_name in dir(lowercase_ ): _UpperCamelCase : List[str] = None if attr_name.endswith("Tokenizer" ): _UpperCamelCase : Tuple = slow_tokenizers _UpperCamelCase : Any = attr_name[:-9] elif attr_name.endswith("TokenizerFast" ): _UpperCamelCase : Optional[Any] = fast_tokenizers _UpperCamelCase : List[str] = attr_name[:-13] elif _re_tf_models.match(lowercase_ ) is not None: _UpperCamelCase : List[Any] = tf_models _UpperCamelCase : Dict = _re_tf_models.match(lowercase_ ).groups()[0] elif _re_flax_models.match(lowercase_ ) is not None: _UpperCamelCase : Dict = flax_models _UpperCamelCase : Union[str, Any] = _re_flax_models.match(lowercase_ ).groups()[0] elif _re_pt_models.match(lowercase_ ) is not None: _UpperCamelCase : Optional[int] = pt_models _UpperCamelCase : Any = _re_pt_models.match(lowercase_ ).groups()[0] if lookup_dict is not None: while len(lowercase_ ) > 0: if attr_name in model_name_to_prefix.values(): _UpperCamelCase : Dict = True break # Try again after removing the last word in the name _UpperCamelCase : List[str] = "".join(camel_case_split(lowercase_ )[:-1] ) # Let's build that table! _UpperCamelCase : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) _UpperCamelCase : List[str] = ["Model", "Tokenizer slow", "Tokenizer fast", "PyTorch support", "TensorFlow support", "Flax Support"] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). _UpperCamelCase : Union[str, Any] = [len(lowercase_ ) + 2 for c in columns] _UpperCamelCase : Any = max([len(lowercase_ ) for name in model_names] ) + 2 # Build the table per se _UpperCamelCase : Tuple = "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for c, w in zip(lowercase_ ,lowercase_ )] ) + "|\n" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths] ) + "|\n" _UpperCamelCase : Union[str, Any] = {True: "✅", False: "❌"} for name in model_names: _UpperCamelCase : Optional[int] = model_name_to_prefix[name] _UpperCamelCase : Tuple = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for l, w in zip(lowercase_ ,lowercase_ )] ) + "|\n" return table def lowercase__ ( lowercase_=False ) -> List[Any]: """simple docstring""" _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : str = _find_text_in_file( filename=os.path.join(lowercase_ ,"index.md" ) ,start_prompt="<!--This table is updated automatically from the auto modules" ,end_prompt="<!-- End table-->" ,) _UpperCamelCase : Any = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(lowercase_ ,"index.md" ) ,"w" ,encoding="utf-8" ,newline="\n" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( "The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this." ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") lowerCamelCase__ = parser.parse_args() check_model_table(args.fix_and_overwrite)
51
0
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __SCREAMING_SNAKE_CASE ( __lowercase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[str] = AudioLDMPipeline SCREAMING_SNAKE_CASE__ :int = TEXT_TO_AUDIO_PARAMS SCREAMING_SNAKE_CASE__ :Dict = TEXT_TO_AUDIO_BATCH_PARAMS SCREAMING_SNAKE_CASE__ :Optional[Any] = frozenset( [ "num_inference_steps", "num_waveforms_per_prompt", "generator", "latents", "output_type", "return_dict", "callback", "callback_steps", ] ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]: torch.manual_seed(0 ) _UpperCamelCase : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=(32, 64) , class_embed_type="simple_projection" , projection_class_embeddings_input_dim=32 , class_embeddings_concat=__a , ) _UpperCamelCase : List[str] = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=__a , set_alpha_to_one=__a , ) torch.manual_seed(0 ) _UpperCamelCase : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) _UpperCamelCase : List[Any] = ClapTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , projection_dim=32 , ) _UpperCamelCase : Union[str, Any] = ClapTextModelWithProjection(__a ) _UpperCamelCase : List[Any] = RobertaTokenizer.from_pretrained("hf-internal-testing/tiny-random-roberta" , model_max_length=77 ) _UpperCamelCase : List[Any] = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_6000 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=__a , ) _UpperCamelCase : Optional[Any] = SpeechTaHifiGan(__a ) _UpperCamelCase : int = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """vocoder""": vocoder, } return components def __SCREAMING_SNAKE_CASE ( self : Any , __a : Optional[Any] , __a : List[str]=0 ) -> Union[str, Any]: if str(__a ).startswith("mps" ): _UpperCamelCase : List[str] = torch.manual_seed(__a ) else: _UpperCamelCase : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) _UpperCamelCase : Dict = { """prompt""": """A hammer hitting a wooden surface""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, } return inputs def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: _UpperCamelCase : List[Any] = """cpu""" # ensure determinism for the device-dependent torch.Generator _UpperCamelCase : Optional[int] = self.get_dummy_components() _UpperCamelCase : List[str] = AudioLDMPipeline(**__a ) _UpperCamelCase : Tuple = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase : Optional[int] = self.get_dummy_inputs(__a ) _UpperCamelCase : List[Any] = audioldm_pipe(**__a ) _UpperCamelCase : Optional[Any] = output.audios[0] assert audio.ndim == 1 assert len(__a ) == 256 _UpperCamelCase : str = audio[:10] _UpperCamelCase : Any = np.array( [-0.00_50, 0.00_50, -0.00_60, 0.00_33, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_33] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: _UpperCamelCase : str = self.get_dummy_components() _UpperCamelCase : int = AudioLDMPipeline(**__a ) _UpperCamelCase : Tuple = audioldm_pipe.to(__a ) _UpperCamelCase : int = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase : int = self.get_dummy_inputs(__a ) _UpperCamelCase : Optional[int] = 3 * [inputs["""prompt"""]] # forward _UpperCamelCase : Union[str, Any] = audioldm_pipe(**__a ) _UpperCamelCase : List[Any] = output.audios[0] _UpperCamelCase : Optional[int] = self.get_dummy_inputs(__a ) _UpperCamelCase : Tuple = 3 * [inputs.pop("prompt" )] _UpperCamelCase : Dict = audioldm_pipe.tokenizer( __a , padding="max_length" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=__a , return_tensors="pt" , ) _UpperCamelCase : List[Any] = text_inputs["""input_ids"""].to(__a ) _UpperCamelCase : List[str] = audioldm_pipe.text_encoder( __a , ) _UpperCamelCase : Any = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state _UpperCamelCase : List[str] = F.normalize(__a , dim=-1 ) _UpperCamelCase : str = prompt_embeds # forward _UpperCamelCase : Dict = audioldm_pipe(**__a ) _UpperCamelCase : List[Any] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Union[str, Any]: _UpperCamelCase : str = self.get_dummy_components() _UpperCamelCase : List[Any] = AudioLDMPipeline(**__a ) _UpperCamelCase : List[Any] = audioldm_pipe.to(__a ) _UpperCamelCase : Tuple = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase : Optional[int] = self.get_dummy_inputs(__a ) _UpperCamelCase : Optional[Any] = 3 * ["""this is a negative prompt"""] _UpperCamelCase : int = negative_prompt _UpperCamelCase : Optional[int] = 3 * [inputs["""prompt"""]] # forward _UpperCamelCase : Any = audioldm_pipe(**__a ) _UpperCamelCase : Optional[Any] = output.audios[0] _UpperCamelCase : Any = self.get_dummy_inputs(__a ) _UpperCamelCase : List[Any] = 3 * [inputs.pop("prompt" )] _UpperCamelCase : int = [] for p in [prompt, negative_prompt]: _UpperCamelCase : Any = audioldm_pipe.tokenizer( __a , padding="max_length" , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=__a , return_tensors="pt" , ) _UpperCamelCase : Dict = text_inputs["""input_ids"""].to(__a ) _UpperCamelCase : List[Any] = audioldm_pipe.text_encoder( __a , ) _UpperCamelCase : Union[str, Any] = text_embeds.text_embeds # additional L_2 normalization over each hidden-state _UpperCamelCase : str = F.normalize(__a , dim=-1 ) embeds.append(__a ) _UpperCamelCase : Union[str, Any] = embeds # forward _UpperCamelCase : List[str] = audioldm_pipe(**__a ) _UpperCamelCase : List[str] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1e-2 def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: _UpperCamelCase : int = """cpu""" # ensure determinism for the device-dependent torch.Generator _UpperCamelCase : Dict = self.get_dummy_components() _UpperCamelCase : List[Any] = PNDMScheduler(skip_prk_steps=__a ) _UpperCamelCase : Optional[Any] = AudioLDMPipeline(**__a ) _UpperCamelCase : int = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase : List[Any] = self.get_dummy_inputs(__a ) _UpperCamelCase : Any = """egg cracking""" _UpperCamelCase : str = audioldm_pipe(**__a , negative_prompt=__a ) _UpperCamelCase : Optional[Any] = output.audios[0] assert audio.ndim == 1 assert len(__a ) == 256 _UpperCamelCase : int = audio[:10] _UpperCamelCase : List[Any] = np.array( [-0.00_51, 0.00_50, -0.00_60, 0.00_34, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_32] ) assert np.abs(audio_slice - expected_slice ).max() < 1e-2 def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: _UpperCamelCase : int = """cpu""" # ensure determinism for the device-dependent torch.Generator _UpperCamelCase : Tuple = self.get_dummy_components() _UpperCamelCase : Dict = PNDMScheduler(skip_prk_steps=__a ) _UpperCamelCase : Any = AudioLDMPipeline(**__a ) _UpperCamelCase : List[Any] = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase : Optional[Any] = """A hammer hitting a wooden surface""" # test num_waveforms_per_prompt=1 (default) _UpperCamelCase : Dict = audioldm_pipe(__a , num_inference_steps=2 ).audios assert audios.shape == (1, 256) # test num_waveforms_per_prompt=1 (default) for batch of prompts _UpperCamelCase : List[Any] = 2 _UpperCamelCase : Tuple = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 256) # test num_waveforms_per_prompt for single prompt _UpperCamelCase : Optional[int] = 2 _UpperCamelCase : Dict = audioldm_pipe(__a , num_inference_steps=2 , num_waveforms_per_prompt=__a ).audios assert audios.shape == (num_waveforms_per_prompt, 256) # test num_waveforms_per_prompt for batch of prompts _UpperCamelCase : str = 2 _UpperCamelCase : Union[str, Any] = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=__a ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 256) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: _UpperCamelCase : Any = """cpu""" # ensure determinism for the device-dependent torch.Generator _UpperCamelCase : str = self.get_dummy_components() _UpperCamelCase : str = AudioLDMPipeline(**__a ) _UpperCamelCase : Any = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase : List[Any] = audioldm_pipe.vocoder.config.sampling_rate _UpperCamelCase : Union[str, Any] = self.get_dummy_inputs(__a ) _UpperCamelCase : str = audioldm_pipe(audio_length_in_s=0.0_16 , **__a ) _UpperCamelCase : int = output.audios[0] assert audio.ndim == 1 assert len(__a ) / vocoder_sampling_rate == 0.0_16 _UpperCamelCase : int = audioldm_pipe(audio_length_in_s=0.0_32 , **__a ) _UpperCamelCase : Any = output.audios[0] assert audio.ndim == 1 assert len(__a ) / vocoder_sampling_rate == 0.0_32 def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: _UpperCamelCase : Tuple = self.get_dummy_components() _UpperCamelCase : int = AudioLDMPipeline(**__a ) _UpperCamelCase : List[str] = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase : int = ["""hey"""] _UpperCamelCase : str = audioldm_pipe(__a , num_inference_steps=1 ) _UpperCamelCase : Optional[Any] = output.audios.shape assert audio_shape == (1, 256) _UpperCamelCase : Optional[int] = audioldm_pipe.vocoder.config config.model_in_dim *= 2 _UpperCamelCase : Optional[Any] = SpeechTaHifiGan(__a ).to(__a ) _UpperCamelCase : Dict = audioldm_pipe(__a , num_inference_steps=1 ) _UpperCamelCase : List[str] = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 256) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__a ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: self._test_inference_batch_single_identical(test_mean_pixel_difference=__a ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__a ) @slow class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : str , __a : List[str]="cpu" , __a : Optional[int]=torch.floataa , __a : Optional[Any]=0 ) -> List[Any]: _UpperCamelCase : Tuple = torch.Generator(device=__a ).manual_seed(__a ) _UpperCamelCase : Optional[Any] = np.random.RandomState(__a ).standard_normal((1, 8, 128, 16) ) _UpperCamelCase : str = torch.from_numpy(__a ).to(device=__a , dtype=__a ) _UpperCamelCase : Optional[int] = { """prompt""": """A hammer hitting a wooden surface""", """latents""": latents, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 2.5, } return inputs def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: _UpperCamelCase : Dict = AudioLDMPipeline.from_pretrained("cvssp/audioldm" ) _UpperCamelCase : Optional[Any] = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase : int = self.get_inputs(__a ) _UpperCamelCase : Optional[Any] = 25 _UpperCamelCase : Tuple = audioldm_pipe(**__a ).audios[0] assert audio.ndim == 1 assert len(__a ) == 8_1920 _UpperCamelCase : Any = audio[7_7230:7_7240] _UpperCamelCase : Any = np.array( [-0.48_84, -0.46_07, 0.00_23, 0.50_07, 0.58_96, 0.51_51, 0.38_13, -0.02_08, -0.36_87, -0.43_15] ) _UpperCamelCase : int = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1e-2 def __SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: _UpperCamelCase : Dict = AudioLDMPipeline.from_pretrained("cvssp/audioldm" ) _UpperCamelCase : str = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) _UpperCamelCase : Optional[int] = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase : Tuple = self.get_inputs(__a ) _UpperCamelCase : int = audioldm_pipe(**__a ).audios[0] assert audio.ndim == 1 assert len(__a ) == 8_1920 _UpperCamelCase : List[str] = audio[2_7780:2_7790] _UpperCamelCase : Tuple = np.array([-0.21_31, -0.08_73, -0.01_24, -0.01_89, 0.05_69, 0.13_73, 0.18_83, 0.28_86, 0.32_97, 0.22_12] ) _UpperCamelCase : int = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3e-2
720
"""simple docstring""" from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. lowerCamelCase__ = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. lowerCamelCase__ = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. lowerCamelCase__ = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def lowercase__ ( lowercase_ ,lowercase_ ) -> tuple[str, float]: """simple docstring""" _UpperCamelCase : str = len([g for position, g in enumerate(lowercase_ ) if g == main_target[position]] ) return (item, float(lowercase_ )) def lowercase__ ( lowercase_ ,lowercase_ ) -> tuple[str, str]: """simple docstring""" _UpperCamelCase : Tuple = random.randint(0 ,len(lowercase_ ) - 1 ) _UpperCamelCase : Dict = parent_a[:random_slice] + parent_a[random_slice:] _UpperCamelCase : Tuple = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def lowercase__ ( lowercase_ ,lowercase_ ) -> str: """simple docstring""" _UpperCamelCase : int = list(lowercase_ ) if random.uniform(0 ,1 ) < MUTATION_PROBABILITY: _UpperCamelCase : int = random.choice(lowercase_ ) return "".join(lowercase_ ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,) -> list[str]: """simple docstring""" _UpperCamelCase : Optional[Any] = [] # Generate more children proportionally to the fitness score. _UpperCamelCase : List[str] = int(parent_a[1] * 100 ) + 1 _UpperCamelCase : Union[str, Any] = 10 if child_n >= 10 else child_n for _ in range(lowercase_ ): _UpperCamelCase : Dict = population_score[random.randint(0 ,lowercase_ )][0] _UpperCamelCase, _UpperCamelCase : Dict = crossover(parent_a[0] ,lowercase_ ) # Append new string to the population list. pop.append(mutate(lowercase_ ,lowercase_ ) ) pop.append(mutate(lowercase_ ,lowercase_ ) ) return pop def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ = True ) -> tuple[int, int, str]: """simple docstring""" if N_POPULATION < N_SELECTED: _UpperCamelCase : List[str] = F'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(lowercase_ ) # Verify that the target contains no genes besides the ones inside genes variable. _UpperCamelCase : int = sorted({c for c in target if c not in genes} ) if not_in_genes_list: _UpperCamelCase : int = F'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(lowercase_ ) # Generate random starting population. _UpperCamelCase : Union[str, Any] = [] for _ in range(lowercase_ ): population.append("".join([random.choice(lowercase_ ) for i in range(len(lowercase_ ) )] ) ) # Just some logs to know what the algorithms is doing. _UpperCamelCase, _UpperCamelCase : str = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowercase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. _UpperCamelCase : int = [evaluate(lowercase_ ,lowercase_ ) for item in population] # Check if there is a matching evolution. _UpperCamelCase : Optional[Any] = sorted(lowercase_ ,key=lambda lowercase_ : x[1] ,reverse=lowercase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'''\nGeneration: {generation}''' F'''\nTotal Population:{total_population}''' F'''\nBest score: {population_score[0][1]}''' F'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. _UpperCamelCase : str = population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowercase_ ) # Normalize population score to be between 0 and 1. _UpperCamelCase : str = [ (item, score / len(lowercase_ )) for item, score in population_score ] # This is selection for i in range(lowercase_ ): population.extend(select(population_score[int(lowercase_ )] ,lowercase_ ,lowercase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowercase_ ) > N_POPULATION: break if __name__ == "__main__": lowerCamelCase__ = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) lowerCamelCase__ = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = basic(target_str, genes_list) print( f"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}""" )
51
0
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING lowerCamelCase__ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :int = "upernet" def __init__( self : Optional[Any] , __a : Optional[Any]=None , __a : List[str]=512 , __a : List[Any]=0.02 , __a : Any=[1, 2, 3, 6] , __a : int=True , __a : Optional[Any]=0.4 , __a : List[Any]=384 , __a : Optional[Any]=256 , __a : Dict=1 , __a : Optional[int]=False , __a : List[str]=255 , **__a : Optional[Any] , ) -> Optional[int]: super().__init__(**UpperCAmelCase__ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) _UpperCamelCase : int = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _UpperCamelCase : Union[str, Any] = backbone_config.get("model_type" ) _UpperCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] _UpperCamelCase : int = config_class.from_dict(UpperCAmelCase__ ) _UpperCamelCase : List[str] = backbone_config _UpperCamelCase : int = hidden_size _UpperCamelCase : Optional[int] = initializer_range _UpperCamelCase : str = pool_scales _UpperCamelCase : List[Any] = use_auxiliary_head _UpperCamelCase : List[str] = auxiliary_loss_weight _UpperCamelCase : Optional[Any] = auxiliary_in_channels _UpperCamelCase : Dict = auxiliary_channels _UpperCamelCase : List[Any] = auxiliary_num_convs _UpperCamelCase : Tuple = auxiliary_concat_input _UpperCamelCase : Optional[int] = loss_ignore_index def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: _UpperCamelCase : Tuple = copy.deepcopy(self.__dict__ ) _UpperCamelCase : Dict = self.backbone_config.to_dict() _UpperCamelCase : int = self.__class__.model_type return output
721
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = ["model.decoder.embed_positions.weights"] def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" if "emb" in name: _UpperCamelCase : List[str] = name.replace("emb" ,"model.decoder.embed_tokens" ) if "transformer" in name: _UpperCamelCase : Optional[int] = name.replace("transformer" ,"model.decoder" ) if "cross_attention" in name: _UpperCamelCase : Optional[int] = name.replace("cross_attention" ,"encoder_attn" ) if "linear1" in name: _UpperCamelCase : Optional[Any] = name.replace("linear1" ,"fc1" ) if "linear2" in name: _UpperCamelCase : Union[str, Any] = name.replace("linear2" ,"fc2" ) if "norm1" in name: _UpperCamelCase : Optional[Any] = name.replace("norm1" ,"self_attn_layer_norm" ) if "norm_cross" in name: _UpperCamelCase : Dict = name.replace("norm_cross" ,"encoder_attn_layer_norm" ) if "norm2" in name: _UpperCamelCase : Union[str, Any] = name.replace("norm2" ,"final_layer_norm" ) if "out_norm" in name: _UpperCamelCase : Union[str, Any] = name.replace("out_norm" ,"model.decoder.layer_norm" ) if "linears" in name: _UpperCamelCase : List[str] = name.replace("linears" ,"lm_heads" ) if "condition_provider.conditioners.description.output_proj" in name: _UpperCamelCase : Any = name.replace("condition_provider.conditioners.description.output_proj" ,"enc_to_dec_proj" ) return name def lowercase__ ( lowercase_ ,lowercase_ ) -> Tuple[Dict, Dict]: """simple docstring""" _UpperCamelCase : str = list(state_dict.keys() ) _UpperCamelCase : Optional[Any] = {} for key in keys: _UpperCamelCase : Optional[int] = state_dict.pop(lowercase_ ) _UpperCamelCase : List[Any] = rename_keys(lowercase_ ) if "in_proj_weight" in key: # split fused qkv proj _UpperCamelCase : Tuple = val[:hidden_size, :] _UpperCamelCase : Optional[Any] = val[hidden_size : 2 * hidden_size, :] _UpperCamelCase : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _UpperCamelCase : Optional[Any] = val else: _UpperCamelCase : List[str] = val return state_dict, enc_dec_proj_state_dict def lowercase__ ( lowercase_ ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values _UpperCamelCase : List[Any] = 1_024 _UpperCamelCase : List[str] = 24 _UpperCamelCase : Any = 16 elif checkpoint == "medium": _UpperCamelCase : Tuple = 1_536 _UpperCamelCase : Dict = 48 _UpperCamelCase : Tuple = 24 elif checkpoint == "large": _UpperCamelCase : int = 2_048 _UpperCamelCase : Optional[int] = 48 _UpperCamelCase : Dict = 32 else: raise ValueError(F'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' ) _UpperCamelCase : str = MusicgenDecoderConfig( hidden_size=lowercase_ ,ffn_dim=hidden_size * 4 ,num_hidden_layers=lowercase_ ,num_attention_heads=lowercase_ ,) return config @torch.no_grad() def lowercase__ ( lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_="cpu" ) -> List[str]: """simple docstring""" _UpperCamelCase : str = MusicGen.get_pretrained(lowercase_ ,device=lowercase_ ) _UpperCamelCase : Union[str, Any] = decoder_config_from_checkpoint(lowercase_ ) _UpperCamelCase : Optional[int] = fairseq_model.lm.state_dict() _UpperCamelCase, _UpperCamelCase : Optional[Any] = rename_state_dict( lowercase_ ,hidden_size=decoder_config.hidden_size ) _UpperCamelCase : Tuple = TaEncoderModel.from_pretrained("t5-base" ) _UpperCamelCase : Union[str, Any] = EncodecModel.from_pretrained("facebook/encodec_32khz" ) _UpperCamelCase : str = MusicgenForCausalLM(lowercase_ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _UpperCamelCase, _UpperCamelCase : str = decoder.load_state_dict(lowercase_ ,strict=lowercase_ ) for key in missing_keys.copy(): if key.startswith(("text_encoder", "audio_encoder") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(lowercase_ ) if len(lowercase_ ) > 0: raise ValueError(F'''Missing key(s) in state_dict: {missing_keys}''' ) if len(lowercase_ ) > 0: raise ValueError(F'''Unexpected key(s) in state_dict: {unexpected_keys}''' ) # init the composite model _UpperCamelCase : str = MusicgenForConditionalGeneration(text_encoder=lowercase_ ,audio_encoder=lowercase_ ,decoder=lowercase_ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(lowercase_ ) # check we can do a forward pass _UpperCamelCase : List[str] = torch.arange(0 ,8 ,dtype=torch.long ).reshape(2 ,-1 ) _UpperCamelCase : Dict = input_ids.reshape(2 * 4 ,-1 ) with torch.no_grad(): _UpperCamelCase : Tuple = model(input_ids=lowercase_ ,decoder_input_ids=lowercase_ ).logits if logits.shape != (8, 1, 2_048): raise ValueError("Incorrect shape for logits" ) # now construct the processor _UpperCamelCase : int = AutoTokenizer.from_pretrained("t5-base" ) _UpperCamelCase : str = AutoFeatureExtractor.from_pretrained("facebook/encodec_32khz" ,padding_side="left" ) _UpperCamelCase : Optional[int] = MusicgenProcessor(feature_extractor=lowercase_ ,tokenizer=lowercase_ ) # set the appropriate bos/pad token ids _UpperCamelCase : str = 2_048 _UpperCamelCase : str = 2_048 # set other default generation config params _UpperCamelCase : Optional[Any] = int(30 * audio_encoder.config.frame_rate ) _UpperCamelCase : List[str] = True _UpperCamelCase : int = 3.0 if pytorch_dump_folder is not None: Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) logger.info(F'''Saving model {checkpoint} to {pytorch_dump_folder}''' ) model.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) if repo_id: logger.info(F'''Pushing model {checkpoint} to {repo_id}''' ) model.push_to_hub(lowercase_ ) processor.push_to_hub(lowercase_ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) lowerCamelCase__ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
51
0
"""simple docstring""" from argparse import ArgumentParser from .add_new_model import AddNewModelCommand from .add_new_model_like import AddNewModelLikeCommand from .convert import ConvertCommand from .download import DownloadCommand from .env import EnvironmentCommand from .lfs import LfsCommands from .pt_to_tf import PTtoTFCommand from .run import RunCommand from .serving import ServeCommand from .user import UserCommands def lowercase__ ( ) -> List[str]: """simple docstring""" _UpperCamelCase : Union[str, Any] = ArgumentParser("Transformers CLI tool" ,usage="transformers-cli <command> [<args>]" ) _UpperCamelCase : int = parser.add_subparsers(help="transformers-cli command helpers" ) # Register commands ConvertCommand.register_subcommand(lowercase_ ) DownloadCommand.register_subcommand(lowercase_ ) EnvironmentCommand.register_subcommand(lowercase_ ) RunCommand.register_subcommand(lowercase_ ) ServeCommand.register_subcommand(lowercase_ ) UserCommands.register_subcommand(lowercase_ ) AddNewModelCommand.register_subcommand(lowercase_ ) AddNewModelLikeCommand.register_subcommand(lowercase_ ) LfsCommands.register_subcommand(lowercase_ ) PTtoTFCommand.register_subcommand(lowercase_ ) # Let's go _UpperCamelCase : List[Any] = parser.parse_args() if not hasattr(lowercase_ ,"func" ): parser.print_help() exit(1 ) # Run _UpperCamelCase : List[str] = args.func(lowercase_ ) service.run() if __name__ == "__main__": main()
700
"""simple docstring""" from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowerCamelCase__ = input("Enter image url: ").strip() print(f"""Downloading image from {url} ...""") lowerCamelCase__ = BeautifulSoup(requests.get(url).content, "html.parser") # The image URL is in the content field of the first meta tag with property og:image lowerCamelCase__ = soup.find("meta", {"property": "og:image"})["content"] lowerCamelCase__ = requests.get(image_url).content lowerCamelCase__ = f"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, "wb") as fp: fp.write(image_data) print(f"""Done. Image saved to disk as {file_name}.""")
51
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, 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 numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , __a : Optional[int] , ) -> str: _UpperCamelCase : List[str] = parent _UpperCamelCase : List[str] = 13 _UpperCamelCase : List[Any] = 7 _UpperCamelCase : List[Any] = True _UpperCamelCase : List[Any] = True _UpperCamelCase : List[Any] = True _UpperCamelCase : int = True _UpperCamelCase : Optional[Any] = True _UpperCamelCase : Dict = False _UpperCamelCase : List[str] = False _UpperCamelCase : Dict = False _UpperCamelCase : Dict = 2 _UpperCamelCase : Any = 99 _UpperCamelCase : Optional[Any] = 0 _UpperCamelCase : Union[str, Any] = 32 _UpperCamelCase : int = 2 _UpperCamelCase : List[str] = 4 _UpperCamelCase : Dict = 0.1 _UpperCamelCase : Any = 0.1 _UpperCamelCase : Tuple = 512 _UpperCamelCase : Optional[Any] = 16 _UpperCamelCase : Union[str, Any] = 2 _UpperCamelCase : str = 0.02 _UpperCamelCase : List[Any] = 3 _UpperCamelCase : Union[str, Any] = 4 _UpperCamelCase : Optional[int] = "last" _UpperCamelCase : int = True _UpperCamelCase : Optional[Any] = None _UpperCamelCase : Optional[int] = 0 def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[Any]: _UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase : str = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa ) _UpperCamelCase : List[str] = None if self.use_input_lengths: _UpperCamelCase : List[Any] = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length _UpperCamelCase : str = None if self.use_token_type_ids: _UpperCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) _UpperCamelCase : int = None _UpperCamelCase : List[Any] = None _UpperCamelCase : Tuple = None if self.use_labels: _UpperCamelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCamelCase : Tuple = ids_tensor([self.batch_size] , 2 , dtype=tf.floataa ) _UpperCamelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) _UpperCamelCase : Dict = FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def __SCREAMING_SNAKE_CASE ( self : int , __a : str , __a : Tuple , __a : Optional[Any] , __a : Dict , __a : Union[str, Any] , __a : Any , __a : Union[str, Any] , __a : int , __a : Optional[int] , ) -> Optional[int]: _UpperCamelCase : Tuple = TFFlaubertModel(config=__a ) _UpperCamelCase : Dict = {"input_ids": input_ids, "lengths": input_lengths, "langs": token_type_ids} _UpperCamelCase : Optional[int] = model(__a ) _UpperCamelCase : Optional[Any] = [input_ids, input_mask] _UpperCamelCase : str = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE ( self : str , __a : str , __a : Tuple , __a : List[str] , __a : List[Any] , __a : Optional[Any] , __a : Dict , __a : Optional[int] , __a : Optional[Any] , __a : Union[str, Any] , ) -> int: _UpperCamelCase : str = TFFlaubertWithLMHeadModel(__a ) _UpperCamelCase : Optional[int] = {"input_ids": input_ids, "lengths": input_lengths, "langs": token_type_ids} _UpperCamelCase : Union[str, Any] = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __SCREAMING_SNAKE_CASE ( self : str , __a : Optional[int] , __a : Tuple , __a : int , __a : Tuple , __a : Optional[Any] , __a : List[str] , __a : List[Any] , __a : Optional[int] , __a : int , ) -> List[str]: _UpperCamelCase : Dict = TFFlaubertForQuestionAnsweringSimple(__a ) _UpperCamelCase : int = {"input_ids": input_ids, "lengths": input_lengths} _UpperCamelCase : List[str] = model(__a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : int , __a : Tuple , __a : List[Any] , __a : List[str] , __a : str , __a : int , __a : str , __a : Tuple , __a : str , ) -> Dict: _UpperCamelCase : Any = TFFlaubertForSequenceClassification(__a ) _UpperCamelCase : Optional[int] = {"input_ids": input_ids, "lengths": input_lengths} _UpperCamelCase : Union[str, Any] = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : Tuple , __a : Dict , __a : Any , __a : List[str] , __a : Union[str, Any] , __a : int , __a : Optional[Any] , __a : Dict , __a : Tuple , ) -> Optional[Any]: _UpperCamelCase : Dict = self.num_labels _UpperCamelCase : int = TFFlaubertForTokenClassification(config=__a ) _UpperCamelCase : Optional[Any] = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _UpperCamelCase : Dict = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : Optional[int] , __a : Optional[Any] , __a : Tuple , __a : Tuple , __a : Any , __a : Union[str, Any] , __a : int , __a : Tuple , __a : str , ) -> List[str]: _UpperCamelCase : int = self.num_choices _UpperCamelCase : str = TFFlaubertForMultipleChoice(config=__a ) _UpperCamelCase : List[str] = tf.tile(tf.expand_dims(__a , 1 ) , (1, self.num_choices, 1) ) _UpperCamelCase : Any = tf.tile(tf.expand_dims(__a , 1 ) , (1, self.num_choices, 1) ) _UpperCamelCase : List[str] = tf.tile(tf.expand_dims(__a , 1 ) , (1, self.num_choices, 1) ) _UpperCamelCase : List[str] = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } _UpperCamelCase : Tuple = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: _UpperCamelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( _UpperCamelCase ), ( _UpperCamelCase ), ( _UpperCamelCase ), ( _UpperCamelCase ), ( _UpperCamelCase ), ( _UpperCamelCase ), ( _UpperCamelCase ), ( _UpperCamelCase ), ( _UpperCamelCase ), ) : int = config_and_inputs _UpperCamelCase : Dict = { "input_ids": input_ids, "token_type_ids": token_type_ids, "langs": token_type_ids, "lengths": input_lengths, } return config, inputs_dict @require_tf class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[Any] = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) SCREAMING_SNAKE_CASE__ :List[str] = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable SCREAMING_SNAKE_CASE__ :List[str] = ( { 'feature-extraction': TFFlaubertModel, 'fill-mask': TFFlaubertWithLMHeadModel, 'question-answering': TFFlaubertForQuestionAnsweringSimple, 'text-classification': TFFlaubertForSequenceClassification, 'token-classification': TFFlaubertForTokenClassification, 'zero-shot': TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ :Optional[Any] = False SCREAMING_SNAKE_CASE__ :Union[str, Any] = False def __SCREAMING_SNAKE_CASE ( self : int , __a : List[str] , __a : Dict , __a : Optional[int] , __a : Union[str, Any] , __a : List[Any] ) -> Optional[Any]: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: _UpperCamelCase : List[Any] = TFFlaubertModelTester(self ) _UpperCamelCase : Any = ConfigTester(self , config_class=__a , emb_dim=37 ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: _UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: _UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__a ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: _UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: _UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__a ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]: _UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*__a ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: _UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*__a ) @slow def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase : Union[str, Any] = TFFlaubertModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_tf @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def __SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: _UpperCamelCase : int = TFFlaubertModel.from_pretrained("jplu/tf-flaubert-small-cased" ) _UpperCamelCase : Optional[Any] = tf.convert_to_tensor( [[0, 158, 735, 2592, 1424, 6727, 82, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" _UpperCamelCase : Optional[Any] = model(__a )[0] _UpperCamelCase : Optional[int] = tf.TensorShape((1, 8, 512) ) self.assertEqual(output.shape , __a ) # compare the actual values for a slice. _UpperCamelCase : Union[str, Any] = tf.convert_to_tensor( [ [ [-1.8_76_87_73, -1.56_65_55, 0.27_07_24_18], [-1.6_92_00_38, -0.5_87_35_05, 1.9_32_95_99], [-2.9_56_39_85, -1.6_99_38_35, 1.7_97_20_52], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
701
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append(".") def lowercase__ ( lowercase_ ) -> int: """simple docstring""" _UpperCamelCase : Any = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " F'''{test_file} instead.''' ) _UpperCamelCase : str = components[-1] if not test_fn.endswith("py" ): raise ValueError(F'''`test_file` should be a python file. Got {test_fn} instead.''' ) if not test_fn.startswith("test_modeling_" ): raise ValueError( F'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.''' ) _UpperCamelCase : Dict = components[:-1] + [test_fn.replace(".py" ,"" )] _UpperCamelCase : List[str] = ".".join(lowercase_ ) return test_module_path def lowercase__ ( lowercase_ ) -> List[Any]: """simple docstring""" _UpperCamelCase : Optional[Any] = get_module_path(lowercase_ ) _UpperCamelCase : str = importlib.import_module(lowercase_ ) return test_module def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : Union[str, Any] = [] _UpperCamelCase : List[Any] = get_test_module(lowercase_ ) for attr in dir(lowercase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowercase_ ,lowercase_ ) ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Tuple: """simple docstring""" _UpperCamelCase : Optional[Any] = [] _UpperCamelCase : Any = get_test_module(lowercase_ ) for attr in dir(lowercase_ ): _UpperCamelCase : int = getattr(lowercase_ ,lowercase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). _UpperCamelCase : Optional[Any] = getattr(lowercase_ ,"all_model_classes" ,[] ) if len(lowercase_ ) > 0: test_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Dict = get_test_classes(lowercase_ ) _UpperCamelCase : int = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : List[str] = test_class() if hasattr(lowercase_ ,"setUp" ): test.setUp() _UpperCamelCase : Tuple = None if hasattr(lowercase_ ,"model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: _UpperCamelCase : Tuple = test.model_tester.__class__ return model_tester def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : str = get_test_classes(lowercase_ ) _UpperCamelCase : Dict = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ,lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : Any = get_test_classes_for_model(lowercase_ ,lowercase_ ) _UpperCamelCase : List[Any] = [] for test_class in test_classes: _UpperCamelCase : List[Any] = get_model_tester_from_test_class(lowercase_ ) if tester_class is not None: tester_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Any = get_test_classes(lowercase_ ) _UpperCamelCase : Tuple = {test_class: get_model_tester_from_test_class(lowercase_ ) for test_class in test_classes} return test_tester_mapping def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : List[Any] = get_model_classes(lowercase_ ) _UpperCamelCase : Optional[int] = { model_class: get_test_classes_for_model(lowercase_ ,lowercase_ ) for model_class in model_classes } return model_test_mapping def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Optional[Any] = get_model_classes(lowercase_ ) _UpperCamelCase : Tuple = { model_class: get_tester_classes_for_model(lowercase_ ,lowercase_ ) for model_class in model_classes } return model_to_tester_mapping def lowercase__ ( lowercase_ ) -> Optional[int]: """simple docstring""" if isinstance(lowercase_ ,lowercase_ ): return o elif isinstance(lowercase_ ,lowercase_ ): return o.__name__ elif isinstance(lowercase_ ,(list, tuple) ): return [to_json(lowercase_ ) for x in o] elif isinstance(lowercase_ ,lowercase_ ): return {to_json(lowercase_ ): to_json(lowercase_ ) for k, v in o.items()} else: return o
51
0
from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class __SCREAMING_SNAKE_CASE : '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = LEDConfig SCREAMING_SNAKE_CASE__ :int = {} SCREAMING_SNAKE_CASE__ :List[Any] = "gelu" def __init__( self : Optional[Any] , __a : int , __a : Any=13 , __a : Any=7 , __a : str=True , __a : Dict=False , __a : Any=99 , __a : str=32 , __a : Optional[Any]=2 , __a : str=4 , __a : Dict=37 , __a : str=0.1 , __a : List[Any]=0.1 , __a : Union[str, Any]=20 , __a : List[Any]=2 , __a : Tuple=1 , __a : str=0 , __a : Optional[int]=4 , ) -> Optional[Any]: _UpperCamelCase : Dict = parent _UpperCamelCase : Union[str, Any] = batch_size _UpperCamelCase : Any = seq_length _UpperCamelCase : Union[str, Any] = is_training _UpperCamelCase : int = use_labels _UpperCamelCase : List[Any] = vocab_size _UpperCamelCase : str = hidden_size _UpperCamelCase : Optional[int] = num_hidden_layers _UpperCamelCase : Union[str, Any] = num_attention_heads _UpperCamelCase : str = intermediate_size _UpperCamelCase : Optional[Any] = hidden_dropout_prob _UpperCamelCase : Union[str, Any] = attention_probs_dropout_prob _UpperCamelCase : Optional[Any] = max_position_embeddings _UpperCamelCase : int = eos_token_id _UpperCamelCase : List[str] = pad_token_id _UpperCamelCase : List[Any] = bos_token_id _UpperCamelCase : List[Any] = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after _UpperCamelCase : str = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests _UpperCamelCase : str = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: _UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _UpperCamelCase : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _UpperCamelCase : List[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) _UpperCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase : Optional[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) _UpperCamelCase : List[str] = prepare_led_inputs_dict(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) _UpperCamelCase : List[Any] = tf.concat( [tf.zeros_like(__UpperCamelCase )[:, :-1], tf.ones_like(__UpperCamelCase )[:, -1:]] , axis=-1 , ) _UpperCamelCase : int = global_attention_mask return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : Optional[Any] , __a : Tuple ) -> int: _UpperCamelCase : Union[str, Any] = TFLEDModel(config=__UpperCamelCase ).get_decoder() _UpperCamelCase : Dict = inputs_dict["input_ids"] _UpperCamelCase : Optional[int] = input_ids[:1, :] _UpperCamelCase : Dict = inputs_dict["attention_mask"][:1, :] _UpperCamelCase : List[Any] = 1 # first forward pass _UpperCamelCase : Union[str, Any] = model(__UpperCamelCase , attention_mask=__UpperCamelCase , use_cache=__UpperCamelCase ) _UpperCamelCase, _UpperCamelCase : Optional[int] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _UpperCamelCase : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) _UpperCamelCase : Tuple = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _UpperCamelCase : int = tf.concat([input_ids, next_tokens] , axis=-1 ) _UpperCamelCase : Any = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _UpperCamelCase : str = model(__UpperCamelCase , attention_mask=__UpperCamelCase )[0] _UpperCamelCase : Optional[int] = model(__UpperCamelCase , attention_mask=__UpperCamelCase , past_key_values=__UpperCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _UpperCamelCase : List[str] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _UpperCamelCase : List[Any] = output_from_no_past[:, -3:, random_slice_idx] _UpperCamelCase : Tuple = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__UpperCamelCase , __UpperCamelCase , rtol=1e-3 ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_=None ,lowercase_=None ,) -> Optional[Any]: """simple docstring""" if attention_mask is None: _UpperCamelCase : Dict = tf.cast(tf.math.not_equal(lowercase__ ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: _UpperCamelCase : List[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: _UpperCamelCase : Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _UpperCamelCase : int = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class __SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[str] = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :Tuple = (TFLEDForConditionalGeneration,) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :Dict = ( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ :List[str] = True SCREAMING_SNAKE_CASE__ :Any = False SCREAMING_SNAKE_CASE__ :str = False SCREAMING_SNAKE_CASE__ :Any = False def __SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: _UpperCamelCase : Union[str, Any] = TFLEDModelTester(self ) _UpperCamelCase : str = ConfigTester(self , config_class=__UpperCamelCase ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: _UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__UpperCamelCase ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: _UpperCamelCase, _UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase : int = tf.zeros_like(inputs_dict["attention_mask"] ) _UpperCamelCase : Union[str, Any] = 2 _UpperCamelCase : Union[str, Any] = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) _UpperCamelCase : str = True _UpperCamelCase : Union[str, Any] = self.model_tester.seq_length _UpperCamelCase : Any = self.model_tester.encoder_seq_length def check_decoder_attentions_output(__a : str ): _UpperCamelCase : str = outputs.decoder_attentions self.assertEqual(len(__UpperCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(__a : str ): _UpperCamelCase : Optional[Any] = [t.numpy() for t in outputs.encoder_attentions] _UpperCamelCase : Any = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(__UpperCamelCase ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(__UpperCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: _UpperCamelCase : int = True _UpperCamelCase : Any = False _UpperCamelCase : List[str] = False _UpperCamelCase : Any = model_class(__UpperCamelCase ) _UpperCamelCase : List[Any] = model(self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) _UpperCamelCase : str = len(__UpperCamelCase ) self.assertEqual(config.output_hidden_states , __UpperCamelCase ) check_encoder_attentions_output(__UpperCamelCase ) if self.is_encoder_decoder: _UpperCamelCase : Any = model_class(__UpperCamelCase ) _UpperCamelCase : Dict = model(self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) self.assertEqual(config.output_hidden_states , __UpperCamelCase ) check_decoder_attentions_output(__UpperCamelCase ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _UpperCamelCase : Dict = True _UpperCamelCase : str = model_class(__UpperCamelCase ) _UpperCamelCase : List[str] = model(self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) self.assertEqual(config.output_hidden_states , __UpperCamelCase ) check_encoder_attentions_output(__UpperCamelCase ) # Check attention is always last and order is fine _UpperCamelCase : Optional[Any] = True _UpperCamelCase : Optional[Any] = True _UpperCamelCase : Dict = model_class(__UpperCamelCase ) _UpperCamelCase : Optional[Any] = model(self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__UpperCamelCase ) ) self.assertEqual(model.config.output_hidden_states , __UpperCamelCase ) check_encoder_attentions_output(__UpperCamelCase ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: pass def __SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: pass def lowercase__ ( lowercase_ ) -> int: """simple docstring""" return tf.constant(lowercase__ ,dtype=tf.intaa ) lowerCamelCase__ = 1E-4 @slow @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Union[str, Any]: _UpperCamelCase : int = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here _UpperCamelCase : Optional[int] = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Any = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : List[Any] = prepare_led_inputs_dict(model.config , __UpperCamelCase , __UpperCamelCase ) _UpperCamelCase : Union[str, Any] = model(**__UpperCamelCase )[0] _UpperCamelCase : List[str] = (1, 1024, 768) self.assertEqual(output.shape , __UpperCamelCase ) # change to expected output here _UpperCamelCase : List[Any] = tf.convert_to_tensor( [[2.30_50, 2.82_79, 0.65_31], [-1.84_57, -0.14_55, -3.56_61], [-1.01_86, 0.45_86, -2.20_43]] , ) tf.debugging.assert_near(output[:, :3, :3] , __UpperCamelCase , atol=1e-3 ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: _UpperCamelCase : Optional[Any] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here _UpperCamelCase : List[str] = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : str = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Any = prepare_led_inputs_dict(model.config , __UpperCamelCase , __UpperCamelCase ) _UpperCamelCase : Optional[Any] = model(**__UpperCamelCase )[0] _UpperCamelCase : Union[str, Any] = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , __UpperCamelCase ) # change to expected output here _UpperCamelCase : List[Any] = tf.convert_to_tensor( [[33.65_07, 6.45_72, 16.80_89], [5.87_39, -2.42_38, 11.29_02], [-3.21_39, -4.31_49, 4.27_83]] , ) tf.debugging.assert_near(output[:, :3, :3] , __UpperCamelCase , atol=1e-3 , rtol=1e-3 )
702
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure)
51
0
"""simple docstring""" from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar lowerCamelCase__ = TypeVar("T") def lowercase__ ( lowercase_ ) -> Dict: """simple docstring""" return (position - 1) // 2 def lowercase__ ( lowercase_ ) -> Tuple: """simple docstring""" return (2 * position) + 1 def lowercase__ ( lowercase_ ) -> Dict: """simple docstring""" return (2 * position) + 2 class __SCREAMING_SNAKE_CASE ( Generic[T] ): def __init__( self : str ) -> None: _UpperCamelCase : list[tuple[T, int]] = [] _UpperCamelCase : dict[T, int] = {} _UpperCamelCase : int = 0 def __len__( self : Any ) -> int: return self.elements def __repr__( self : Union[str, Any] ) -> str: return str(self.heap ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.elements == 0 def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : Union[str, Any] , __a : str ) -> None: self.heap.append((elem, weight) ) _UpperCamelCase : Optional[Any] = self.elements self.elements += 1 self._bubble_up(lowercase__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> T: if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) _UpperCamelCase : List[str] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: _UpperCamelCase : Tuple = self.heap[0] self._bubble_down(lowercase__ ) return elem def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : List[str] , __a : int ) -> None: _UpperCamelCase : List[str] = self.position_map[elem] _UpperCamelCase : Any = (elem, weight) if position > 0: _UpperCamelCase : Optional[int] = get_parent_position(lowercase__ ) _UpperCamelCase : Tuple = self.heap[parent_position] if parent_weight > weight: self._bubble_up(lowercase__ ) else: self._bubble_down(lowercase__ ) else: self._bubble_down(lowercase__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : str ) -> None: _UpperCamelCase : Tuple = self.position_map[elem] if curr_pos == 0: return None _UpperCamelCase : Optional[int] = get_parent_position(lowercase__ ) _UpperCamelCase : Optional[Any] = self.heap[curr_pos] _UpperCamelCase : int = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(lowercase__ , lowercase__ ) return self._bubble_up(lowercase__ ) return None def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : List[Any] ) -> None: _UpperCamelCase : Any = self.position_map[elem] _UpperCamelCase : List[Any] = self.heap[curr_pos] _UpperCamelCase : Dict = get_child_left_position(lowercase__ ) _UpperCamelCase : Optional[int] = get_child_right_position(lowercase__ ) if child_left_position < self.elements and child_right_position < self.elements: _UpperCamelCase : Any = self.heap[child_left_position] _UpperCamelCase : str = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(lowercase__ , lowercase__ ) return self._bubble_down(lowercase__ ) if child_left_position < self.elements: _UpperCamelCase : List[str] = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(lowercase__ , lowercase__ ) return self._bubble_down(lowercase__ ) else: return None if child_right_position < self.elements: _UpperCamelCase : Optional[int] = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(lowercase__ , lowercase__ ) return self._bubble_down(lowercase__ ) return None def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : List[str] , __a : Dict ) -> None: _UpperCamelCase : List[Any] = self.heap[nodea_pos][0] _UpperCamelCase : str = self.heap[nodea_pos][0] _UpperCamelCase : Union[str, Any] = ( self.heap[nodea_pos], self.heap[nodea_pos], ) _UpperCamelCase : Dict = nodea_pos _UpperCamelCase : Any = nodea_pos class __SCREAMING_SNAKE_CASE ( Generic[T] ): def __init__( self : Dict ) -> None: _UpperCamelCase : dict[T, dict[T, int]] = {} _UpperCamelCase : int = 0 def __repr__( self : str ) -> str: return str(self.connections ) def __len__( self : Tuple ) -> int: return self.nodes def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : Any ) -> None: if node not in self.connections: _UpperCamelCase : Optional[int] = {} self.nodes += 1 def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : str , __a : Tuple , __a : Tuple ) -> None: self.add_node(lowercase__ ) self.add_node(lowercase__ ) _UpperCamelCase : Union[str, Any] = weight _UpperCamelCase : Any = weight def lowercase__ ( lowercase_ ,) -> Tuple: """simple docstring""" _UpperCamelCase : dict[T, int] = {node: maxsize for node in graph.connections} _UpperCamelCase : dict[T, T | None] = {node: None for node in graph.connections} _UpperCamelCase : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(lowerCAmelCase_ ,lowerCAmelCase_ ) if priority_queue.is_empty(): return dist, parent # initialization _UpperCamelCase : str = priority_queue.extract_min() _UpperCamelCase : Optional[int] = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: _UpperCamelCase : Dict = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCAmelCase_ ,dist[neighbour] ) _UpperCamelCase : int = node # running prim's algorithm while not priority_queue.is_empty(): _UpperCamelCase : Any = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: _UpperCamelCase : int = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCAmelCase_ ,dist[neighbour] ) _UpperCamelCase : List[str] = node return dist, parent
703
"""simple docstring""" lowerCamelCase__ = "\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCamelCase__ = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase__ = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
51
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "microsoft/trocr-base-handwritten": ( "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json" ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class __SCREAMING_SNAKE_CASE ( _UpperCAmelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[Any] = """trocr""" SCREAMING_SNAKE_CASE__ :Union[str, Any] = ["""past_key_values"""] SCREAMING_SNAKE_CASE__ :str = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self : Union[str, Any] , __a : Tuple=5_0265 , __a : Union[str, Any]=1024 , __a : str=12 , __a : Tuple=16 , __a : Union[str, Any]=4096 , __a : Any="gelu" , __a : Union[str, Any]=512 , __a : str=0.1 , __a : str=0.0 , __a : Union[str, Any]=0.0 , __a : Dict=2 , __a : Optional[int]=0.02 , __a : List[str]=0.0 , __a : Any=True , __a : Optional[int]=False , __a : Optional[Any]=True , __a : Dict=True , __a : int=1 , __a : List[Any]=0 , __a : Tuple=2 , **__a : Optional[Any] , ) -> str: _UpperCamelCase : Union[str, Any] = vocab_size _UpperCamelCase : int = d_model _UpperCamelCase : Any = decoder_layers _UpperCamelCase : str = decoder_attention_heads _UpperCamelCase : Optional[Any] = decoder_ffn_dim _UpperCamelCase : str = activation_function _UpperCamelCase : Dict = max_position_embeddings _UpperCamelCase : Dict = dropout _UpperCamelCase : Optional[int] = attention_dropout _UpperCamelCase : Dict = activation_dropout _UpperCamelCase : Tuple = init_std _UpperCamelCase : Optional[int] = decoder_layerdrop _UpperCamelCase : Optional[int] = use_cache _UpperCamelCase : Union[str, Any] = scale_embedding _UpperCamelCase : Optional[Any] = use_learned_position_embeddings _UpperCamelCase : Dict = layernorm_embedding super().__init__( pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , decoder_start_token_id=lowercase__ , **lowercase__ , )
704
"""simple docstring""" import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: _UpperCamelCase : Tuple = tempfile.mkdtemp() _UpperCamelCase : str = 5 # Realm tok _UpperCamelCase : Tuple = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "test", "question", "this", "is", "the", "first", "second", "third", "fourth", "fifth", "record", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _UpperCamelCase : Optional[int] = os.path.join(self.tmpdirname , "realm_tokenizer" ) os.makedirs(__a , exist_ok=__a ) _UpperCamelCase : Optional[Any] = os.path.join(__a , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) _UpperCamelCase : Optional[int] = os.path.join(self.tmpdirname , "realm_block_records" ) os.makedirs(__a , exist_ok=__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , "realm_tokenizer" ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: shutil.rmtree(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: _UpperCamelCase : Optional[Any] = RealmConfig(num_block_records=self.num_block_records ) return config def __SCREAMING_SNAKE_CASE ( self : int ) -> int: _UpperCamelCase : Any = Dataset.from_dict( { "id": ["0", "1"], "question": ["foo", "bar"], "answers": [["Foo", "Bar"], ["Bar"]], } ) return dataset def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: _UpperCamelCase : int = np.array( [ b"This is the first record", b"This is the second record", b"This is the third record", b"This is the fourth record", b"This is the fifth record", b"This is a longer longer longer record", ] , dtype=__a , ) return block_records def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: _UpperCamelCase : List[str] = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: _UpperCamelCase : Tuple = self.get_config() _UpperCamelCase : int = self.get_dummy_retriever() _UpperCamelCase : Tuple = retriever.tokenizer _UpperCamelCase : List[str] = np.array([0, 3] , dtype="long" ) _UpperCamelCase : Union[str, Any] = tokenizer(["Test question"] ).input_ids _UpperCamelCase : List[str] = tokenizer( ["the fourth"] , add_special_tokens=__a , return_token_type_ids=__a , return_attention_mask=__a , ).input_ids _UpperCamelCase : str = config.reader_seq_len _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : List[Any] = retriever( __a , __a , answer_ids=__a , max_length=__a , return_tensors="np" ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "first", "record", "[SEP]"] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "fourth", "record", "[SEP]"] , ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: _UpperCamelCase : Any = self.get_config() _UpperCamelCase : Dict = self.get_dummy_retriever() _UpperCamelCase : Dict = retriever.tokenizer _UpperCamelCase : List[Any] = np.array([0, 3, 5] , dtype="long" ) _UpperCamelCase : Optional[int] = tokenizer(["Test question"] ).input_ids _UpperCamelCase : str = tokenizer( ["the fourth", "longer longer"] , add_special_tokens=__a , return_token_type_ids=__a , return_attention_mask=__a , ).input_ids _UpperCamelCase : Union[str, Any] = config.reader_seq_len _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : Optional[Any] = retriever( __a , __a , answer_ids=__a , max_length=__a , return_tensors="np" ) self.assertEqual([False, True, True] , __a ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , __a ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , __a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: _UpperCamelCase : List[Any] = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) # Test local path _UpperCamelCase : int = retriever.from_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) self.assertEqual(retriever.block_records[0] , b"This is the first record" ) # Test mocked remote path with patch("transformers.models.realm.retrieval_realm.hf_hub_download" ) as mock_hf_hub_download: _UpperCamelCase : List[Any] = os.path.join( os.path.join(self.tmpdirname , "realm_block_records" ) , _REALM_BLOCK_RECORDS_FILENAME ) _UpperCamelCase : int = RealmRetriever.from_pretrained("google/realm-cc-news-pretrained-openqa" ) self.assertEqual(retriever.block_records[0] , b"This is the first record" )
51
0
"""simple docstring""" import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def lowercase__ ( lowercase_ ) -> str: """simple docstring""" _UpperCamelCase : List[str] = args.pruning_method _UpperCamelCase : Tuple = args.threshold _UpperCamelCase : List[str] = args.model_name_or_path.rstrip("/" ) _UpperCamelCase : Optional[int] = args.target_model_path print(F'''Load fine-pruned model from {model_name_or_path}''' ) _UpperCamelCase : Optional[int] = torch.load(os.path.join(a_ ,"pytorch_model.bin" ) ) _UpperCamelCase : List[str] = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: _UpperCamelCase : int = tensor print(F'''Copied layer {name}''' ) elif "classifier" in name or "qa_output" in name: _UpperCamelCase : int = tensor print(F'''Copied layer {name}''' ) elif "bias" in name: _UpperCamelCase : Optional[int] = tensor print(F'''Copied layer {name}''' ) else: if pruning_method == "magnitude": _UpperCamelCase : List[Any] = MagnitudeBinarizer.apply(inputs=a_ ,threshold=a_ ) _UpperCamelCase : Optional[Any] = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "topK": if "mask_scores" in name: continue _UpperCamelCase : Any = name[:-6] _UpperCamelCase : int = model[F'''{prefix_}mask_scores'''] _UpperCamelCase : List[str] = TopKBinarizer.apply(a_ ,a_ ) _UpperCamelCase : Optional[int] = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue _UpperCamelCase : List[Any] = name[:-6] _UpperCamelCase : Optional[Any] = model[F'''{prefix_}mask_scores'''] _UpperCamelCase : Any = ThresholdBinarizer.apply(a_ ,a_ ,a_ ) _UpperCamelCase : Optional[int] = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "l0": if "mask_scores" in name: continue _UpperCamelCase : List[str] = name[:-6] _UpperCamelCase : Optional[Any] = model[F'''{prefix_}mask_scores'''] _UpperCamelCase : Optional[Any] = -0.1, 1.1 _UpperCamelCase : int = torch.sigmoid(a_ ) _UpperCamelCase : Any = s * (r - l) + l _UpperCamelCase : List[str] = s_bar.clamp(min=0.0 ,max=1.0 ) _UpperCamelCase : Optional[Any] = tensor * mask print(F'''Pruned layer {name}''' ) else: raise ValueError("Unknown pruning method" ) if target_model_path is None: _UpperCamelCase : int = os.path.join( os.path.dirname(a_ ) ,F'''bertarized_{os.path.basename(a_ )}''' ) if not os.path.isdir(a_ ): shutil.copytree(a_ ,a_ ) print(F'''\nCreated folder {target_model_path}''' ) torch.save(a_ ,os.path.join(a_ ,"pytorch_model.bin" ) ) print("\nPruned model saved! See you later!" ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument( "--pruning_method", choices=["l0", "magnitude", "topK", "sigmoied_threshold"], type=str, required=True, help=( "Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning," " sigmoied_threshold = Soft movement pruning)" ), ) parser.add_argument( "--threshold", type=float, required=False, help=( "For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model." "For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared." "Not needed for `l0`" ), ) parser.add_argument( "--model_name_or_path", type=str, required=True, help="Folder containing the model that was previously fine-pruned", ) parser.add_argument( "--target_model_path", default=None, type=str, required=False, help="Folder containing the model that was previously fine-pruned", ) lowerCamelCase__ = parser.parse_args() main(args)
705
"""simple docstring""" from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class __SCREAMING_SNAKE_CASE : '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = LEDConfig SCREAMING_SNAKE_CASE__ :str = {} SCREAMING_SNAKE_CASE__ :List[str] = "gelu" def __init__( self : List[Any] , __a : Union[str, Any] , __a : List[Any]=13 , __a : int=7 , __a : str=True , __a : Any=False , __a : str=99 , __a : str=32 , __a : Union[str, Any]=2 , __a : Optional[Any]=4 , __a : List[Any]=37 , __a : List[Any]=0.1 , __a : Tuple=0.1 , __a : Dict=20 , __a : str=2 , __a : Dict=1 , __a : Any=0 , __a : List[Any]=4 , ) -> List[Any]: _UpperCamelCase : Optional[Any] = parent _UpperCamelCase : List[str] = batch_size _UpperCamelCase : str = seq_length _UpperCamelCase : str = is_training _UpperCamelCase : Any = use_labels _UpperCamelCase : Any = vocab_size _UpperCamelCase : List[str] = hidden_size _UpperCamelCase : Optional[Any] = num_hidden_layers _UpperCamelCase : Dict = num_attention_heads _UpperCamelCase : Optional[Any] = intermediate_size _UpperCamelCase : int = hidden_dropout_prob _UpperCamelCase : Dict = attention_probs_dropout_prob _UpperCamelCase : str = max_position_embeddings _UpperCamelCase : int = eos_token_id _UpperCamelCase : Dict = pad_token_id _UpperCamelCase : Optional[Any] = bos_token_id _UpperCamelCase : str = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after _UpperCamelCase : List[str] = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests _UpperCamelCase : int = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __SCREAMING_SNAKE_CASE ( self : int ) -> str: _UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _UpperCamelCase : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _UpperCamelCase : Tuple = tf.concat([input_ids, eos_tensor] , axis=1 ) _UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase : List[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) _UpperCamelCase : Dict = prepare_led_inputs_dict(__a , __a , __a ) _UpperCamelCase : Union[str, Any] = tf.concat( [tf.zeros_like(__a )[:, :-1], tf.ones_like(__a )[:, -1:]] , axis=-1 , ) _UpperCamelCase : Union[str, Any] = global_attention_mask return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : List[Any] , __a : int ) -> Tuple: _UpperCamelCase : Tuple = TFLEDModel(config=__a ).get_decoder() _UpperCamelCase : Tuple = inputs_dict["input_ids"] _UpperCamelCase : int = input_ids[:1, :] _UpperCamelCase : List[str] = inputs_dict["attention_mask"][:1, :] _UpperCamelCase : List[Any] = 1 # first forward pass _UpperCamelCase : Any = model(__a , attention_mask=__a , use_cache=__a ) _UpperCamelCase, _UpperCamelCase : Union[str, Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _UpperCamelCase : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) _UpperCamelCase : Any = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _UpperCamelCase : List[str] = tf.concat([input_ids, next_tokens] , axis=-1 ) _UpperCamelCase : Union[str, Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _UpperCamelCase : Tuple = model(__a , attention_mask=__a )[0] _UpperCamelCase : int = model(__a , attention_mask=__a , past_key_values=__a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _UpperCamelCase : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _UpperCamelCase : List[str] = output_from_no_past[:, -3:, random_slice_idx] _UpperCamelCase : Optional[int] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__a , __a , rtol=1e-3 ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_=None ,lowercase_=None ,) -> Dict: """simple docstring""" if attention_mask is None: _UpperCamelCase : str = tf.cast(tf.math.not_equal(lowercase_ ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: _UpperCamelCase : str = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: _UpperCamelCase : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _UpperCamelCase : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :List[str] = (TFLEDForConditionalGeneration,) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :List[str] = ( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ :Tuple = True SCREAMING_SNAKE_CASE__ :str = False SCREAMING_SNAKE_CASE__ :Optional[Any] = False SCREAMING_SNAKE_CASE__ :int = False def __SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: _UpperCamelCase : int = TFLEDModelTester(self ) _UpperCamelCase : Any = ConfigTester(self , config_class=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: _UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__a ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase, _UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase : Optional[int] = tf.zeros_like(inputs_dict["attention_mask"] ) _UpperCamelCase : Union[str, Any] = 2 _UpperCamelCase : str = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) _UpperCamelCase : Dict = True _UpperCamelCase : str = self.model_tester.seq_length _UpperCamelCase : Union[str, Any] = self.model_tester.encoder_seq_length def check_decoder_attentions_output(__a : Optional[int] ): _UpperCamelCase : Optional[int] = outputs.decoder_attentions self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(__a : Optional[Any] ): _UpperCamelCase : Union[str, Any] = [t.numpy() for t in outputs.encoder_attentions] _UpperCamelCase : List[Any] = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: _UpperCamelCase : Dict = True _UpperCamelCase : Optional[Any] = False _UpperCamelCase : int = False _UpperCamelCase : Optional[int] = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) _UpperCamelCase : Any = len(__a ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) if self.is_encoder_decoder: _UpperCamelCase : Optional[Any] = model_class(__a ) _UpperCamelCase : List[Any] = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_decoder_attentions_output(__a ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _UpperCamelCase : int = True _UpperCamelCase : Tuple = model_class(__a ) _UpperCamelCase : str = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) # Check attention is always last and order is fine _UpperCamelCase : Any = True _UpperCamelCase : List[str] = True _UpperCamelCase : Tuple = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__a ) ) self.assertEqual(model.config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: pass def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: # TODO: Head-masking not yet implement pass def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" return tf.constant(lowercase_ ,dtype=tf.intaa ) lowerCamelCase__ = 1E-4 @slow @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: _UpperCamelCase : Any = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here _UpperCamelCase : int = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Tuple = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Optional[Any] = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Optional[int] = model(**__a )[0] _UpperCamelCase : Optional[int] = (1, 1024, 768) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : Tuple = tf.convert_to_tensor( [[2.30_50, 2.82_79, 0.65_31], [-1.84_57, -0.14_55, -3.56_61], [-1.01_86, 0.45_86, -2.20_43]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> str: _UpperCamelCase : Optional[int] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here _UpperCamelCase : Optional[int] = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : List[str] = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Optional[Any] = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Union[str, Any] = model(**__a )[0] _UpperCamelCase : int = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : Optional[int] = tf.convert_to_tensor( [[33.65_07, 6.45_72, 16.80_89], [5.87_39, -2.42_38, 11.29_02], [-3.21_39, -4.31_49, 4.27_83]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 , rtol=1e-3 )
51
0
"""simple docstring""" import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration lowerCamelCase__ = [ # tf -> hf ("""/""", """."""), ("""layer_""", """layers."""), ("""kernel""", """weight"""), ("""beta""", """bias"""), ("""gamma""", """weight"""), ("""pegasus""", """model"""), ] lowerCamelCase__ = [ (""".output.dense""", """.fc2"""), ("""intermediate.LayerNorm""", """final_layer_norm"""), ("""intermediate.dense""", """fc1"""), ] lowerCamelCase__ = ( INIT_COMMON + [ ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.out_proj"""), ("""attention.self""", """self_attn"""), ("""attention.encdec.LayerNorm""", """encoder_attn_layer_norm"""), ("""attention.encdec_output.dense""", """encoder_attn.out_proj"""), ("""attention.encdec""", """encoder_attn"""), ("""key""", """k_proj"""), ("""value""", """v_proj"""), ("""query""", """q_proj"""), ("""decoder.LayerNorm""", """decoder.layernorm_embedding"""), ] + END_COMMON ) lowerCamelCase__ = ( INIT_COMMON + [ ("""embeddings.word_embeddings""", """shared.weight"""), ("""embeddings.position_embeddings""", """embed_positions.weight"""), ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.output"""), ("""attention.self""", """self_attn.self"""), ("""encoder.LayerNorm""", """encoder.layernorm_embedding"""), ] + END_COMMON ) lowerCamelCase__ = [ """encdec/key/bias""", """encdec/query/bias""", """encdec/value/bias""", """self/key/bias""", """self/query/bias""", """self/value/bias""", """encdec_output/dense/bias""", """attention/output/dense/bias""", ] def lowercase__ ( lowercase_ ,lowercase_ ) -> List[Any]: """simple docstring""" for tf_name, hf_name in patterns: _UpperCamelCase : List[Any] = k.replace(lowercase_ ,lowercase_ ) return k def lowercase__ ( lowercase_ ,lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Union[str, Any] = BigBirdPegasusConfig(**lowercase_ ) _UpperCamelCase : Tuple = BigBirdPegasusForConditionalGeneration(lowercase_ ) _UpperCamelCase : List[str] = torch_model.state_dict() _UpperCamelCase : int = {} # separating decoder weights _UpperCamelCase : Any = {k: tf_weights[k] for k in tf_weights if k.startswith("pegasus/decoder" )} _UpperCamelCase : Optional[Any] = {k: tf_weights[k] for k in tf_weights if not k.startswith("pegasus/decoder" )} for k, v in tqdm(decoder_weights.items() ,"tf -> hf conversion" ): _UpperCamelCase : Tuple = [k.endswith(lowercase_ ) for ending in KEYS_TO_IGNORE] if any(lowercase_ ): continue _UpperCamelCase : Tuple = DECODER_PATTERNS _UpperCamelCase : List[Any] = rename_state_dict_key(lowercase_ ,lowercase_ ) if new_k not in state_dict: raise ValueError(F'''could not find new key {new_k} in state dict. (converted from {k})''' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _UpperCamelCase : Dict = v.T _UpperCamelCase : str = torch.from_numpy(lowercase_ ) assert v.shape == state_dict[new_k].shape, F'''{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}''' for k, v in tqdm(remaining_weights.items() ,"tf -> hf conversion" ): _UpperCamelCase : Tuple = [k.endswith(lowercase_ ) for ending in KEYS_TO_IGNORE] if any(lowercase_ ): continue _UpperCamelCase : Union[str, Any] = REMAINING_PATTERNS _UpperCamelCase : Union[str, Any] = rename_state_dict_key(lowercase_ ,lowercase_ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(F'''could not find new key {new_k} in state dict. (converted from {k})''' ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): _UpperCamelCase : List[str] = v.T _UpperCamelCase : Union[str, Any] = torch.from_numpy(lowercase_ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, F'''{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}''' _UpperCamelCase : List[Any] = mapping["model.embed_positions.weight"] _UpperCamelCase : Dict = mapping.pop("model.embed_positions.weight" ) _UpperCamelCase, _UpperCamelCase : Tuple = torch_model.load_state_dict(lowercase_ ,strict=lowercase_ ) _UpperCamelCase : List[Any] = [ k for k in missing if k not in [ "final_logits_bias", "model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight", "lm_head.weight", ] ] assert unexpected_missing == [], F'''no matches found for the following torch keys {unexpected_missing}''' assert extra == [], F'''no matches found for the following tf keys {extra}''' return torch_model def lowercase__ ( lowercase_ ) -> Optional[int]: """simple docstring""" _UpperCamelCase : Optional[Any] = tf.train.list_variables(lowercase_ ) _UpperCamelCase : Tuple = {} _UpperCamelCase : List[Any] = ["global_step"] for name, shape in tqdm(lowercase_ ,desc="converting tf checkpoint to dict" ): _UpperCamelCase : Tuple = any(pat in name for pat in ignore_name ) if skip_key: continue _UpperCamelCase : List[str] = tf.train.load_variable(lowercase_ ,lowercase_ ) _UpperCamelCase : Tuple = array return tf_weights def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Union[str, Any] = get_tf_weights_as_numpy(lowercase_ ) _UpperCamelCase : Optional[Any] = convert_bigbird_pegasus(lowercase_ ,lowercase_ ) torch_model.save_pretrained(lowercase_ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("--tf_ckpt_path", type=str, help="passed to tf.train.list_variables") parser.add_argument("--save_dir", default=None, type=str, help="Path to the output PyTorch model.") lowerCamelCase__ = parser.parse_args() lowerCamelCase__ = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
706
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Union[str, Any] = RoCBertTokenizer SCREAMING_SNAKE_CASE__ :Dict = None SCREAMING_SNAKE_CASE__ :List[Any] = False SCREAMING_SNAKE_CASE__ :Union[str, Any] = True SCREAMING_SNAKE_CASE__ :Union[str, Any] = filter_non_english def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: super().setUp() _UpperCamelCase : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] _UpperCamelCase : List[str] = {} _UpperCamelCase : Tuple = {} for i, value in enumerate(__a ): _UpperCamelCase : List[str] = i _UpperCamelCase : Optional[Any] = i _UpperCamelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) _UpperCamelCase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(__a , __a , ensure_ascii=__a ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(__a , __a , ensure_ascii=__a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: _UpperCamelCase : Tuple = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : int = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(__a , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__a ) , [5, 6, 2, 5, 7, 8] ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: _UpperCamelCase : Dict = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: _UpperCamelCase : List[Any] = RoCBertBasicTokenizer(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 : Optional[Any] ) -> Tuple: _UpperCamelCase : Optional[Any] = RoCBertBasicTokenizer(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 : Dict ) -> str: _UpperCamelCase : Dict = RoCBertBasicTokenizer(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 : Union[str, Any] ) -> Union[str, Any]: _UpperCamelCase : List[str] = RoCBertBasicTokenizer(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[int]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase : Union[str, Any] = RoCBertBasicTokenizer(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 : Tuple ) -> List[Any]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(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 : Optional[Any] ) -> int: _UpperCamelCase : int = RoCBertBasicTokenizer(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 : List[str] ) -> Optional[Any]: _UpperCamelCase : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] _UpperCamelCase : Any = {} for i, token in enumerate(__a ): _UpperCamelCase : str = i _UpperCamelCase : Optional[int] = RoCBertWordpieceTokenizer(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 : Dict ) -> Optional[Any]: 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: 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 : Optional[int] ) -> Optional[int]: 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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = self.get_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]"]] ) if self.test_rust_tokenizer: _UpperCamelCase : Tuple = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__a ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Union[str, Any] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' _UpperCamelCase : Optional[Any] = tokenizer_r.encode_plus( __a , return_attention_mask=__a , return_token_type_ids=__a , return_offsets_mapping=__a , add_special_tokens=__a , ) _UpperCamelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(__a , "do_lower_case" ) else False _UpperCamelCase : Dict = ( [ ((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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = ["的", "人", "有"] _UpperCamelCase : int = "".join(__a ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = True _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : int = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : int = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : List[Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Union[str, Any] = 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 ) _UpperCamelCase : Any = False _UpperCamelCase : Dict = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Any = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Dict = tokenizer_p.convert_ids_to_tokens(__a ) # it is expected that only the first Chinese character is not preceded by "##". _UpperCamelCase : Any = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(__a ) ] self.assertListEqual(__a , __a ) self.assertListEqual(__a , __a ) @slow def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: _UpperCamelCase : Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : Optional[int] = tokenizer.encode("你好" , add_special_tokens=__a ) _UpperCamelCase : Dict = tokenizer.encode("你是谁" , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__a ) _UpperCamelCase : Tuple = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: _UpperCamelCase : Optional[Any] = self.get_tokenizers(do_lower_case=__a ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): _UpperCamelCase : int = "你好,你是谁" _UpperCamelCase : Any = tokenizer.tokenize(__a ) _UpperCamelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(__a ) _UpperCamelCase : List[str] = tokenizer.convert_tokens_to_shape_ids(__a ) _UpperCamelCase : Any = tokenizer.convert_tokens_to_pronunciation_ids(__a ) _UpperCamelCase : Optional[int] = tokenizer.prepare_for_model( __a , __a , __a , add_special_tokens=__a ) _UpperCamelCase : Tuple = tokenizer.encode_plus(__a , add_special_tokens=__a ) self.assertEqual(__a , __a )
51
0
"""simple docstring""" import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu from accelerate.utils import KwargsHandler @dataclass class __SCREAMING_SNAKE_CASE ( UpperCAmelCase_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :int = 0 SCREAMING_SNAKE_CASE__ :bool = False SCREAMING_SNAKE_CASE__ :float = 3.0 class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: self.assertDictEqual(MockClass().to_kwargs() , {} ) self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {"a": 2} ) self.assertDictEqual(MockClass(a=2 , b=_snake_case ).to_kwargs() , {"a": 2, "b": True} ) self.assertDictEqual(MockClass(a=2 , c=2.25 ).to_kwargs() , {"a": 2, "c": 2.25} ) @require_cuda def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: _UpperCamelCase : List[str] = GradScalerKwargs(init_scale=1024 , growth_factor=2 ) AcceleratorState._reset_state() _UpperCamelCase : List[Any] = Accelerator(mixed_precision="fp16" , kwargs_handlers=[scaler_handler] ) print(accelerator.use_fpaa ) _UpperCamelCase : Union[str, Any] = accelerator.scaler # Check the kwargs have been applied self.assertEqual(scaler._init_scale , 10_24.0 ) self.assertEqual(scaler._growth_factor , 2.0 ) # Check the other values are at the default self.assertEqual(scaler._backoff_factor , 0.5 ) self.assertEqual(scaler._growth_interval , 2000 ) self.assertEqual(scaler._enabled , _snake_case ) @require_multi_gpu def __SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: _UpperCamelCase : Tuple = ["torchrun", F'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] execute_subprocess_async(_snake_case , env=os.environ.copy() ) if __name__ == "__main__": lowerCamelCase__ = DistributedDataParallelKwargs(bucket_cap_mb=15, find_unused_parameters=True) lowerCamelCase__ = Accelerator(kwargs_handlers=[ddp_scaler]) lowerCamelCase__ = torch.nn.Linear(100, 200) lowerCamelCase__ = accelerator.prepare(model) # Check the values changed in kwargs lowerCamelCase__ = "" lowerCamelCase__ = model.bucket_bytes_cap // (1024 * 1024) if observed_bucket_cap_map != 15: error_msg += f"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" if model.find_unused_parameters is not True: error_msg += f"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" # Check the values of the defaults if model.dim != 0: error_msg += f"Default value not respected, should have `0` but found {model.dim}.\n" if model.broadcast_buffers is not True: error_msg += f"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" if model.gradient_as_bucket_view is not False: error_msg += f"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
707
"""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 lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "hustvl/yolos-small": "https://huggingface.co/hustvl/yolos-small/resolve/main/config.json", # See all YOLOS models at https://huggingface.co/models?filter=yolos } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = "yolos" def __init__( self : Dict , __a : Optional[Any]=768 , __a : List[Any]=12 , __a : Any=12 , __a : List[Any]=3072 , __a : Optional[int]="gelu" , __a : Dict=0.0 , __a : Optional[Any]=0.0 , __a : Any=0.02 , __a : Optional[int]=1e-1_2 , __a : List[Any]=[512, 864] , __a : List[str]=16 , __a : str=3 , __a : Optional[Any]=True , __a : Optional[Any]=100 , __a : List[str]=True , __a : Any=False , __a : List[str]=1 , __a : str=5 , __a : Optional[Any]=2 , __a : Tuple=5 , __a : Any=2 , __a : Union[str, Any]=0.1 , **__a : List[str] , ) -> List[str]: super().__init__(**__a ) _UpperCamelCase : Dict = hidden_size _UpperCamelCase : Any = num_hidden_layers _UpperCamelCase : str = num_attention_heads _UpperCamelCase : Dict = intermediate_size _UpperCamelCase : List[str] = hidden_act _UpperCamelCase : List[str] = hidden_dropout_prob _UpperCamelCase : str = attention_probs_dropout_prob _UpperCamelCase : Tuple = initializer_range _UpperCamelCase : List[str] = layer_norm_eps _UpperCamelCase : Tuple = image_size _UpperCamelCase : Tuple = patch_size _UpperCamelCase : Dict = num_channels _UpperCamelCase : Any = qkv_bias _UpperCamelCase : str = num_detection_tokens _UpperCamelCase : str = use_mid_position_embeddings _UpperCamelCase : List[str] = auxiliary_loss # Hungarian matcher _UpperCamelCase : List[Any] = class_cost _UpperCamelCase : int = bbox_cost _UpperCamelCase : Optional[int] = giou_cost # Loss coefficients _UpperCamelCase : List[Any] = bbox_loss_coefficient _UpperCamelCase : str = giou_loss_coefficient _UpperCamelCase : Dict = eos_coefficient class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[str] = version.parse("1.11" ) @property def __SCREAMING_SNAKE_CASE ( self : str ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> float: return 1e-4 @property def __SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return 12
51
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = StableUnCLIPImgaImgPipeline SCREAMING_SNAKE_CASE__ :List[str] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS SCREAMING_SNAKE_CASE__ :Tuple = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS SCREAMING_SNAKE_CASE__ :List[Any] = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess SCREAMING_SNAKE_CASE__ :Dict = frozenset([] ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: _UpperCamelCase : Optional[Any] = 32 _UpperCamelCase : Union[str, Any] = embedder_hidden_size # image encoding components _UpperCamelCase : int = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) _UpperCamelCase : List[Any] = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=_lowerCAmelCase , projection_dim=_lowerCAmelCase , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) _UpperCamelCase : Optional[Any] = StableUnCLIPImageNormalizer(embedding_dim=_lowerCAmelCase ) _UpperCamelCase : List[Any] = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) _UpperCamelCase : Optional[int] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) _UpperCamelCase : Any = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_lowerCAmelCase , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) _UpperCamelCase : Optional[int] = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_lowerCAmelCase , layers_per_block=1 , upcast_attention=_lowerCAmelCase , use_linear_projection=_lowerCAmelCase , ) torch.manual_seed(0 ) _UpperCamelCase : Union[str, Any] = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type="v_prediction" , set_alpha_to_one=_lowerCAmelCase , steps_offset=1 , ) torch.manual_seed(0 ) _UpperCamelCase : Optional[Any] = AutoencoderKL() _UpperCamelCase : Union[str, Any] = { # image encoding components "feature_extractor": feature_extractor, "image_encoder": image_encoder.eval(), # image noising components "image_normalizer": image_normalizer.eval(), "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder.eval(), "unet": unet.eval(), "scheduler": scheduler, "vae": vae.eval(), } return components def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : int , __a : Union[str, Any]=0 , __a : Optional[int]=True ) -> Tuple: if str(_lowerCAmelCase ).startswith("mps" ): _UpperCamelCase : str = torch.manual_seed(_lowerCAmelCase ) else: _UpperCamelCase : str = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase ) _UpperCamelCase : Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowerCAmelCase ) ).to(_lowerCAmelCase ) if pil_image: _UpperCamelCase : List[str] = input_image * 0.5 + 0.5 _UpperCamelCase : Tuple = input_image.clamp(0 , 1 ) _UpperCamelCase : List[Any] = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() _UpperCamelCase : str = DiffusionPipeline.numpy_to_pil(_lowerCAmelCase )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def __SCREAMING_SNAKE_CASE ( self : str ) -> Any: _UpperCamelCase : List[str] = "cpu" # ensure determinism for the device-dependent torch.Generator _UpperCamelCase : Dict = self.get_dummy_components() _UpperCamelCase : Dict = StableUnCLIPImgaImgPipeline(**_lowerCAmelCase ) _UpperCamelCase : Dict = sd_pipe.to(_lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase ) _UpperCamelCase : List[Any] = self.get_dummy_inputs(_lowerCAmelCase ) inputs.update({"image_embeds": None} ) _UpperCamelCase : Tuple = sd_pipe(**_lowerCAmelCase ).images _UpperCamelCase : int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _UpperCamelCase : int = np.array([0.38_72, 0.72_24, 0.56_01, 0.47_41, 0.68_72, 0.58_14, 0.46_36, 0.38_67, 0.50_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: _UpperCamelCase : Tuple = torch_device in ["cpu", "mps"] self._test_attention_slicing_forward_pass(test_max_difference=_lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: _UpperCamelCase : List[str] = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=_lowerCAmelCase ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: self._test_xformers_attention_forwardGenerator_pass(test_max_difference=_lowerCAmelCase ) @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: _UpperCamelCase : List[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) _UpperCamelCase : List[Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy" ) _UpperCamelCase : Dict = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-l-img2img" , torch_dtype=torch.floataa ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _UpperCamelCase : List[Any] = torch.Generator(device="cpu" ).manual_seed(0 ) _UpperCamelCase : List[Any] = pipe(_lowerCAmelCase , "anime turle" , generator=_lowerCAmelCase , output_type="np" ) _UpperCamelCase : Optional[int] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_lowerCAmelCase , _lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: _UpperCamelCase : Tuple = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) _UpperCamelCase : int = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy" ) _UpperCamelCase : str = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _UpperCamelCase : List[str] = torch.Generator(device="cpu" ).manual_seed(0 ) _UpperCamelCase : Optional[Any] = pipe(_lowerCAmelCase , "anime turle" , generator=_lowerCAmelCase , output_type="np" ) _UpperCamelCase : List[str] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_lowerCAmelCase , _lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: _UpperCamelCase : Any = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png" ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _UpperCamelCase : Tuple = StableUnCLIPImgaImgPipeline.from_pretrained( "fusing/stable-unclip-2-1-h-img2img" , torch_dtype=torch.floataa ) _UpperCamelCase : Any = pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _UpperCamelCase : List[Any] = pipe( _lowerCAmelCase , "anime turtle" , num_inference_steps=2 , output_type="np" , ) _UpperCamelCase : Dict = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
708
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path lowerCamelCase__ = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) lowerCamelCase__ = [ord(letter) for letter in string.ascii_lowercase] lowerCamelCase__ = {ord(char) for char in VALID_CHARS} lowerCamelCase__ = ["the", "be", "to", "of", "and", "in", "that", "have"] def lowercase__ ( lowercase_ ,lowercase_ ) -> str | None: """simple docstring""" _UpperCamelCase : str = "" _UpperCamelCase : int _UpperCamelCase : int _UpperCamelCase : int for keychar, cipherchar in zip(cycle(lowercase_ ) ,lowercase_ ): _UpperCamelCase : Dict = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(lowercase_ ) return decoded def lowercase__ ( lowercase_ ) -> list[str]: """simple docstring""" _UpperCamelCase : list[str] = [] for key in product(lowercase_ ,repeat=3 ): _UpperCamelCase : int = try_key(lowercase_ ,lowercase_ ) if encoded is not None: possibles.append(lowercase_ ) return possibles def lowercase__ ( lowercase_ ,lowercase_ ) -> list[str]: """simple docstring""" return [possible for possible in possibles if common_word in possible.lower()] def lowercase__ ( lowercase_ = "p059_cipher.txt" ) -> int: """simple docstring""" _UpperCamelCase : list[int] _UpperCamelCase : list[str] _UpperCamelCase : str _UpperCamelCase : str _UpperCamelCase : str = Path(lowercase_ ).parent.joinpath(lowercase_ ).read_text(encoding="utf-8" ) _UpperCamelCase : Optional[Any] = [int(lowercase_ ) for number in data.strip().split("," )] _UpperCamelCase : List[str] = filter_valid_chars(lowercase_ ) for common_word in COMMON_WORDS: _UpperCamelCase : Union[str, Any] = filter_common_word(lowercase_ ,lowercase_ ) if len(lowercase_ ) == 1: break _UpperCamelCase : Union[str, Any] = possibles[0] return sum(ord(lowercase_ ) for char in decoded_text ) if __name__ == "__main__": print(f"""{solution() = }""")
51
0
from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: _UpperCamelCase : List[Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a , "embed_dim" ) ) self.parent.assertTrue(hasattr(_a , "num_heads" ) ) class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] , __a : Optional[int] , __a : Optional[int]=13 , __a : Optional[Any]=64 , __a : int=3 , __a : Tuple=[16, 48, 96] , __a : Union[str, Any]=[1, 3, 6] , __a : str=[1, 2, 10] , __a : Tuple=[7, 3, 3] , __a : List[str]=[4, 2, 2] , __a : Union[str, Any]=[2, 1, 1] , __a : Tuple=[2, 2, 2] , __a : Optional[int]=[False, False, True] , __a : Dict=[0.0, 0.0, 0.0] , __a : Union[str, Any]=0.02 , __a : Optional[Any]=1e-1_2 , __a : List[str]=True , __a : str=True , __a : Dict=2 , ) -> Optional[int]: _UpperCamelCase : str = parent _UpperCamelCase : Union[str, Any] = batch_size _UpperCamelCase : int = image_size _UpperCamelCase : Optional[int] = patch_sizes _UpperCamelCase : List[str] = patch_stride _UpperCamelCase : Any = patch_padding _UpperCamelCase : int = is_training _UpperCamelCase : List[str] = use_labels _UpperCamelCase : Tuple = num_labels _UpperCamelCase : Tuple = num_channels _UpperCamelCase : Optional[int] = embed_dim _UpperCamelCase : List[str] = num_heads _UpperCamelCase : Union[str, Any] = stride_kv _UpperCamelCase : Union[str, Any] = depth _UpperCamelCase : Dict = cls_token _UpperCamelCase : Dict = attention_drop_rate _UpperCamelCase : List[Any] = initializer_range _UpperCamelCase : Any = layer_norm_eps def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: _UpperCamelCase : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCamelCase : Union[str, Any] = None if self.use_labels: # create a random int32 tensor of given shape _UpperCamelCase : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) _UpperCamelCase : List[str] = self.get_config() return config, pixel_values, labels def __SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __SCREAMING_SNAKE_CASE ( self : Any , __a : Union[str, Any] , __a : Union[str, Any] , __a : Dict ) -> Optional[Any]: _UpperCamelCase : Dict = TFCvtModel(config=_a ) _UpperCamelCase : int = model(_a , training=_a ) _UpperCamelCase : Union[str, Any] = (self.image_size, self.image_size) _UpperCamelCase : Union[str, Any] = image_size[0], image_size[1] for i in range(len(self.depth ) ): _UpperCamelCase : Optional[int] = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) _UpperCamelCase : Dict = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __SCREAMING_SNAKE_CASE ( self : Any , __a : Dict , __a : Any , __a : Optional[int] ) -> List[str]: _UpperCamelCase : Any = self.num_labels _UpperCamelCase : str = TFCvtForImageClassification(_a ) _UpperCamelCase : List[Any] = model(_a , labels=_a , training=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: _UpperCamelCase : List[Any] = self.prepare_config_and_inputs() _UpperCamelCase : Tuple = config_and_inputs _UpperCamelCase : Any = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[Any] = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :Tuple = ( {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification} if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ :Dict = False SCREAMING_SNAKE_CASE__ :List[str] = False SCREAMING_SNAKE_CASE__ :List[str] = False SCREAMING_SNAKE_CASE__ :Any = False SCREAMING_SNAKE_CASE__ :Union[str, Any] = False def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: _UpperCamelCase : Union[str, Any] = TFCvtModelTester(self ) _UpperCamelCase : str = TFCvtConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> str: self.config_tester.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() @unittest.skip(reason="Cvt does not output attentions" ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: pass @unittest.skip(reason="Cvt does not use inputs_embeds" ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: pass @unittest.skip(reason="Cvt does not support input and output embeddings" ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("GPU" ) ) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("GPU" ) ) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , ) @slow def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: super().test_keras_fit() @unittest.skip(reason="Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: _UpperCamelCase : Any = tf.keras.mixed_precision.Policy("mixed_float16" ) tf.keras.mixed_precision.set_global_policy(_a ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy("float32" ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: _UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase : List[Any] = model_class(_a ) _UpperCamelCase : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCamelCase : List[Any] = [*signature.parameters.keys()] _UpperCamelCase : Dict = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> Optional[Any]: def check_hidden_states_output(__a : List[Any] , __a : Union[str, Any] , __a : Any ): _UpperCamelCase : Union[str, Any] = model_class(_a ) _UpperCamelCase : Union[str, Any] = model(**self._prepare_for_class(_a , _a ) ) _UpperCamelCase : Optional[int] = outputs.hidden_states _UpperCamelCase : Optional[Any] = len(self.model_tester.depth ) self.assertEqual(len(_a ) , _a ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) _UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase : Any = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCamelCase : Optional[Any] = True check_hidden_states_output(_a , _a , _a ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: _UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: _UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def __SCREAMING_SNAKE_CASE ( self : int ) -> Any: for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase : Optional[Any] = TFCvtModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase__ ( ) -> Optional[int]: """simple docstring""" _UpperCamelCase : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: _UpperCamelCase : Dict = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) _UpperCamelCase : Optional[Any] = self.default_image_processor _UpperCamelCase : Tuple = prepare_img() _UpperCamelCase : Optional[Any] = image_processor(images=_a , return_tensors="tf" ) # forward pass _UpperCamelCase : int = model(**_a ) # verify the logits _UpperCamelCase : Dict = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _a ) _UpperCamelCase : Union[str, Any] = tf.constant([0.92_85, 0.90_15, -0.31_50] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , _a , atol=1e-4 ) )
709
"""simple docstring""" def lowercase__ ( lowercase_ ,lowercase_ ) -> None: """simple docstring""" _UpperCamelCase : List[Any] = len(lowercase_ ) print("The following activities are selected:" ) # The first activity is always selected _UpperCamelCase : List[Any] = 0 print(lowercase_ ,end="," ) # Consider rest of the activities for j in range(lowercase_ ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(lowercase_ ,end="," ) _UpperCamelCase : Optional[Any] = j if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase__ = [1, 3, 0, 5, 8, 5] lowerCamelCase__ = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
51
0
"""simple docstring""" from collections import Counter from timeit import timeit def lowercase__ ( lowercase_ = "" ,) -> bool: """simple docstring""" return sum(c % 2 for c in Counter(input_str.replace(" " ,"" ).lower() ).values() ) < 2 def lowercase__ ( lowercase_ = "" ) -> bool: """simple docstring""" if len(__UpperCamelCase ) == 0: return True _UpperCamelCase : Tuple = input_str.replace(" " ,"" ).lower() # character_freq_dict: Stores the frequency of every character in the input string _UpperCamelCase : dict[str, int] = {} for character in lower_case_input_str: _UpperCamelCase : Union[str, Any] = character_freq_dict.get(__UpperCamelCase ,0 ) + 1 _UpperCamelCase : str = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def lowercase__ ( lowercase_ = "" ) -> None: """simple docstring""" print("\nFor string = " ,__UpperCamelCase ,":" ) print( "> can_string_be_rearranged_as_palindrome_counter()" ,"\tans =" ,can_string_be_rearranged_as_palindrome_counter(__UpperCamelCase ) ,"\ttime =" ,timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)" ,setup="import __main__ as z" ,) ,"seconds" ,) print( "> can_string_be_rearranged_as_palindrome()" ,"\tans =" ,can_string_be_rearranged_as_palindrome(__UpperCamelCase ) ,"\ttime =" ,timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)" ,setup="import __main__ as z" ,) ,"seconds" ,) if __name__ == "__main__": lowerCamelCase__ = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) lowerCamelCase__ = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"""{check_str} can {"" if status else "not "}be rearranged as a palindrome""")
710
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :torch.FloatTensor class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : Dict=3 , __a : Any=3 , __a : Union[str, Any]=("DownEncoderBlock2D",) , __a : Optional[int]=(64,) , __a : int=2 , __a : Tuple=32 , __a : int="silu" , __a : str=True , ) -> Dict: super().__init__() _UpperCamelCase : List[str] = layers_per_block _UpperCamelCase : Dict = torch.nn.Convad( __a , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) _UpperCamelCase : int = None _UpperCamelCase : Any = nn.ModuleList([] ) # down _UpperCamelCase : List[str] = block_out_channels[0] for i, down_block_type in enumerate(__a ): _UpperCamelCase : Tuple = output_channel _UpperCamelCase : int = block_out_channels[i] _UpperCamelCase : int = i == len(__a ) - 1 _UpperCamelCase : Dict = get_down_block( __a , num_layers=self.layers_per_block , in_channels=__a , out_channels=__a , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=__a , resnet_groups=__a , attention_head_dim=__a , temb_channels=__a , ) self.down_blocks.append(__a ) # mid _UpperCamelCase : Union[str, Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__a , output_scale_factor=1 , resnet_time_scale_shift="default" , attention_head_dim=block_out_channels[-1] , resnet_groups=__a , temb_channels=__a , ) # out _UpperCamelCase : Any = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__a , eps=1e-6 ) _UpperCamelCase : Any = nn.SiLU() _UpperCamelCase : Union[str, Any] = 2 * out_channels if double_z else out_channels _UpperCamelCase : Tuple = nn.Convad(block_out_channels[-1] , __a , 3 , padding=1 ) _UpperCamelCase : Optional[int] = False def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Dict ) -> List[str]: _UpperCamelCase : int = x _UpperCamelCase : Optional[int] = self.conv_in(__a ) if self.training and self.gradient_checkpointing: def create_custom_forward(__a : Tuple ): def custom_forward(*__a : Any ): return module(*__a ) return custom_forward # down if is_torch_version(">=" , "1.11.0" ): for down_block in self.down_blocks: _UpperCamelCase : Optional[int] = torch.utils.checkpoint.checkpoint( create_custom_forward(__a ) , __a , use_reentrant=__a ) # middle _UpperCamelCase : Tuple = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , use_reentrant=__a ) else: for down_block in self.down_blocks: _UpperCamelCase : Any = torch.utils.checkpoint.checkpoint(create_custom_forward(__a ) , __a ) # middle _UpperCamelCase : int = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __a ) else: # down for down_block in self.down_blocks: _UpperCamelCase : int = down_block(__a ) # middle _UpperCamelCase : int = self.mid_block(__a ) # post-process _UpperCamelCase : Any = self.conv_norm_out(__a ) _UpperCamelCase : Any = self.conv_act(__a ) _UpperCamelCase : Optional[Any] = self.conv_out(__a ) return sample class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : int=3 , __a : Any=3 , __a : str=("UpDecoderBlock2D",) , __a : Optional[int]=(64,) , __a : int=2 , __a : Optional[int]=32 , __a : Tuple="silu" , __a : Union[str, Any]="group" , ) -> str: super().__init__() _UpperCamelCase : List[Any] = layers_per_block _UpperCamelCase : Tuple = nn.Convad( __a , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) _UpperCamelCase : List[str] = None _UpperCamelCase : Dict = nn.ModuleList([] ) _UpperCamelCase : List[Any] = in_channels if norm_type == "spatial" else None # mid _UpperCamelCase : Optional[Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__a , output_scale_factor=1 , resnet_time_scale_shift="default" if norm_type == "group" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__a , temb_channels=__a , ) # up _UpperCamelCase : List[str] = list(reversed(__a ) ) _UpperCamelCase : int = reversed_block_out_channels[0] for i, up_block_type in enumerate(__a ): _UpperCamelCase : int = output_channel _UpperCamelCase : Union[str, Any] = reversed_block_out_channels[i] _UpperCamelCase : Optional[Any] = i == len(__a ) - 1 _UpperCamelCase : Union[str, Any] = get_up_block( __a , num_layers=self.layers_per_block + 1 , in_channels=__a , out_channels=__a , prev_output_channel=__a , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=__a , resnet_groups=__a , attention_head_dim=__a , temb_channels=__a , resnet_time_scale_shift=__a , ) self.up_blocks.append(__a ) _UpperCamelCase : Optional[Any] = output_channel # out if norm_type == "spatial": _UpperCamelCase : Optional[int] = SpatialNorm(block_out_channels[0] , __a ) else: _UpperCamelCase : Optional[int] = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__a , eps=1e-6 ) _UpperCamelCase : str = nn.SiLU() _UpperCamelCase : str = nn.Convad(block_out_channels[0] , __a , 3 , padding=1 ) _UpperCamelCase : Dict = False def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : List[Any] , __a : Union[str, Any]=None ) -> Tuple: _UpperCamelCase : List[str] = z _UpperCamelCase : Dict = self.conv_in(__a ) _UpperCamelCase : Any = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__a : Any ): def custom_forward(*__a : Tuple ): return module(*__a ) return custom_forward if is_torch_version(">=" , "1.11.0" ): # middle _UpperCamelCase : str = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , __a , use_reentrant=__a ) _UpperCamelCase : Optional[int] = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(__a ) , __a , __a , use_reentrant=__a ) else: # middle _UpperCamelCase : Optional[int] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , __a ) _UpperCamelCase : Union[str, Any] = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : str = torch.utils.checkpoint.checkpoint(create_custom_forward(__a ) , __a , __a ) else: # middle _UpperCamelCase : str = self.mid_block(__a , __a ) _UpperCamelCase : int = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : Any = up_block(__a , __a ) # post-process if latent_embeds is None: _UpperCamelCase : List[str] = self.conv_norm_out(__a ) else: _UpperCamelCase : Optional[int] = self.conv_norm_out(__a , __a ) _UpperCamelCase : Tuple = self.conv_act(__a ) _UpperCamelCase : List[Any] = self.conv_out(__a ) return sample class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : Tuple , __a : List[str] , __a : List[str] , __a : str=None , __a : Optional[int]="random" , __a : Any=False , __a : Optional[Any]=True ) -> List[Any]: super().__init__() _UpperCamelCase : Tuple = n_e _UpperCamelCase : Tuple = vq_embed_dim _UpperCamelCase : Union[str, Any] = beta _UpperCamelCase : str = legacy _UpperCamelCase : Dict = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) _UpperCamelCase : Any = remap if self.remap is not None: self.register_buffer("used" , torch.tensor(np.load(self.remap ) ) ) _UpperCamelCase : Dict = self.used.shape[0] _UpperCamelCase : Optional[int] = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": _UpperCamelCase : Optional[int] = self.re_embed _UpperCamelCase : Any = self.re_embed + 1 print( F'''Remapping {self.n_e} indices to {self.re_embed} indices. ''' F'''Using {self.unknown_index} for unknown indices.''' ) else: _UpperCamelCase : Union[str, Any] = n_e _UpperCamelCase : List[str] = sane_index_shape def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : Optional[Any] ) -> Optional[int]: _UpperCamelCase : str = inds.shape assert len(__a ) > 1 _UpperCamelCase : Union[str, Any] = inds.reshape(ishape[0] , -1 ) _UpperCamelCase : Optional[Any] = self.used.to(__a ) _UpperCamelCase : List[str] = (inds[:, :, None] == used[None, None, ...]).long() _UpperCamelCase : Optional[Any] = match.argmax(-1 ) _UpperCamelCase : Any = match.sum(2 ) < 1 if self.unknown_index == "random": _UpperCamelCase : Optional[int] = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: _UpperCamelCase : Dict = self.unknown_index return new.reshape(__a ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : Optional[int] ) -> Optional[int]: _UpperCamelCase : int = inds.shape assert len(__a ) > 1 _UpperCamelCase : List[Any] = inds.reshape(ishape[0] , -1 ) _UpperCamelCase : Optional[int] = self.used.to(__a ) if self.re_embed > self.used.shape[0]: # extra token _UpperCamelCase : int = 0 # simply set to zero _UpperCamelCase : Union[str, Any] = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __a ) return back.reshape(__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : str ) -> Optional[int]: # reshape z -> (batch, height, width, channel) and flatten _UpperCamelCase : List[str] = z.permute(0 , 2 , 3 , 1 ).contiguous() _UpperCamelCase : int = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z _UpperCamelCase : Optional[int] = torch.argmin(torch.cdist(__a , self.embedding.weight ) , dim=1 ) _UpperCamelCase : int = self.embedding(__a ).view(z.shape ) _UpperCamelCase : str = None _UpperCamelCase : Any = None # compute loss for embedding if not self.legacy: _UpperCamelCase : List[str] = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: _UpperCamelCase : str = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients _UpperCamelCase : List[str] = z + (z_q - z).detach() # reshape back to match original input shape _UpperCamelCase : Optional[Any] = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: _UpperCamelCase : Tuple = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis _UpperCamelCase : Dict = self.remap_to_used(__a ) _UpperCamelCase : List[str] = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: _UpperCamelCase : str = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : List[str] , __a : str ) -> Any: # shape specifying (batch, height, width, channel) if self.remap is not None: _UpperCamelCase : str = indices.reshape(shape[0] , -1 ) # add batch axis _UpperCamelCase : str = self.unmap_to_all(__a ) _UpperCamelCase : int = indices.reshape(-1 ) # flatten again # get quantized latent vectors _UpperCamelCase : Optional[int] = self.embedding(__a ) if shape is not None: _UpperCamelCase : Tuple = z_q.view(__a ) # reshape back to match original input shape _UpperCamelCase : Tuple = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __init__( self : Optional[int] , __a : List[str] , __a : Optional[Any]=False ) -> int: _UpperCamelCase : Dict = parameters _UpperCamelCase, _UpperCamelCase : str = torch.chunk(__a , 2 , dim=1 ) _UpperCamelCase : Tuple = torch.clamp(self.logvar , -30.0 , 20.0 ) _UpperCamelCase : Union[str, Any] = deterministic _UpperCamelCase : Dict = torch.exp(0.5 * self.logvar ) _UpperCamelCase : Any = torch.exp(self.logvar ) if self.deterministic: _UpperCamelCase : List[Any] = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : Optional[torch.Generator] = None ) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype _UpperCamelCase : List[Any] = randn_tensor( self.mean.shape , generator=__a , device=self.parameters.device , dtype=self.parameters.dtype ) _UpperCamelCase : List[Any] = self.mean + self.std * sample return x def __SCREAMING_SNAKE_CASE ( self : Any , __a : List[str]=None ) -> List[Any]: if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def __SCREAMING_SNAKE_CASE ( self : str , __a : Tuple , __a : List[str]=[1, 2, 3] ) -> int: if self.deterministic: return torch.Tensor([0.0] ) _UpperCamelCase : List[str] = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: return self.mean
51
0
"""simple docstring""" import math import unittest def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" 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 number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 ,int(math.sqrt(lowerCamelCase_ ) + 1 ) ,6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: self.assertTrue(is_prime(2 ) ) self.assertTrue(is_prime(3 ) ) self.assertTrue(is_prime(5 ) ) self.assertTrue(is_prime(7 ) ) self.assertTrue(is_prime(11 ) ) self.assertTrue(is_prime(13 ) ) self.assertTrue(is_prime(17 ) ) self.assertTrue(is_prime(19 ) ) self.assertTrue(is_prime(23 ) ) self.assertTrue(is_prime(29 ) ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: with self.assertRaises(_lowerCamelCase ): is_prime(-19 ) self.assertFalse( is_prime(0 ) , "Zero doesn\'t have any positive factors, primes must have exactly two." , ) self.assertFalse( is_prime(1 ) , "One only has 1 positive factor, primes must have exactly two." , ) self.assertFalse(is_prime(2 * 2 ) ) self.assertFalse(is_prime(2 * 3 ) ) self.assertFalse(is_prime(3 * 3 ) ) self.assertFalse(is_prime(3 * 5 ) ) self.assertFalse(is_prime(3 * 5 * 7 ) ) if __name__ == "__main__": unittest.main()
711
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''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 __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict[str, str]: return {self.text_column: "text", self.summary_column: "summary"}
51
0
"""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 lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" def get_masked_lm_array(lowercase_ ): _UpperCamelCase : Tuple = F'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' _UpperCamelCase : Tuple = tf.train.load_variable(__snake_case ,__snake_case ) if "kernel" in name: _UpperCamelCase : List[str] = array.transpose() return torch.from_numpy(__snake_case ) def get_encoder_array(lowercase_ ): _UpperCamelCase : Optional[Any] = F'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' _UpperCamelCase : Union[str, Any] = tf.train.load_variable(__snake_case ,__snake_case ) if "kernel" in name: _UpperCamelCase : Optional[int] = array.transpose() return torch.from_numpy(__snake_case ) def get_encoder_layer_array(lowercase_ ,lowercase_ ): _UpperCamelCase : Dict = F'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' _UpperCamelCase : Optional[int] = tf.train.load_variable(__snake_case ,__snake_case ) if "kernel" in name: _UpperCamelCase : Any = array.transpose() return torch.from_numpy(__snake_case ) def get_encoder_attention_layer_array(lowercase_ ,lowercase_ ,lowercase_ ): _UpperCamelCase : List[Any] = F'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' _UpperCamelCase : Optional[Any] = tf.train.load_variable(__snake_case ,__snake_case ) _UpperCamelCase : Union[str, Any] = array.reshape(__snake_case ) if "kernel" in name: _UpperCamelCase : Optional[Any] = array.transpose() return torch.from_numpy(__snake_case ) print(F'''Loading model based on config from {config_path}...''' ) _UpperCamelCase : Optional[Any] = BertConfig.from_json_file(__snake_case ) _UpperCamelCase : Any = BertForMaskedLM(__snake_case ) # Layers for layer_index in range(0 ,config.num_hidden_layers ): _UpperCamelCase : BertLayer = model.bert.encoder.layer[layer_index] # Self-attention _UpperCamelCase : BertSelfAttention = layer.attention.self _UpperCamelCase : Union[str, Any] = get_encoder_attention_layer_array( __snake_case ,"_query_dense/kernel" ,self_attn.query.weight.data.shape ) _UpperCamelCase : Any = get_encoder_attention_layer_array( __snake_case ,"_query_dense/bias" ,self_attn.query.bias.data.shape ) _UpperCamelCase : Optional[Any] = get_encoder_attention_layer_array( __snake_case ,"_key_dense/kernel" ,self_attn.key.weight.data.shape ) _UpperCamelCase : Tuple = get_encoder_attention_layer_array( __snake_case ,"_key_dense/bias" ,self_attn.key.bias.data.shape ) _UpperCamelCase : Any = get_encoder_attention_layer_array( __snake_case ,"_value_dense/kernel" ,self_attn.value.weight.data.shape ) _UpperCamelCase : Optional[Any] = get_encoder_attention_layer_array( __snake_case ,"_value_dense/bias" ,self_attn.value.bias.data.shape ) # Self-attention Output _UpperCamelCase : BertSelfOutput = layer.attention.output _UpperCamelCase : Optional[Any] = get_encoder_attention_layer_array( __snake_case ,"_output_dense/kernel" ,self_output.dense.weight.data.shape ) _UpperCamelCase : Tuple = get_encoder_attention_layer_array( __snake_case ,"_output_dense/bias" ,self_output.dense.bias.data.shape ) _UpperCamelCase : Any = get_encoder_layer_array(__snake_case ,"_attention_layer_norm/gamma" ) _UpperCamelCase : Dict = get_encoder_layer_array(__snake_case ,"_attention_layer_norm/beta" ) # Intermediate _UpperCamelCase : BertIntermediate = layer.intermediate _UpperCamelCase : Optional[int] = get_encoder_layer_array(__snake_case ,"_intermediate_dense/kernel" ) _UpperCamelCase : Union[str, Any] = get_encoder_layer_array(__snake_case ,"_intermediate_dense/bias" ) # Output _UpperCamelCase : BertOutput = layer.output _UpperCamelCase : Any = get_encoder_layer_array(__snake_case ,"_output_dense/kernel" ) _UpperCamelCase : Any = get_encoder_layer_array(__snake_case ,"_output_dense/bias" ) _UpperCamelCase : Any = get_encoder_layer_array(__snake_case ,"_output_layer_norm/gamma" ) _UpperCamelCase : Any = get_encoder_layer_array(__snake_case ,"_output_layer_norm/beta" ) # Embeddings _UpperCamelCase : Dict = get_encoder_array("_position_embedding_layer/embeddings" ) _UpperCamelCase : Any = get_encoder_array("_type_embedding_layer/embeddings" ) _UpperCamelCase : Dict = get_encoder_array("_embedding_norm_layer/gamma" ) _UpperCamelCase : List[str] = get_encoder_array("_embedding_norm_layer/beta" ) # LM Head _UpperCamelCase : Any = model.cls.predictions.transform _UpperCamelCase : List[str] = get_masked_lm_array("dense/kernel" ) _UpperCamelCase : Optional[int] = get_masked_lm_array("dense/bias" ) _UpperCamelCase : List[Any] = get_masked_lm_array("layer_norm/gamma" ) _UpperCamelCase : Optional[Any] = get_masked_lm_array("layer_norm/beta" ) _UpperCamelCase : Optional[Any] = get_masked_lm_array("embedding_table" ) # Pooling _UpperCamelCase : Union[str, Any] = BertPooler(config=__snake_case ) _UpperCamelCase : BertPooler = get_encoder_array("_pooler_layer/kernel" ) _UpperCamelCase : BertPooler = get_encoder_array("_pooler_layer/bias" ) # Export final model model.save_pretrained(__snake_case ) # Integration test - should load without any errors ;) _UpperCamelCase : str = BertForMaskedLM.from_pretrained(__snake_case ) print(new_model.eval() ) print("Model conversion was done sucessfully!" ) if __name__ == "__main__": lowerCamelCase__ = 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.", ) lowerCamelCase__ = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
712
"""simple docstring""" def lowercase__ ( lowercase_ ) -> set: """simple docstring""" _UpperCamelCase : Union[str, Any] = set() # edges = list of graph's edges _UpperCamelCase : Union[str, Any] = get_edges(lowercase_ ) # 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: _UpperCamelCase, _UpperCamelCase : str = edges.pop() chosen_vertices.add(lowercase_ ) chosen_vertices.add(lowercase_ ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(lowercase_ ) return chosen_vertices def lowercase__ ( lowercase_ ) -> set: """simple docstring""" _UpperCamelCase : List[str] = 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)}")
51
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase__ = { "configuration_mgp_str": ["MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP", "MgpstrConfig"], "processing_mgp_str": ["MgpstrProcessor"], "tokenization_mgp_str": ["MgpstrTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST", "MgpstrModel", "MgpstrPreTrainedModel", "MgpstrForSceneTextRecognition", ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
713
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCamelCase__ = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["OwlViTFeatureExtractor"] lowerCamelCase__ = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
51
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} # See all BART models at https://huggingface.co/models?filter=bart lowerCamelCase__ = { "vocab_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json", }, "merges_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt", }, "tokenizer_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json", }, } lowerCamelCase__ = { "facebook/bart-base": 1024, "facebook/bart-large": 1024, "facebook/bart-large-mnli": 1024, "facebook/bart-large-cnn": 1024, "facebook/bart-large-xsum": 1024, "yjernite/bart_eli5": 1024, } class __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[Any] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ :List[str] = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ :Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ :List[Any] = ["input_ids", "attention_mask"] SCREAMING_SNAKE_CASE__ :Any = BartTokenizer def __init__( self : str , __a : Optional[Any]=None , __a : List[Any]=None , __a : Optional[int]=None , __a : int="replace" , __a : str="<s>" , __a : Tuple="</s>" , __a : Dict="</s>" , __a : Union[str, Any]="<s>" , __a : int="<unk>" , __a : Tuple="<pad>" , __a : Union[str, Any]="<mask>" , __a : Any=False , __a : Optional[int]=True , **__a : List[str] , ) -> str: super().__init__( __A , __A , tokenizer_file=__A , errors=__A , bos_token=__A , eos_token=__A , sep_token=__A , cls_token=__A , unk_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , trim_offsets=__A , **__A , ) _UpperCamelCase : Any = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , __A ) != add_prefix_space: _UpperCamelCase : Optional[Any] = getattr(__A , pre_tok_state.pop("type" ) ) _UpperCamelCase : List[Any] = add_prefix_space _UpperCamelCase : List[Any] = pre_tok_class(**__A ) _UpperCamelCase : int = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` _UpperCamelCase : Optional[int] = "post_processor" _UpperCamelCase : Union[str, Any] = getattr(self.backend_tokenizer , __A , __A ) if tokenizer_component_instance: _UpperCamelCase : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _UpperCamelCase : Dict = tuple(state["sep"] ) if "cls" in state: _UpperCamelCase : List[str] = tuple(state["cls"] ) _UpperCamelCase : Union[str, Any] = False if state.get("add_prefix_space" , __A ) != add_prefix_space: _UpperCamelCase : str = add_prefix_space _UpperCamelCase : Optional[Any] = True if state.get("trim_offsets" , __A ) != trim_offsets: _UpperCamelCase : Union[str, Any] = trim_offsets _UpperCamelCase : List[str] = True if changes_to_apply: _UpperCamelCase : str = getattr(__A , state.pop("type" ) ) _UpperCamelCase : List[Any] = component_class(**__A ) setattr(self.backend_tokenizer , __A , __A ) @property def __SCREAMING_SNAKE_CASE ( self : int ) -> str: if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : List[str] ) -> str: _UpperCamelCase : Tuple = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else value _UpperCamelCase : str = value def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , *__a : Any , **__a : Tuple ) -> BatchEncoding: _UpperCamelCase : Dict = kwargs.get("is_split_into_words" , __A ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__A , **__A ) def __SCREAMING_SNAKE_CASE ( self : str , *__a : List[Any] , **__a : str ) -> BatchEncoding: _UpperCamelCase : Union[str, Any] = kwargs.get("is_split_into_words" , __A ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*__A , **__A ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: _UpperCamelCase : List[Any] = self._tokenizer.model.save(__A , name=__A ) return tuple(__A ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : Dict , __a : int=None ) -> Any: _UpperCamelCase : Optional[int] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __SCREAMING_SNAKE_CASE ( self : Any , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: _UpperCamelCase : Any = [self.sep_token_id] _UpperCamelCase : List[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]
714
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowercase__ ( lowercase_ = 1_000_000 ,lowercase_ = 10 ) -> int: """simple docstring""" _UpperCamelCase : defaultdict = defaultdict(lowercase_ ) for outer_width in range(3 ,(t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: _UpperCamelCase : Any = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) ,1 ) else: _UpperCamelCase : str = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowercase_ ,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() = }""")
51
0
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE ( __UpperCAmelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :int = (DDIMParallelScheduler,) SCREAMING_SNAKE_CASE__ :Optional[Any] = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def __SCREAMING_SNAKE_CASE ( self : List[str] , **__a : Optional[Any] ) -> Any: _UpperCamelCase : Tuple = { "num_train_timesteps": 1000, "beta_start": 0.00_01, "beta_end": 0.02, "beta_schedule": "linear", "clip_sample": True, } config.update(**__SCREAMING_SNAKE_CASE ) return config def __SCREAMING_SNAKE_CASE ( self : Dict , **__a : Dict ) -> List[str]: _UpperCamelCase : Union[str, Any] = self.scheduler_classes[0] _UpperCamelCase : List[str] = self.get_scheduler_config(**__SCREAMING_SNAKE_CASE ) _UpperCamelCase : int = scheduler_class(**__SCREAMING_SNAKE_CASE ) _UpperCamelCase, _UpperCamelCase : Optional[Any] = 10, 0.0 _UpperCamelCase : Any = self.dummy_model() _UpperCamelCase : List[Any] = self.dummy_sample_deter scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) for t in scheduler.timesteps: _UpperCamelCase : Any = model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) _UpperCamelCase : List[Any] = scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).prev_sample return sample def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=__SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> str: for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__SCREAMING_SNAKE_CASE ) _UpperCamelCase : Optional[Any] = self.scheduler_classes[0] _UpperCamelCase : Union[str, Any] = self.get_scheduler_config(steps_offset=1 ) _UpperCamelCase : Any = scheduler_class(**__SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__SCREAMING_SNAKE_CASE , beta_end=__SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=__SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : str ) -> int: for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: self.check_over_configs(thresholding=__SCREAMING_SNAKE_CASE ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__SCREAMING_SNAKE_CASE , prediction_type=__SCREAMING_SNAKE_CASE , sample_max_value=__SCREAMING_SNAKE_CASE , ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[int]: for t in [1, 10, 49]: self.check_over_forward(time_step=__SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=__SCREAMING_SNAKE_CASE , num_inference_steps=__SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__SCREAMING_SNAKE_CASE , eta=__SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: _UpperCamelCase : List[Any] = self.scheduler_classes[0] _UpperCamelCase : Tuple = self.get_scheduler_config() _UpperCamelCase : Tuple = scheduler_class(**__SCREAMING_SNAKE_CASE ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.1_47_71 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.3_24_60 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.0_09_79 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1e-5 def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: _UpperCamelCase : Optional[Any] = self.scheduler_classes[0] _UpperCamelCase : int = self.get_scheduler_config() _UpperCamelCase : Optional[Any] = scheduler_class(**__SCREAMING_SNAKE_CASE ) _UpperCamelCase, _UpperCamelCase : Dict = 10, 0.0 scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) _UpperCamelCase : Any = self.dummy_model() _UpperCamelCase : Dict = self.dummy_sample_deter _UpperCamelCase : Optional[Any] = self.dummy_sample_deter + 0.1 _UpperCamelCase : Dict = self.dummy_sample_deter - 0.1 _UpperCamelCase : Optional[int] = samplea.shape[0] _UpperCamelCase : Tuple = torch.stack([samplea, samplea, samplea] , dim=0 ) _UpperCamelCase : str = torch.arange(__SCREAMING_SNAKE_CASE )[0:3, None].repeat(1 , __SCREAMING_SNAKE_CASE ) _UpperCamelCase : List[Any] = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) _UpperCamelCase : List[str] = scheduler.batch_step_no_noise(__SCREAMING_SNAKE_CASE , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __SCREAMING_SNAKE_CASE ) _UpperCamelCase : List[Any] = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) _UpperCamelCase : str = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 1147.7904 ) < 1e-2 assert abs(result_mean.item() - 0.49_82 ) < 1e-3 def __SCREAMING_SNAKE_CASE ( self : Any ) -> str: _UpperCamelCase : Optional[Any] = self.full_loop() _UpperCamelCase : Tuple = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) _UpperCamelCase : str = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 172.0067 ) < 1e-2 assert abs(result_mean.item() - 0.22_39_67 ) < 1e-3 def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: _UpperCamelCase : Optional[int] = self.full_loop(prediction_type="v_prediction" ) _UpperCamelCase : str = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) _UpperCamelCase : List[Any] = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 52.53_02 ) < 1e-2 assert abs(result_mean.item() - 0.06_84 ) < 1e-3 def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: _UpperCamelCase : Dict = self.full_loop(set_alpha_to_one=__SCREAMING_SNAKE_CASE , beta_start=0.01 ) _UpperCamelCase : Optional[int] = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) _UpperCamelCase : Any = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 149.8295 ) < 1e-2 assert abs(result_mean.item() - 0.19_51 ) < 1e-3 def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: _UpperCamelCase : List[str] = self.full_loop(set_alpha_to_one=__SCREAMING_SNAKE_CASE , beta_start=0.01 ) _UpperCamelCase : Optional[Any] = torch.sum(torch.abs(__SCREAMING_SNAKE_CASE ) ) _UpperCamelCase : str = torch.mean(torch.abs(__SCREAMING_SNAKE_CASE ) ) assert abs(result_sum.item() - 149.0784 ) < 1e-2 assert abs(result_mean.item() - 0.19_41 ) < 1e-3
715
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar lowerCamelCase__ = TypeVar("KEY") lowerCamelCase__ = TypeVar("VAL") @dataclass(frozen=_UpperCamelCase , slots=_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( Generic[KEY, VAL] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :KEY SCREAMING_SNAKE_CASE__ :VAL class __SCREAMING_SNAKE_CASE ( _Item ): '''simple docstring''' def __init__( self : List[str] ) -> None: super().__init__(__a , __a ) def __bool__( self : Dict ) -> bool: return False lowerCamelCase__ = _DeletedItem() class __SCREAMING_SNAKE_CASE ( MutableMapping[KEY, VAL] ): '''simple docstring''' def __init__( self : int , __a : int = 8 , __a : float = 0.75 ) -> None: _UpperCamelCase : str = initial_block_size _UpperCamelCase : list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 _UpperCamelCase : List[str] = capacity_factor _UpperCamelCase : Dict = 0 def __SCREAMING_SNAKE_CASE ( self : int , __a : KEY ) -> int: return hash(__a ) % len(self._buckets ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : int ) -> int: return (ind + 1) % len(self._buckets ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : int , __a : KEY , __a : VAL ) -> bool: _UpperCamelCase : List[Any] = self._buckets[ind] if not stored: _UpperCamelCase : Tuple = _Item(__a , __a ) self._len += 1 return True elif stored.key == key: _UpperCamelCase : Union[str, Any] = _Item(__a , __a ) return True else: return False def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> bool: _UpperCamelCase : Any = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False _UpperCamelCase : List[str] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : int ) -> None: _UpperCamelCase : Any = self._buckets _UpperCamelCase : List[Any] = [None] * new_size _UpperCamelCase : List[str] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __SCREAMING_SNAKE_CASE ( self : int ) -> None: self._resize(len(self._buckets ) * 2 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: self._resize(len(self._buckets ) // 2 ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : KEY ) -> Iterator[int]: _UpperCamelCase : str = self._get_bucket_index(__a ) for _ in range(len(self._buckets ) ): yield ind _UpperCamelCase : Tuple = self._get_next_ind(__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : KEY , __a : VAL ) -> None: for ind in self._iterate_buckets(__a ): if self._try_set(__a , __a , __a ): break def __setitem__( self : int , __a : KEY , __a : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(__a , __a ) def __delitem__( self : str , __a : KEY ) -> None: for ind in self._iterate_buckets(__a ): _UpperCamelCase : Tuple = self._buckets[ind] if item is None: raise KeyError(__a ) if item is _deleted: continue if item.key == key: _UpperCamelCase : List[Any] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : str , __a : KEY ) -> VAL: for ind in self._iterate_buckets(__a ): _UpperCamelCase : Tuple = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__a ) def __len__( self : List[Any] ) -> int: return self._len def __iter__( self : List[str] ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : List[str] ) -> str: _UpperCamelCase : Optional[int] = " ,".join( F'''{item.key}: {item.val}''' for item in self._buckets if item ) return F'''HashMap({val_string})'''
51
0
"""simple docstring""" import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class __SCREAMING_SNAKE_CASE ( UpperCamelCase_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = (DPMSolverSDEScheduler,) SCREAMING_SNAKE_CASE__ :Dict = 10 def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , **__a : List[Any] ) -> int: _UpperCamelCase : Optional[int] = { 'num_train_timesteps': 1100, 'beta_start': 0.00_01, 'beta_end': 0.02, 'beta_schedule': 'linear', 'noise_sampler_seed': 0, } config.update(**__a ) return config def __SCREAMING_SNAKE_CASE ( self : Dict ) -> int: for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=__a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Dict: for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01] , [0.00_02, 0.0_02, 0.02] ): self.check_over_configs(beta_start=__a , beta_end=__a ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__a ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: _UpperCamelCase : Tuple = self.scheduler_classes[0] _UpperCamelCase : Optional[int] = self.get_scheduler_config() _UpperCamelCase : Dict = scheduler_class(**__a ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase : Dict = self.dummy_model() _UpperCamelCase : Tuple = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase : int = sample.to(__a ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase : List[str] = scheduler.scale_model_input(__a , __a ) _UpperCamelCase : Optional[int] = model(__a , __a ) _UpperCamelCase : List[Any] = scheduler.step(__a , __a , __a ) _UpperCamelCase : str = output.prev_sample _UpperCamelCase : Any = torch.sum(torch.abs(__a ) ) _UpperCamelCase : int = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_67.47_82_10_44_92_18_75 ) < 1e-2 assert abs(result_mean.item() - 0.21_78_70_59_64_56_52_77 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_71.59_35_21_11_81_64_06 ) < 1e-2 assert abs(result_mean.item() - 0.2_23_42_90_68_92_29_96_52 ) < 1e-3 else: assert abs(result_sum.item() - 1_62.52_38_34_22_85_15_62 ) < 1e-2 assert abs(result_mean.item() - 0.2_11_61_95_70_85_13_26 ) < 1e-3 def __SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: _UpperCamelCase : Tuple = self.scheduler_classes[0] _UpperCamelCase : int = self.get_scheduler_config(prediction_type="v_prediction" ) _UpperCamelCase : Dict = scheduler_class(**__a ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCamelCase : Union[str, Any] = self.dummy_model() _UpperCamelCase : Any = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCamelCase : Dict = sample.to(__a ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase : int = scheduler.scale_model_input(__a , __a ) _UpperCamelCase : Optional[Any] = model(__a , __a ) _UpperCamelCase : Tuple = scheduler.step(__a , __a , __a ) _UpperCamelCase : Optional[int] = output.prev_sample _UpperCamelCase : Optional[int] = torch.sum(torch.abs(__a ) ) _UpperCamelCase : Tuple = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_24.77_14_92_00_43_94_53 ) < 1e-2 assert abs(result_mean.item() - 0.1_62_26_28_90_14_81_62_84 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_28.1_66_33_60_59_57_03 ) < 1e-2 assert abs(result_mean.item() - 0.1_66_88_32_60_01_16_72_97 ) < 1e-3 else: assert abs(result_sum.item() - 1_19.8_48_75_48_82_81_25 ) < 1e-2 assert abs(result_mean.item() - 0.15_60_53_06_62_53_66_21 ) < 1e-3 def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: _UpperCamelCase : Dict = self.scheduler_classes[0] _UpperCamelCase : Dict = self.get_scheduler_config() _UpperCamelCase : List[str] = scheduler_class(**__a ) scheduler.set_timesteps(self.num_inference_steps , device=__a ) _UpperCamelCase : Dict = self.dummy_model() _UpperCamelCase : str = self.dummy_sample_deter.to(__a ) * scheduler.init_noise_sigma for t in scheduler.timesteps: _UpperCamelCase : Optional[int] = scheduler.scale_model_input(__a , __a ) _UpperCamelCase : Tuple = model(__a , __a ) _UpperCamelCase : Dict = scheduler.step(__a , __a , __a ) _UpperCamelCase : Union[str, Any] = output.prev_sample _UpperCamelCase : Tuple = torch.sum(torch.abs(__a ) ) _UpperCamelCase : Optional[int] = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_67.46_95_73_97_46_09_38 ) < 1e-2 assert abs(result_mean.item() - 0.2_18_05_93_46_07_98_26_35 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_71.59_35_36_37_69_53_12 ) < 1e-2 assert abs(result_mean.item() - 0.2_23_42_90_83_82_41_57_71 ) < 1e-3 else: assert abs(result_sum.item() - 1_62.52_38_34_22_85_15_62 ) < 1e-2 assert abs(result_mean.item() - 0.2_11_61_95_70_85_13_26 ) < 1e-3 def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: _UpperCamelCase : Union[str, Any] = self.scheduler_classes[0] _UpperCamelCase : str = self.get_scheduler_config() _UpperCamelCase : Optional[int] = scheduler_class(**__a , use_karras_sigmas=__a ) scheduler.set_timesteps(self.num_inference_steps , device=__a ) _UpperCamelCase : int = self.dummy_model() _UpperCamelCase : List[Any] = self.dummy_sample_deter.to(__a ) * scheduler.init_noise_sigma _UpperCamelCase : Any = sample.to(__a ) for t in scheduler.timesteps: _UpperCamelCase : List[Any] = scheduler.scale_model_input(__a , __a ) _UpperCamelCase : Optional[Any] = model(__a , __a ) _UpperCamelCase : Union[str, Any] = scheduler.step(__a , __a , __a ) _UpperCamelCase : List[Any] = output.prev_sample _UpperCamelCase : Optional[Any] = torch.sum(torch.abs(__a ) ) _UpperCamelCase : Tuple = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 1_76.66_97_41_35_74_21_88 ) < 1e-2 assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 1_77.63_65_35_64_45_31_25 ) < 1e-2 assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11 ) < 1e-2 else: assert abs(result_sum.item() - 1_70.3_13_52_23_38_86_72 ) < 1e-2 assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11 ) < 1e-2
716
"""simple docstring""" class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , __a : list[int] ) -> None: _UpperCamelCase : Tuple = len(__a ) _UpperCamelCase : Dict = [0] * len_array if len_array > 0: _UpperCamelCase : Optional[Any] = array[0] for i in range(1 , __a ): _UpperCamelCase : Tuple = self.prefix_sum[i - 1] + array[i] def __SCREAMING_SNAKE_CASE ( self : Dict , __a : int , __a : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : int ) -> bool: _UpperCamelCase : int = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(__a ) return False if __name__ == "__main__": import doctest doctest.testmod()
51
0
"""simple docstring""" from ...processing_utils import ProcessorMixin class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Union[str, Any] = ["image_processor", "feature_extractor"] SCREAMING_SNAKE_CASE__ :List[str] = "TvltImageProcessor" SCREAMING_SNAKE_CASE__ :List[Any] = "TvltFeatureExtractor" def __init__( self : List[str] , __a : List[Any] , __a : List[str] ) -> List[str]: super().__init__(image_processor=__A , feature_extractor=__A ) _UpperCamelCase : Optional[Any] = image_processor _UpperCamelCase : Any = feature_extractor def __call__( self : List[str] , __a : Any=None , __a : Any=None , __a : Optional[int]=None , __a : str=None , __a : List[Any]=False , __a : Tuple=False , *__a : List[str] , **__a : Optional[Any] , ) -> Optional[Any]: if images is None and audio is None: raise ValueError("You need to specify either an `images` or `audio` input to process." ) _UpperCamelCase : int = None if images is not None: _UpperCamelCase : Optional[int] = self.image_processor(__A , mask_pixel=__A , *__A , **__A ) if images_mixed is not None: _UpperCamelCase : Optional[Any] = self.image_processor(__A , is_mixed=__A , *__A , **__A ) if audio is not None: _UpperCamelCase : Dict = self.feature_extractor( __A , *__A , sampling_rate=__A , mask_audio=__A , **__A ) _UpperCamelCase : Optional[int] = {} if audio is not None: output_dict.update(__A ) if images is not None: output_dict.update(__A ) if images_mixed_dict is not None: output_dict.update(__A ) return output_dict @property def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: _UpperCamelCase : Any = self.image_processor.model_input_names _UpperCamelCase : Tuple = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
717
"""simple docstring""" import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def lowercase__ ( lowercase_ ,lowercase_=7 ) -> Tuple: """simple docstring""" _UpperCamelCase : Optional[int] = None if token is not None: _UpperCamelCase : Optional[Any] = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} # The id of a workflow (not of a workflow run) _UpperCamelCase : Any = "636036" _UpperCamelCase : Tuple = F'''https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs''' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'''?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}''' _UpperCamelCase : Dict = requests.get(lowercase_ ,headers=lowercase_ ).json() return result["workflow_runs"] def lowercase__ ( lowercase_ ) -> List[str]: """simple docstring""" _UpperCamelCase : List[Any] = get_daily_ci_runs(lowercase_ ) _UpperCamelCase : Tuple = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": _UpperCamelCase : Union[str, Any] = workflow_run["id"] break return workflow_run_id def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Optional[int]: """simple docstring""" _UpperCamelCase : str = get_last_daily_ci_runs(lowercase_ ) if workflow_run_id is not None: _UpperCamelCase : int = get_artifacts_links(worflow_run_id=lowercase_ ,token=lowercase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: _UpperCamelCase : Dict = artifacts_links[artifact_name] download_artifact( artifact_name=lowercase_ ,artifact_url=lowercase_ ,output_dir=lowercase_ ,token=lowercase_ ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> int: """simple docstring""" get_last_daily_ci_artifacts(lowercase_ ,lowercase_ ,lowercase_ ) _UpperCamelCase : Dict = {} for artifact_name in artifact_names: _UpperCamelCase : Union[str, Any] = os.path.join(lowercase_ ,F'''{artifact_name}.zip''' ) if os.path.isfile(lowercase_ ): _UpperCamelCase : int = {} with zipfile.ZipFile(lowercase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowercase_ ): # read the file with z.open(lowercase_ ) as f: _UpperCamelCase : int = f.read().decode("UTF-8" ) return results
51
0
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() 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
718
"""simple docstring""" import math class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Any , __a : list[list[float]] , __a : list[int] ) -> int: _UpperCamelCase : List[Any] = 0.0 _UpperCamelCase : Union[str, Any] = 0.0 for i in range(len(__a ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : list[list[int | float]] , __a : list[int] , __a : int , __a : float ) -> list[list[int | float]]: for i in range(len(__a ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def lowercase__ ( ) -> None: """simple docstring""" _UpperCamelCase : Optional[int] = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) _UpperCamelCase : List[str] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training _UpperCamelCase : List[Any] = SelfOrganizingMap() _UpperCamelCase : int = 3 _UpperCamelCase : List[Any] = 0.5 for _ in range(lowercase_ ): for j in range(len(lowercase_ ) ): # training sample _UpperCamelCase : int = training_samples[j] # Compute the winning vector _UpperCamelCase : Tuple = self_organizing_map.get_winner(lowercase_ ,lowercase_ ) # Update the winning vector _UpperCamelCase : int = self_organizing_map.update(lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) # classify test sample _UpperCamelCase : Optional[int] = [0, 0, 0, 1] _UpperCamelCase : Dict = self_organizing_map.get_winner(lowercase_ ,lowercase_ ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
51
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase__ = { 'configuration_graphormer': ['GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GraphormerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ 'GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'GraphormerForGraphClassification', 'GraphormerModel', 'GraphormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
719
"""simple docstring""" import argparse import collections import os import re 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/check_table.py lowerCamelCase__ = "src/transformers" lowerCamelCase__ = "docs/source/en" lowerCamelCase__ = "." def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> List[str]: """simple docstring""" with open(lowercase_ ,"r" ,encoding="utf-8" ,newline="\n" ) as f: _UpperCamelCase : Union[str, Any] = f.readlines() # Find the start prompt. _UpperCamelCase : Dict = 0 while not lines[start_index].startswith(lowercase_ ): start_index += 1 start_index += 1 _UpperCamelCase : Optional[int] = start_index while not lines[end_index].startswith(lowercase_ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | lowerCamelCase__ = "Model|Encoder|Decoder|ForConditionalGeneration" # 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)") # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase__ = direct_transformers_import(TRANSFORMERS_PATH) def lowercase__ ( lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Tuple = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)" ,lowercase_ ) return [m.group(0 ) for m in matches] def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : str = 2 if text == "✅" or text == "❌" else len(lowercase_ ) _UpperCamelCase : Union[str, Any] = (width - text_length) // 2 _UpperCamelCase : Dict = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def lowercase__ ( ) -> str: """simple docstring""" _UpperCamelCase : Optional[Any] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _UpperCamelCase : str = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } _UpperCamelCase : Dict = {name: config.replace("Config" ,"" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. _UpperCamelCase : int = collections.defaultdict(lowercase_ ) _UpperCamelCase : Dict = collections.defaultdict(lowercase_ ) _UpperCamelCase : Dict = collections.defaultdict(lowercase_ ) _UpperCamelCase : int = collections.defaultdict(lowercase_ ) _UpperCamelCase : str = collections.defaultdict(lowercase_ ) # Let's lookup through all transformers object (once). for attr_name in dir(lowercase_ ): _UpperCamelCase : List[str] = None if attr_name.endswith("Tokenizer" ): _UpperCamelCase : Tuple = slow_tokenizers _UpperCamelCase : Any = attr_name[:-9] elif attr_name.endswith("TokenizerFast" ): _UpperCamelCase : Optional[Any] = fast_tokenizers _UpperCamelCase : List[str] = attr_name[:-13] elif _re_tf_models.match(lowercase_ ) is not None: _UpperCamelCase : List[Any] = tf_models _UpperCamelCase : Dict = _re_tf_models.match(lowercase_ ).groups()[0] elif _re_flax_models.match(lowercase_ ) is not None: _UpperCamelCase : Dict = flax_models _UpperCamelCase : Union[str, Any] = _re_flax_models.match(lowercase_ ).groups()[0] elif _re_pt_models.match(lowercase_ ) is not None: _UpperCamelCase : Optional[int] = pt_models _UpperCamelCase : Any = _re_pt_models.match(lowercase_ ).groups()[0] if lookup_dict is not None: while len(lowercase_ ) > 0: if attr_name in model_name_to_prefix.values(): _UpperCamelCase : Dict = True break # Try again after removing the last word in the name _UpperCamelCase : List[str] = "".join(camel_case_split(lowercase_ )[:-1] ) # Let's build that table! _UpperCamelCase : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) _UpperCamelCase : List[str] = ["Model", "Tokenizer slow", "Tokenizer fast", "PyTorch support", "TensorFlow support", "Flax Support"] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). _UpperCamelCase : Union[str, Any] = [len(lowercase_ ) + 2 for c in columns] _UpperCamelCase : Any = max([len(lowercase_ ) for name in model_names] ) + 2 # Build the table per se _UpperCamelCase : Tuple = "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for c, w in zip(lowercase_ ,lowercase_ )] ) + "|\n" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths] ) + "|\n" _UpperCamelCase : Union[str, Any] = {True: "✅", False: "❌"} for name in model_names: _UpperCamelCase : Optional[int] = model_name_to_prefix[name] _UpperCamelCase : Tuple = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for l, w in zip(lowercase_ ,lowercase_ )] ) + "|\n" return table def lowercase__ ( lowercase_=False ) -> List[Any]: """simple docstring""" _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : str = _find_text_in_file( filename=os.path.join(lowercase_ ,"index.md" ) ,start_prompt="<!--This table is updated automatically from the auto modules" ,end_prompt="<!-- End table-->" ,) _UpperCamelCase : Any = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(lowercase_ ,"index.md" ) ,"w" ,encoding="utf-8" ,newline="\n" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( "The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this." ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") lowerCamelCase__ = parser.parse_args() check_model_table(args.fix_and_overwrite)
51
0
"""simple docstring""" import argparse import torch # Step 1. clone https://github.com/microsoft/unilm # Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd # Step 3. cd unilm # Step 4. ln -s $(realpath wavlm/modules.py) ./ # create simlink # import classes from unilm.wavlm.WavLM import WavLM as WavLMOrig from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig from transformers import WavLMConfig, WavLMModel, logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn.grep_linear": "encoder.layers.*.attention.gru_rel_pos_linear", "self_attn.relative_attention_bias": "encoder.layers.*.attention.rel_attn_embed", "self_attn.grep_a": "encoder.layers.*.attention.gru_rel_pos_const", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "ctc_proj", "mask_emb": "masked_spec_embed", } lowerCamelCase__ = [ "ctc_proj", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) -> int: """simple docstring""" for attribute in key.split("." ): _UpperCamelCase : Tuple = getattr(lowerCAmelCase__ ,lowerCAmelCase__ ) if weight_type is not None: _UpperCamelCase : Union[str, Any] = getattr(lowerCAmelCase__ ,lowerCAmelCase__ ).shape else: _UpperCamelCase : List[Any] = 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 : Optional[Any] = value elif weight_type == "weight_g": _UpperCamelCase : int = value elif weight_type == "weight_v": _UpperCamelCase : Dict = value elif weight_type == "bias": _UpperCamelCase : Optional[Any] = value else: _UpperCamelCase : str = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Optional[int] = [] _UpperCamelCase : List[str] = fairseq_model.state_dict() _UpperCamelCase : List[Any] = hf_model.feature_extractor for name, value in fairseq_dict.items(): _UpperCamelCase : List[Any] = False if "conv_layers" in name: load_conv_layer( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,hf_model.config.feat_extract_norm == "group" ,) _UpperCamelCase : int = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: _UpperCamelCase : List[Any] = True if "*" in mapped_key: _UpperCamelCase : List[Any] = name.split(lowerCAmelCase__ )[0].split("." )[-2] _UpperCamelCase : Union[str, Any] = mapped_key.replace("*" ,lowerCAmelCase__ ) if "weight_g" in name: _UpperCamelCase : int = "weight_g" elif "weight_v" in name: _UpperCamelCase : List[str] = "weight_v" elif "bias" in name and "relative_attention_bias" not in name: _UpperCamelCase : Any = "bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj _UpperCamelCase : Optional[int] = "weight" else: _UpperCamelCase : List[Any] = None set_recursively(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) continue if not is_used: unused_weights.append(lowerCAmelCase__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) -> List[str]: """simple docstring""" _UpperCamelCase : Any = full_name.split("conv_layers." )[-1] _UpperCamelCase : Any = name.split("." ) _UpperCamelCase : Union[str, Any] = int(items[0] ) _UpperCamelCase : int = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) _UpperCamelCase : List[str] = 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 : List[Any] = 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 : Optional[Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) _UpperCamelCase : Any = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowerCAmelCase__ ) @torch.no_grad() def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_=None ) -> str: """simple docstring""" _UpperCamelCase : List[str] = torch.load(lowerCAmelCase__ ) _UpperCamelCase : List[Any] = WavLMConfigOrig(checkpoint["cfg"] ) _UpperCamelCase : Tuple = WavLMOrig(lowerCAmelCase__ ) model.load_state_dict(checkpoint["model"] ) model.eval() if config_path is not None: _UpperCamelCase : int = WavLMConfig.from_pretrained(lowerCAmelCase__ ) else: _UpperCamelCase : List[str] = WavLMConfig() _UpperCamelCase : Union[str, Any] = WavLMModel(lowerCAmelCase__ ) recursively_load_weights(lowerCAmelCase__ ,lowerCAmelCase__ ) hf_wavlm.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") lowerCamelCase__ = parser.parse_args() convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
720
"""simple docstring""" from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. lowerCamelCase__ = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. lowerCamelCase__ = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. lowerCamelCase__ = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def lowercase__ ( lowercase_ ,lowercase_ ) -> tuple[str, float]: """simple docstring""" _UpperCamelCase : str = len([g for position, g in enumerate(lowercase_ ) if g == main_target[position]] ) return (item, float(lowercase_ )) def lowercase__ ( lowercase_ ,lowercase_ ) -> tuple[str, str]: """simple docstring""" _UpperCamelCase : Tuple = random.randint(0 ,len(lowercase_ ) - 1 ) _UpperCamelCase : Dict = parent_a[:random_slice] + parent_a[random_slice:] _UpperCamelCase : Tuple = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def lowercase__ ( lowercase_ ,lowercase_ ) -> str: """simple docstring""" _UpperCamelCase : int = list(lowercase_ ) if random.uniform(0 ,1 ) < MUTATION_PROBABILITY: _UpperCamelCase : int = random.choice(lowercase_ ) return "".join(lowercase_ ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,) -> list[str]: """simple docstring""" _UpperCamelCase : Optional[Any] = [] # Generate more children proportionally to the fitness score. _UpperCamelCase : List[str] = int(parent_a[1] * 100 ) + 1 _UpperCamelCase : Union[str, Any] = 10 if child_n >= 10 else child_n for _ in range(lowercase_ ): _UpperCamelCase : Dict = population_score[random.randint(0 ,lowercase_ )][0] _UpperCamelCase, _UpperCamelCase : Dict = crossover(parent_a[0] ,lowercase_ ) # Append new string to the population list. pop.append(mutate(lowercase_ ,lowercase_ ) ) pop.append(mutate(lowercase_ ,lowercase_ ) ) return pop def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ = True ) -> tuple[int, int, str]: """simple docstring""" if N_POPULATION < N_SELECTED: _UpperCamelCase : List[str] = F'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(lowercase_ ) # Verify that the target contains no genes besides the ones inside genes variable. _UpperCamelCase : int = sorted({c for c in target if c not in genes} ) if not_in_genes_list: _UpperCamelCase : int = F'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(lowercase_ ) # Generate random starting population. _UpperCamelCase : Union[str, Any] = [] for _ in range(lowercase_ ): population.append("".join([random.choice(lowercase_ ) for i in range(len(lowercase_ ) )] ) ) # Just some logs to know what the algorithms is doing. _UpperCamelCase, _UpperCamelCase : str = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowercase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. _UpperCamelCase : int = [evaluate(lowercase_ ,lowercase_ ) for item in population] # Check if there is a matching evolution. _UpperCamelCase : Optional[Any] = sorted(lowercase_ ,key=lambda lowercase_ : x[1] ,reverse=lowercase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'''\nGeneration: {generation}''' F'''\nTotal Population:{total_population}''' F'''\nBest score: {population_score[0][1]}''' F'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. _UpperCamelCase : str = population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowercase_ ) # Normalize population score to be between 0 and 1. _UpperCamelCase : str = [ (item, score / len(lowercase_ )) for item, score in population_score ] # This is selection for i in range(lowercase_ ): population.extend(select(population_score[int(lowercase_ )] ,lowercase_ ,lowercase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowercase_ ) > N_POPULATION: break if __name__ == "__main__": lowerCamelCase__ = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) lowerCamelCase__ = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = basic(target_str, genes_list) print( f"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}""" )
51
0
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef lowerCamelCase__ = ( """This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate """ """library. You can have a look at this example script for pointers: """ """https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py""" ) def lowercase__ ( lowercase_ ,lowercase_ ) -> int: """simple docstring""" warnings.warn(_lowerCamelCase ,_lowerCamelCase ) requires_backends(_lowerCamelCase ,"sklearn" ) return (preds == labels).mean() def lowercase__ ( lowercase_ ,lowercase_ ) -> Dict: """simple docstring""" warnings.warn(_lowerCamelCase ,_lowerCamelCase ) requires_backends(_lowerCamelCase ,"sklearn" ) _UpperCamelCase : Optional[int] = simple_accuracy(_lowerCamelCase ,_lowerCamelCase ) _UpperCamelCase : str = fa_score(y_true=_lowerCamelCase ,y_pred=_lowerCamelCase ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def lowercase__ ( lowercase_ ,lowercase_ ) -> Optional[int]: """simple docstring""" warnings.warn(_lowerCamelCase ,_lowerCamelCase ) requires_backends(_lowerCamelCase ,"sklearn" ) _UpperCamelCase : Union[str, Any] = pearsonr(_lowerCamelCase ,_lowerCamelCase )[0] _UpperCamelCase : Tuple = spearmanr(_lowerCamelCase ,_lowerCamelCase )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Tuple: """simple docstring""" warnings.warn(_lowerCamelCase ,_lowerCamelCase ) requires_backends(_lowerCamelCase ,"sklearn" ) assert len(_lowerCamelCase ) == len(_lowerCamelCase ), F'''Predictions and labels have mismatched lengths {len(_lowerCamelCase )} and {len(_lowerCamelCase )}''' if task_name == "cola": return {"mcc": matthews_corrcoef(_lowerCamelCase ,_lowerCamelCase )} elif task_name == "sst-2": return {"acc": simple_accuracy(_lowerCamelCase ,_lowerCamelCase )} elif task_name == "mrpc": return acc_and_fa(_lowerCamelCase ,_lowerCamelCase ) elif task_name == "sts-b": return pearson_and_spearman(_lowerCamelCase ,_lowerCamelCase ) elif task_name == "qqp": return acc_and_fa(_lowerCamelCase ,_lowerCamelCase ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(_lowerCamelCase ,_lowerCamelCase )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(_lowerCamelCase ,_lowerCamelCase )} elif task_name == "qnli": return {"acc": simple_accuracy(_lowerCamelCase ,_lowerCamelCase )} elif task_name == "rte": return {"acc": simple_accuracy(_lowerCamelCase ,_lowerCamelCase )} elif task_name == "wnli": return {"acc": simple_accuracy(_lowerCamelCase ,_lowerCamelCase )} elif task_name == "hans": return {"acc": simple_accuracy(_lowerCamelCase ,_lowerCamelCase )} else: raise KeyError(_lowerCamelCase ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Tuple: """simple docstring""" warnings.warn(_lowerCamelCase ,_lowerCamelCase ) requires_backends(_lowerCamelCase ,"sklearn" ) if len(_lowerCamelCase ) != len(_lowerCamelCase ): raise ValueError(F'''Predictions and labels have mismatched lengths {len(_lowerCamelCase )} and {len(_lowerCamelCase )}''' ) if task_name == "xnli": return {"acc": simple_accuracy(_lowerCamelCase ,_lowerCamelCase )} else: raise KeyError(_lowerCamelCase )
721
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = ["model.decoder.embed_positions.weights"] def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" if "emb" in name: _UpperCamelCase : List[str] = name.replace("emb" ,"model.decoder.embed_tokens" ) if "transformer" in name: _UpperCamelCase : Optional[int] = name.replace("transformer" ,"model.decoder" ) if "cross_attention" in name: _UpperCamelCase : Optional[int] = name.replace("cross_attention" ,"encoder_attn" ) if "linear1" in name: _UpperCamelCase : Optional[Any] = name.replace("linear1" ,"fc1" ) if "linear2" in name: _UpperCamelCase : Union[str, Any] = name.replace("linear2" ,"fc2" ) if "norm1" in name: _UpperCamelCase : Optional[Any] = name.replace("norm1" ,"self_attn_layer_norm" ) if "norm_cross" in name: _UpperCamelCase : Dict = name.replace("norm_cross" ,"encoder_attn_layer_norm" ) if "norm2" in name: _UpperCamelCase : Union[str, Any] = name.replace("norm2" ,"final_layer_norm" ) if "out_norm" in name: _UpperCamelCase : Union[str, Any] = name.replace("out_norm" ,"model.decoder.layer_norm" ) if "linears" in name: _UpperCamelCase : List[str] = name.replace("linears" ,"lm_heads" ) if "condition_provider.conditioners.description.output_proj" in name: _UpperCamelCase : Any = name.replace("condition_provider.conditioners.description.output_proj" ,"enc_to_dec_proj" ) return name def lowercase__ ( lowercase_ ,lowercase_ ) -> Tuple[Dict, Dict]: """simple docstring""" _UpperCamelCase : str = list(state_dict.keys() ) _UpperCamelCase : Optional[Any] = {} for key in keys: _UpperCamelCase : Optional[int] = state_dict.pop(lowercase_ ) _UpperCamelCase : List[Any] = rename_keys(lowercase_ ) if "in_proj_weight" in key: # split fused qkv proj _UpperCamelCase : Tuple = val[:hidden_size, :] _UpperCamelCase : Optional[Any] = val[hidden_size : 2 * hidden_size, :] _UpperCamelCase : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _UpperCamelCase : Optional[Any] = val else: _UpperCamelCase : List[str] = val return state_dict, enc_dec_proj_state_dict def lowercase__ ( lowercase_ ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values _UpperCamelCase : List[Any] = 1_024 _UpperCamelCase : List[str] = 24 _UpperCamelCase : Any = 16 elif checkpoint == "medium": _UpperCamelCase : Tuple = 1_536 _UpperCamelCase : Dict = 48 _UpperCamelCase : Tuple = 24 elif checkpoint == "large": _UpperCamelCase : int = 2_048 _UpperCamelCase : Optional[int] = 48 _UpperCamelCase : Dict = 32 else: raise ValueError(F'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' ) _UpperCamelCase : str = MusicgenDecoderConfig( hidden_size=lowercase_ ,ffn_dim=hidden_size * 4 ,num_hidden_layers=lowercase_ ,num_attention_heads=lowercase_ ,) return config @torch.no_grad() def lowercase__ ( lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_="cpu" ) -> List[str]: """simple docstring""" _UpperCamelCase : str = MusicGen.get_pretrained(lowercase_ ,device=lowercase_ ) _UpperCamelCase : Union[str, Any] = decoder_config_from_checkpoint(lowercase_ ) _UpperCamelCase : Optional[int] = fairseq_model.lm.state_dict() _UpperCamelCase, _UpperCamelCase : Optional[Any] = rename_state_dict( lowercase_ ,hidden_size=decoder_config.hidden_size ) _UpperCamelCase : Tuple = TaEncoderModel.from_pretrained("t5-base" ) _UpperCamelCase : Union[str, Any] = EncodecModel.from_pretrained("facebook/encodec_32khz" ) _UpperCamelCase : str = MusicgenForCausalLM(lowercase_ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _UpperCamelCase, _UpperCamelCase : str = decoder.load_state_dict(lowercase_ ,strict=lowercase_ ) for key in missing_keys.copy(): if key.startswith(("text_encoder", "audio_encoder") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(lowercase_ ) if len(lowercase_ ) > 0: raise ValueError(F'''Missing key(s) in state_dict: {missing_keys}''' ) if len(lowercase_ ) > 0: raise ValueError(F'''Unexpected key(s) in state_dict: {unexpected_keys}''' ) # init the composite model _UpperCamelCase : str = MusicgenForConditionalGeneration(text_encoder=lowercase_ ,audio_encoder=lowercase_ ,decoder=lowercase_ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(lowercase_ ) # check we can do a forward pass _UpperCamelCase : List[str] = torch.arange(0 ,8 ,dtype=torch.long ).reshape(2 ,-1 ) _UpperCamelCase : Dict = input_ids.reshape(2 * 4 ,-1 ) with torch.no_grad(): _UpperCamelCase : Tuple = model(input_ids=lowercase_ ,decoder_input_ids=lowercase_ ).logits if logits.shape != (8, 1, 2_048): raise ValueError("Incorrect shape for logits" ) # now construct the processor _UpperCamelCase : int = AutoTokenizer.from_pretrained("t5-base" ) _UpperCamelCase : str = AutoFeatureExtractor.from_pretrained("facebook/encodec_32khz" ,padding_side="left" ) _UpperCamelCase : Optional[int] = MusicgenProcessor(feature_extractor=lowercase_ ,tokenizer=lowercase_ ) # set the appropriate bos/pad token ids _UpperCamelCase : str = 2_048 _UpperCamelCase : str = 2_048 # set other default generation config params _UpperCamelCase : Optional[Any] = int(30 * audio_encoder.config.frame_rate ) _UpperCamelCase : List[str] = True _UpperCamelCase : int = 3.0 if pytorch_dump_folder is not None: Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) logger.info(F'''Saving model {checkpoint} to {pytorch_dump_folder}''' ) model.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) if repo_id: logger.info(F'''Pushing model {checkpoint} to {repo_id}''' ) model.push_to_hub(lowercase_ ) processor.push_to_hub(lowercase_ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) lowerCamelCase__ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
51
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} lowerCamelCase__ = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } lowerCamelCase__ = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class __SCREAMING_SNAKE_CASE ( snake_case_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ :str = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ :List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ :List[str] = ["""input_ids""", """attention_mask"""] SCREAMING_SNAKE_CASE__ :Dict = GPTaTokenizer def __init__( self : List[Any] , __a : int=None , __a : Any=None , __a : Tuple=None , __a : Optional[int]="<|endoftext|>" , __a : str="<|endoftext|>" , __a : List[str]="<|endoftext|>" , __a : Optional[Any]=False , **__a : Optional[int] , ) -> Optional[int]: super().__init__( __a , __a , tokenizer_file=__a , unk_token=__a , bos_token=__a , eos_token=__a , add_prefix_space=__a , **__a , ) _UpperCamelCase : Union[str, Any] = kwargs.pop("add_bos_token" , __a ) _UpperCamelCase : Optional[int] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , __a ) != add_prefix_space: _UpperCamelCase : Optional[Any] = getattr(__a , pre_tok_state.pop("type" ) ) _UpperCamelCase : Optional[Any] = add_prefix_space _UpperCamelCase : Optional[int] = pre_tok_class(**__a ) _UpperCamelCase : Optional[int] = add_prefix_space def __SCREAMING_SNAKE_CASE ( self : Tuple , *__a : Union[str, Any] , **__a : Any ) -> Union[str, Any]: _UpperCamelCase : int = kwargs.get("is_split_into_words" , __a ) assert self.add_prefix_space or not is_split_into_words, ( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__a , **__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , *__a : List[Any] , **__a : Optional[Any] ) -> Dict: _UpperCamelCase : List[Any] = kwargs.get("is_split_into_words" , __a ) assert self.add_prefix_space or not is_split_into_words, ( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*__a , **__a ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : str , __a : Any = None ) -> Tuple: _UpperCamelCase : Optional[int] = self._tokenizer.model.save(__a , name=__a ) return tuple(__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : Optional[Any] ) -> List[Any]: _UpperCamelCase : List[Any] = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__a , add_special_tokens=__a ) + [self.eos_token_id] ) if len(__a ) > self.model_max_length: _UpperCamelCase : Optional[Any] = input_ids[-self.model_max_length :] return input_ids
700
"""simple docstring""" from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowerCamelCase__ = input("Enter image url: ").strip() print(f"""Downloading image from {url} ...""") lowerCamelCase__ = BeautifulSoup(requests.get(url).content, "html.parser") # The image URL is in the content field of the first meta tag with property og:image lowerCamelCase__ = soup.find("meta", {"property": "og:image"})["content"] lowerCamelCase__ = requests.get(image_url).content lowerCamelCase__ = f"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, "wb") as fp: fp.write(image_data) print(f"""Done. Image saved to disk as {file_name}.""")
51
0
"""simple docstring""" def lowercase__ ( lowercase_ ,lowercase_ ) -> List[str]: """simple docstring""" assert x is not None assert y is not None _UpperCamelCase : Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : Union[str, Any] = len(SCREAMING_SNAKE_CASE_ ) # declaring the array for storing the dp values _UpperCamelCase : int = [[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741 for i in range(1 ,m + 1 ): for j in range(1 ,n + 1 ): _UpperCamelCase : Any = 1 if x[i - 1] == y[j - 1] else 0 _UpperCamelCase : Optional[Any] = max(l[i - 1][j] ,l[i][j - 1] ,l[i - 1][j - 1] + match ) _UpperCamelCase : Optional[int] = "" _UpperCamelCase : int = m, n while i > 0 and j > 0: _UpperCamelCase : Any = 1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: _UpperCamelCase : List[str] = x[i - 1] + seq i -= 1 j -= 1 elif l[i][j] == l[i - 1][j]: i -= 1 else: j -= 1 return l[m][n], seq if __name__ == "__main__": lowerCamelCase__ = "AGGTAB" lowerCamelCase__ = "GXTXAYB" lowerCamelCase__ = 4 lowerCamelCase__ = "GTAB" lowerCamelCase__ , lowerCamelCase__ = longest_common_subsequence(a, b) print("len =", ln, ", sub-sequence =", subseq) import doctest doctest.testmod()
701
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append(".") def lowercase__ ( lowercase_ ) -> int: """simple docstring""" _UpperCamelCase : Any = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " F'''{test_file} instead.''' ) _UpperCamelCase : str = components[-1] if not test_fn.endswith("py" ): raise ValueError(F'''`test_file` should be a python file. Got {test_fn} instead.''' ) if not test_fn.startswith("test_modeling_" ): raise ValueError( F'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.''' ) _UpperCamelCase : Dict = components[:-1] + [test_fn.replace(".py" ,"" )] _UpperCamelCase : List[str] = ".".join(lowercase_ ) return test_module_path def lowercase__ ( lowercase_ ) -> List[Any]: """simple docstring""" _UpperCamelCase : Optional[Any] = get_module_path(lowercase_ ) _UpperCamelCase : str = importlib.import_module(lowercase_ ) return test_module def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : Union[str, Any] = [] _UpperCamelCase : List[Any] = get_test_module(lowercase_ ) for attr in dir(lowercase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowercase_ ,lowercase_ ) ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Tuple: """simple docstring""" _UpperCamelCase : Optional[Any] = [] _UpperCamelCase : Any = get_test_module(lowercase_ ) for attr in dir(lowercase_ ): _UpperCamelCase : int = getattr(lowercase_ ,lowercase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). _UpperCamelCase : Optional[Any] = getattr(lowercase_ ,"all_model_classes" ,[] ) if len(lowercase_ ) > 0: test_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Dict = get_test_classes(lowercase_ ) _UpperCamelCase : int = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : List[str] = test_class() if hasattr(lowercase_ ,"setUp" ): test.setUp() _UpperCamelCase : Tuple = None if hasattr(lowercase_ ,"model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: _UpperCamelCase : Tuple = test.model_tester.__class__ return model_tester def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : str = get_test_classes(lowercase_ ) _UpperCamelCase : Dict = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ,lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : Any = get_test_classes_for_model(lowercase_ ,lowercase_ ) _UpperCamelCase : List[Any] = [] for test_class in test_classes: _UpperCamelCase : List[Any] = get_model_tester_from_test_class(lowercase_ ) if tester_class is not None: tester_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Any = get_test_classes(lowercase_ ) _UpperCamelCase : Tuple = {test_class: get_model_tester_from_test_class(lowercase_ ) for test_class in test_classes} return test_tester_mapping def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : List[Any] = get_model_classes(lowercase_ ) _UpperCamelCase : Optional[int] = { model_class: get_test_classes_for_model(lowercase_ ,lowercase_ ) for model_class in model_classes } return model_test_mapping def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Optional[Any] = get_model_classes(lowercase_ ) _UpperCamelCase : Tuple = { model_class: get_tester_classes_for_model(lowercase_ ,lowercase_ ) for model_class in model_classes } return model_to_tester_mapping def lowercase__ ( lowercase_ ) -> Optional[int]: """simple docstring""" if isinstance(lowercase_ ,lowercase_ ): return o elif isinstance(lowercase_ ,lowercase_ ): return o.__name__ elif isinstance(lowercase_ ,(list, tuple) ): return [to_json(lowercase_ ) for x in o] elif isinstance(lowercase_ ,lowercase_ ): return {to_json(lowercase_ ): to_json(lowercase_ ) for k, v in o.items()} else: return o
51
0
# 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 lowerCamelCase__ = "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 lowercase__ ( ) -> Optional[int]: """simple docstring""" _UpperCamelCase : Dict = _ask_options( "In which compute environment are you running?" ,["This machine", "AWS (Amazon SageMaker)"] ,_convert_compute_environment ,) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: _UpperCamelCase : Dict = get_sagemaker_input() else: _UpperCamelCase : Tuple = get_cluster_input() return config def lowercase__ ( lowercase_=None ) -> Optional[int]: """simple docstring""" if subparsers is not None: _UpperCamelCase : Any = subparsers.add_parser("config" ,description=SCREAMING_SNAKE_CASE_ ) else: _UpperCamelCase : Optional[Any] = argparse.ArgumentParser("Accelerate config command" ,description=SCREAMING_SNAKE_CASE_ ) parser.add_argument( "--config_file" ,default=SCREAMING_SNAKE_CASE_ ,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=SCREAMING_SNAKE_CASE_ ) return parser def lowercase__ ( lowercase_ ) -> int: """simple docstring""" _UpperCamelCase : List[Any] = get_user_input() if args.config_file is not None: _UpperCamelCase : Union[str, Any] = args.config_file else: if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): os.makedirs(SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : Optional[Any] = default_yaml_config_file if config_file.endswith(".json" ): config.to_json_file(SCREAMING_SNAKE_CASE_ ) else: config.to_yaml_file(SCREAMING_SNAKE_CASE_ ) print(F'''accelerate configuration saved at {config_file}''' ) def lowercase__ ( ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Optional[Any] = config_command_parser() _UpperCamelCase : Tuple = parser.parse_args() config_command(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
702
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure)
51
0
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class __SCREAMING_SNAKE_CASE : SCREAMING_SNAKE_CASE__ :Optional[Any] = None SCREAMING_SNAKE_CASE__ :Optional[Any] = None SCREAMING_SNAKE_CASE__ :Optional[int] = None # sigma(t_i) @classmethod def __SCREAMING_SNAKE_CASE ( cls : Optional[int] ) -> List[str]: return cls() @dataclass class __SCREAMING_SNAKE_CASE ( __A ): SCREAMING_SNAKE_CASE__ :Any = 42 SCREAMING_SNAKE_CASE__ :List[Any] = 42 SCREAMING_SNAKE_CASE__ :str = 42 class __SCREAMING_SNAKE_CASE ( __A , __A ): @property def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: return True @register_to_config def __init__( self : Any , __a : Any = 0.02 , __a : Dict = 100 , __a : Tuple = 1.0_07 , __a : Optional[int] = 80 , __a : Dict = 0.05 , __a : int = 50 , ) -> Optional[int]: pass def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: return KarrasVeSchedulerState.create() def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : Tuple , __a : int , __a : List[Any] = () ) -> List[str]: _UpperCamelCase : Optional[Any] = jnp.arange(0 , __a )[::-1].copy() _UpperCamelCase : Union[str, Any] = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=__a , schedule=jnp.array(__a , dtype=jnp.floataa ) , timesteps=__a , ) def __SCREAMING_SNAKE_CASE ( self : str , __a : Tuple , __a : List[Any] , __a : Optional[Any] , __a : Optional[int] , ) -> Tuple: if self.config.s_min <= sigma <= self.config.s_max: _UpperCamelCase : Optional[Any] = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: _UpperCamelCase : int = 0 # sample eps ~ N(0, S_noise^2 * I) _UpperCamelCase : List[Any] = random.split(__a , num=1 ) _UpperCamelCase : Tuple = self.config.s_noise * random.normal(key=__a , shape=sample.shape ) _UpperCamelCase : Optional[int] = sigma + gamma * sigma _UpperCamelCase : int = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def __SCREAMING_SNAKE_CASE ( self : str , __a : Dict , __a : List[str] , __a : Dict , __a : List[Any] , __a : Any , __a : List[Any] = True , ) -> Tuple: _UpperCamelCase : List[str] = sample_hat + sigma_hat * model_output _UpperCamelCase : str = (sample_hat - pred_original_sample) / sigma_hat _UpperCamelCase : Tuple = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=__a , derivative=__a , state=__a ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : Optional[Any] , __a : Dict , __a : Optional[Any] , __a : int , __a : List[str] , __a : List[Any] , __a : Union[str, Any] , __a : List[Any] = True , ) -> Dict: _UpperCamelCase : Any = sample_prev + sigma_prev * model_output _UpperCamelCase : Optional[int] = (sample_prev - pred_original_sample) / sigma_prev _UpperCamelCase : List[Any] = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=__a , derivative=__a , state=__a ) def __SCREAMING_SNAKE_CASE ( self : int , __a : Any , __a : Tuple , __a : List[Any] , __a : Any ) -> List[Any]: raise NotImplementedError()
703
"""simple docstring""" lowerCamelCase__ = "\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCamelCase__ = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase__ = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
51
0
"""simple docstring""" import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class __SCREAMING_SNAKE_CASE ( __lowercase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[int] = ComputeEnvironment.AMAZON_SAGEMAKER SCREAMING_SNAKE_CASE__ :Any = True SCREAMING_SNAKE_CASE__ :List[Any] = "ml.p3.2xlarge" SCREAMING_SNAKE_CASE__ :int = "accelerate_sagemaker_execution_role" SCREAMING_SNAKE_CASE__ :List[str] = "hf-sm" SCREAMING_SNAKE_CASE__ :Dict = "us-east-1" SCREAMING_SNAKE_CASE__ :Optional[int] = 1 SCREAMING_SNAKE_CASE__ :Tuple = "accelerate-sagemaker-1" SCREAMING_SNAKE_CASE__ :str = "1.6" SCREAMING_SNAKE_CASE__ :Tuple = "4.4" SCREAMING_SNAKE_CASE__ :str = "train.py" SCREAMING_SNAKE_CASE__ :Tuple = [ "--model_name_or_path", "bert", "--do_train", "False", "--epochs", "3", "--learning_rate", "5e-5", "--max_steps", "50.5", ] SCREAMING_SNAKE_CASE__ :Any = [ "--model_name_or_path", "bert", "--do_train", "--do_test", "False", "--do_predict", "--epochs", "3", "--learning_rate", "5e-5", "--max_steps", "50.5", ] class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: # If no defaults are changed, `to_kwargs` returns an empty dict. _UpperCamelCase : List[str] = _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args ) assert isinstance(converted_args["model_name_or_path"] , _A ) assert isinstance(converted_args["do_train"] , _A ) assert isinstance(converted_args["epochs"] , _A ) assert isinstance(converted_args["learning_rate"] , _A ) assert isinstance(converted_args["max_steps"] , _A ) with pytest.raises(_A ): _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args )
704
"""simple docstring""" import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: _UpperCamelCase : Tuple = tempfile.mkdtemp() _UpperCamelCase : str = 5 # Realm tok _UpperCamelCase : Tuple = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "test", "question", "this", "is", "the", "first", "second", "third", "fourth", "fifth", "record", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _UpperCamelCase : Optional[int] = os.path.join(self.tmpdirname , "realm_tokenizer" ) os.makedirs(__a , exist_ok=__a ) _UpperCamelCase : Optional[Any] = os.path.join(__a , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) _UpperCamelCase : Optional[int] = os.path.join(self.tmpdirname , "realm_block_records" ) os.makedirs(__a , exist_ok=__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , "realm_tokenizer" ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: shutil.rmtree(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: _UpperCamelCase : Optional[Any] = RealmConfig(num_block_records=self.num_block_records ) return config def __SCREAMING_SNAKE_CASE ( self : int ) -> int: _UpperCamelCase : Any = Dataset.from_dict( { "id": ["0", "1"], "question": ["foo", "bar"], "answers": [["Foo", "Bar"], ["Bar"]], } ) return dataset def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: _UpperCamelCase : int = np.array( [ b"This is the first record", b"This is the second record", b"This is the third record", b"This is the fourth record", b"This is the fifth record", b"This is a longer longer longer record", ] , dtype=__a , ) return block_records def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: _UpperCamelCase : List[str] = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: _UpperCamelCase : Tuple = self.get_config() _UpperCamelCase : int = self.get_dummy_retriever() _UpperCamelCase : Tuple = retriever.tokenizer _UpperCamelCase : List[str] = np.array([0, 3] , dtype="long" ) _UpperCamelCase : Union[str, Any] = tokenizer(["Test question"] ).input_ids _UpperCamelCase : List[str] = tokenizer( ["the fourth"] , add_special_tokens=__a , return_token_type_ids=__a , return_attention_mask=__a , ).input_ids _UpperCamelCase : str = config.reader_seq_len _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : List[Any] = retriever( __a , __a , answer_ids=__a , max_length=__a , return_tensors="np" ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "first", "record", "[SEP]"] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "fourth", "record", "[SEP]"] , ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: _UpperCamelCase : Any = self.get_config() _UpperCamelCase : Dict = self.get_dummy_retriever() _UpperCamelCase : Dict = retriever.tokenizer _UpperCamelCase : List[Any] = np.array([0, 3, 5] , dtype="long" ) _UpperCamelCase : Optional[int] = tokenizer(["Test question"] ).input_ids _UpperCamelCase : str = tokenizer( ["the fourth", "longer longer"] , add_special_tokens=__a , return_token_type_ids=__a , return_attention_mask=__a , ).input_ids _UpperCamelCase : Union[str, Any] = config.reader_seq_len _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : Optional[Any] = retriever( __a , __a , answer_ids=__a , max_length=__a , return_tensors="np" ) self.assertEqual([False, True, True] , __a ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , __a ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , __a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: _UpperCamelCase : List[Any] = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) # Test local path _UpperCamelCase : int = retriever.from_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) self.assertEqual(retriever.block_records[0] , b"This is the first record" ) # Test mocked remote path with patch("transformers.models.realm.retrieval_realm.hf_hub_download" ) as mock_hf_hub_download: _UpperCamelCase : List[Any] = os.path.join( os.path.join(self.tmpdirname , "realm_block_records" ) , _REALM_BLOCK_RECORDS_FILENAME ) _UpperCamelCase : int = RealmRetriever.from_pretrained("google/realm-cc-news-pretrained-openqa" ) self.assertEqual(retriever.block_records[0] , b"This is the first record" )
51
0
"""simple docstring""" import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) -> Any: """simple docstring""" if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ): _UpperCamelCase : Tuple = np.full((len(lowerCAmelCase__ ), sequence_length, 2) ,lowerCAmelCase__ ) else: _UpperCamelCase : str = np.full((len(lowerCAmelCase__ ), sequence_length) ,lowerCAmelCase__ ) for i, tensor in enumerate(lowerCAmelCase__ ): if padding_side == "right": if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ): _UpperCamelCase : Optional[int] = tensor[:sequence_length] else: _UpperCamelCase : Union[str, Any] = tensor[:sequence_length] else: if isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ): _UpperCamelCase : List[Any] = tensor[:sequence_length] else: _UpperCamelCase : Union[str, Any] = tensor[:sequence_length] return out_tensor.tolist() def lowercase__ ( lowercase_ ) -> str: """simple docstring""" _UpperCamelCase : Dict = ord(lowerCAmelCase__ ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True _UpperCamelCase : Optional[Any] = unicodedata.category(lowerCAmelCase__ ) if cat.startswith("P" ): return True return False @dataclass class __SCREAMING_SNAKE_CASE ( __a ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :PreTrainedTokenizerBase SCREAMING_SNAKE_CASE__ :Union[bool, str, PaddingStrategy] = True SCREAMING_SNAKE_CASE__ :Optional[int] = None SCREAMING_SNAKE_CASE__ :Optional[int] = None SCREAMING_SNAKE_CASE__ :int = -100 SCREAMING_SNAKE_CASE__ :str = "pt" def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : List[str] ) -> List[str]: import torch _UpperCamelCase : Tuple = "label" if "label" in features[0].keys() else "labels" _UpperCamelCase : Optional[Any] = [feature[label_name] for feature in features] if label_name in features[0].keys() else None _UpperCamelCase : Dict = self.tokenizer.pad( snake_case__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" if labels is None else None , ) if labels is None: return batch _UpperCamelCase : Any = torch.tensor(batch["entity_ids"] ).shape[1] _UpperCamelCase : Union[str, Any] = self.tokenizer.padding_side if padding_side == "right": _UpperCamelCase : Dict = [ list(snake_case__ ) + [self.label_pad_token_id] * (sequence_length - len(snake_case__ )) for label in labels ] else: _UpperCamelCase : int = [ [self.label_pad_token_id] * (sequence_length - len(snake_case__ )) + list(snake_case__ ) for label in labels ] _UpperCamelCase : Any = [feature["ner_tags"] for feature in features] _UpperCamelCase : List[Any] = padding_tensor(snake_case__ , -1 , snake_case__ , snake_case__ ) _UpperCamelCase : str = [feature["original_entity_spans"] for feature in features] _UpperCamelCase : List[str] = padding_tensor(snake_case__ , (-1, -1) , snake_case__ , snake_case__ ) _UpperCamelCase : Optional[int] = {k: torch.tensor(snake_case__ , dtype=torch.intaa ) for k, v in batch.items()} return batch
705
"""simple docstring""" from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class __SCREAMING_SNAKE_CASE : '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = LEDConfig SCREAMING_SNAKE_CASE__ :str = {} SCREAMING_SNAKE_CASE__ :List[str] = "gelu" def __init__( self : List[Any] , __a : Union[str, Any] , __a : List[Any]=13 , __a : int=7 , __a : str=True , __a : Any=False , __a : str=99 , __a : str=32 , __a : Union[str, Any]=2 , __a : Optional[Any]=4 , __a : List[Any]=37 , __a : List[Any]=0.1 , __a : Tuple=0.1 , __a : Dict=20 , __a : str=2 , __a : Dict=1 , __a : Any=0 , __a : List[Any]=4 , ) -> List[Any]: _UpperCamelCase : Optional[Any] = parent _UpperCamelCase : List[str] = batch_size _UpperCamelCase : str = seq_length _UpperCamelCase : str = is_training _UpperCamelCase : Any = use_labels _UpperCamelCase : Any = vocab_size _UpperCamelCase : List[str] = hidden_size _UpperCamelCase : Optional[Any] = num_hidden_layers _UpperCamelCase : Dict = num_attention_heads _UpperCamelCase : Optional[Any] = intermediate_size _UpperCamelCase : int = hidden_dropout_prob _UpperCamelCase : Dict = attention_probs_dropout_prob _UpperCamelCase : str = max_position_embeddings _UpperCamelCase : int = eos_token_id _UpperCamelCase : Dict = pad_token_id _UpperCamelCase : Optional[Any] = bos_token_id _UpperCamelCase : str = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after _UpperCamelCase : List[str] = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests _UpperCamelCase : int = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __SCREAMING_SNAKE_CASE ( self : int ) -> str: _UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _UpperCamelCase : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _UpperCamelCase : Tuple = tf.concat([input_ids, eos_tensor] , axis=1 ) _UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase : List[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) _UpperCamelCase : Dict = prepare_led_inputs_dict(__a , __a , __a ) _UpperCamelCase : Union[str, Any] = tf.concat( [tf.zeros_like(__a )[:, :-1], tf.ones_like(__a )[:, -1:]] , axis=-1 , ) _UpperCamelCase : Union[str, Any] = global_attention_mask return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : List[Any] , __a : int ) -> Tuple: _UpperCamelCase : Tuple = TFLEDModel(config=__a ).get_decoder() _UpperCamelCase : Tuple = inputs_dict["input_ids"] _UpperCamelCase : int = input_ids[:1, :] _UpperCamelCase : List[str] = inputs_dict["attention_mask"][:1, :] _UpperCamelCase : List[Any] = 1 # first forward pass _UpperCamelCase : Any = model(__a , attention_mask=__a , use_cache=__a ) _UpperCamelCase, _UpperCamelCase : Union[str, Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _UpperCamelCase : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) _UpperCamelCase : Any = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _UpperCamelCase : List[str] = tf.concat([input_ids, next_tokens] , axis=-1 ) _UpperCamelCase : Union[str, Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _UpperCamelCase : Tuple = model(__a , attention_mask=__a )[0] _UpperCamelCase : int = model(__a , attention_mask=__a , past_key_values=__a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _UpperCamelCase : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _UpperCamelCase : List[str] = output_from_no_past[:, -3:, random_slice_idx] _UpperCamelCase : Optional[int] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__a , __a , rtol=1e-3 ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_=None ,lowercase_=None ,) -> Dict: """simple docstring""" if attention_mask is None: _UpperCamelCase : str = tf.cast(tf.math.not_equal(lowercase_ ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: _UpperCamelCase : str = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: _UpperCamelCase : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _UpperCamelCase : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :List[str] = (TFLEDForConditionalGeneration,) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :List[str] = ( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ :Tuple = True SCREAMING_SNAKE_CASE__ :str = False SCREAMING_SNAKE_CASE__ :Optional[Any] = False SCREAMING_SNAKE_CASE__ :int = False def __SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: _UpperCamelCase : int = TFLEDModelTester(self ) _UpperCamelCase : Any = ConfigTester(self , config_class=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: _UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__a ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase, _UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase : Optional[int] = tf.zeros_like(inputs_dict["attention_mask"] ) _UpperCamelCase : Union[str, Any] = 2 _UpperCamelCase : str = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) _UpperCamelCase : Dict = True _UpperCamelCase : str = self.model_tester.seq_length _UpperCamelCase : Union[str, Any] = self.model_tester.encoder_seq_length def check_decoder_attentions_output(__a : Optional[int] ): _UpperCamelCase : Optional[int] = outputs.decoder_attentions self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(__a : Optional[Any] ): _UpperCamelCase : Union[str, Any] = [t.numpy() for t in outputs.encoder_attentions] _UpperCamelCase : List[Any] = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: _UpperCamelCase : Dict = True _UpperCamelCase : Optional[Any] = False _UpperCamelCase : int = False _UpperCamelCase : Optional[int] = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) _UpperCamelCase : Any = len(__a ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) if self.is_encoder_decoder: _UpperCamelCase : Optional[Any] = model_class(__a ) _UpperCamelCase : List[Any] = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_decoder_attentions_output(__a ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _UpperCamelCase : int = True _UpperCamelCase : Tuple = model_class(__a ) _UpperCamelCase : str = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) # Check attention is always last and order is fine _UpperCamelCase : Any = True _UpperCamelCase : List[str] = True _UpperCamelCase : Tuple = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__a ) ) self.assertEqual(model.config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: pass def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: # TODO: Head-masking not yet implement pass def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" return tf.constant(lowercase_ ,dtype=tf.intaa ) lowerCamelCase__ = 1E-4 @slow @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: _UpperCamelCase : Any = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here _UpperCamelCase : int = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Tuple = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Optional[Any] = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Optional[int] = model(**__a )[0] _UpperCamelCase : Optional[int] = (1, 1024, 768) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : Tuple = tf.convert_to_tensor( [[2.30_50, 2.82_79, 0.65_31], [-1.84_57, -0.14_55, -3.56_61], [-1.01_86, 0.45_86, -2.20_43]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> str: _UpperCamelCase : Optional[int] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here _UpperCamelCase : Optional[int] = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : List[str] = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Optional[Any] = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Union[str, Any] = model(**__a )[0] _UpperCamelCase : int = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : Optional[int] = tf.convert_to_tensor( [[33.65_07, 6.45_72, 16.80_89], [5.87_39, -2.42_38, 11.29_02], [-3.21_39, -4.31_49, 4.27_83]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 , rtol=1e-3 )
51
0
"""simple docstring""" import json import logging import os import sys from time import time from unittest.mock import patch from transformers.testing_utils import TestCasePlus, require_torch_tpu logging.basicConfig(level=logging.DEBUG) lowerCamelCase__ = logging.getLogger() def lowercase__ ( lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : Any = {} _UpperCamelCase : Optional[Any] = os.path.join(lowerCAmelCase_ ,"all_results.json" ) if os.path.exists(lowerCAmelCase_ ): with open(lowerCAmelCase_ ,"r" ) as f: _UpperCamelCase : List[Any] = json.load(lowerCAmelCase_ ) else: raise ValueError(F'''can\'t find {path}''' ) return results lowerCamelCase__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @require_torch_tpu class __SCREAMING_SNAKE_CASE ( __lowerCamelCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: import xla_spawn _UpperCamelCase : Optional[int] = self.get_auto_remove_tmp_dir() _UpperCamelCase : List[Any] = F''' ./examples/pytorch/text-classification/run_glue.py --num_cores=8 ./examples/pytorch/text-classification/run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --overwrite_output_dir --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --do_train --do_eval --debug tpu_metrics_debug --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --max_steps=10 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(a_ , "argv" , a_ ): _UpperCamelCase : Union[str, Any] = time() xla_spawn.main() _UpperCamelCase : Optional[Any] = time() _UpperCamelCase : int = get_results(a_ ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) # Assert that the script takes less than 500 seconds to make sure it doesn't hang. self.assertLess(end - start , 500 ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: import xla_spawn _UpperCamelCase : Optional[int] = "\n ./tests/test_trainer_tpu.py\n --num_cores=8\n ./tests/test_trainer_tpu.py\n ".split() with patch.object(a_ , "argv" , a_ ): xla_spawn.main()
706
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Union[str, Any] = RoCBertTokenizer SCREAMING_SNAKE_CASE__ :Dict = None SCREAMING_SNAKE_CASE__ :List[Any] = False SCREAMING_SNAKE_CASE__ :Union[str, Any] = True SCREAMING_SNAKE_CASE__ :Union[str, Any] = filter_non_english def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: super().setUp() _UpperCamelCase : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] _UpperCamelCase : List[str] = {} _UpperCamelCase : Tuple = {} for i, value in enumerate(__a ): _UpperCamelCase : List[str] = i _UpperCamelCase : Optional[Any] = i _UpperCamelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) _UpperCamelCase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(__a , __a , ensure_ascii=__a ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(__a , __a , ensure_ascii=__a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: _UpperCamelCase : Tuple = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : int = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(__a , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__a ) , [5, 6, 2, 5, 7, 8] ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: _UpperCamelCase : Dict = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: _UpperCamelCase : List[Any] = RoCBertBasicTokenizer(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 : Optional[Any] ) -> Tuple: _UpperCamelCase : Optional[Any] = RoCBertBasicTokenizer(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 : Dict ) -> str: _UpperCamelCase : Dict = RoCBertBasicTokenizer(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 : Union[str, Any] ) -> Union[str, Any]: _UpperCamelCase : List[str] = RoCBertBasicTokenizer(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[int]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase : Union[str, Any] = RoCBertBasicTokenizer(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 : Tuple ) -> List[Any]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(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 : Optional[Any] ) -> int: _UpperCamelCase : int = RoCBertBasicTokenizer(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 : List[str] ) -> Optional[Any]: _UpperCamelCase : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] _UpperCamelCase : Any = {} for i, token in enumerate(__a ): _UpperCamelCase : str = i _UpperCamelCase : Optional[int] = RoCBertWordpieceTokenizer(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 : Dict ) -> Optional[Any]: 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: 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 : Optional[int] ) -> Optional[int]: 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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = self.get_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]"]] ) if self.test_rust_tokenizer: _UpperCamelCase : Tuple = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__a ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Union[str, Any] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' _UpperCamelCase : Optional[Any] = tokenizer_r.encode_plus( __a , return_attention_mask=__a , return_token_type_ids=__a , return_offsets_mapping=__a , add_special_tokens=__a , ) _UpperCamelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(__a , "do_lower_case" ) else False _UpperCamelCase : Dict = ( [ ((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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = ["的", "人", "有"] _UpperCamelCase : int = "".join(__a ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = True _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : int = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : int = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : List[Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Union[str, Any] = 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 ) _UpperCamelCase : Any = False _UpperCamelCase : Dict = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Any = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Dict = tokenizer_p.convert_ids_to_tokens(__a ) # it is expected that only the first Chinese character is not preceded by "##". _UpperCamelCase : Any = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(__a ) ] self.assertListEqual(__a , __a ) self.assertListEqual(__a , __a ) @slow def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: _UpperCamelCase : Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : Optional[int] = tokenizer.encode("你好" , add_special_tokens=__a ) _UpperCamelCase : Dict = tokenizer.encode("你是谁" , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__a ) _UpperCamelCase : Tuple = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: _UpperCamelCase : Optional[Any] = self.get_tokenizers(do_lower_case=__a ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): _UpperCamelCase : int = "你好,你是谁" _UpperCamelCase : Any = tokenizer.tokenize(__a ) _UpperCamelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(__a ) _UpperCamelCase : List[str] = tokenizer.convert_tokens_to_shape_ids(__a ) _UpperCamelCase : Any = tokenizer.convert_tokens_to_pronunciation_ids(__a ) _UpperCamelCase : Optional[int] = tokenizer.prepare_for_model( __a , __a , __a , add_special_tokens=__a ) _UpperCamelCase : Tuple = tokenizer.encode_plus(__a , add_special_tokens=__a ) self.assertEqual(__a , __a )
51
0
"""simple docstring""" from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , __a : Optional[Any] , ) -> Dict: _UpperCamelCase : Any = parent _UpperCamelCase : Union[str, Any] = 13 _UpperCamelCase : Union[str, Any] = 7 _UpperCamelCase : Tuple = 30 _UpperCamelCase : Dict = self.seq_length + self.mem_len _UpperCamelCase : List[Any] = 15 _UpperCamelCase : Dict = True _UpperCamelCase : Any = True _UpperCamelCase : str = 99 _UpperCamelCase : List[Any] = [10, 50, 80] _UpperCamelCase : List[Any] = 32 _UpperCamelCase : Optional[int] = 32 _UpperCamelCase : str = 4 _UpperCamelCase : Any = 8 _UpperCamelCase : Union[str, Any] = 128 _UpperCamelCase : int = 2 _UpperCamelCase : str = 2 _UpperCamelCase : Any = None _UpperCamelCase : Tuple = 1 _UpperCamelCase : Optional[Any] = 0 _UpperCamelCase : Any = 3 _UpperCamelCase : Dict = self.vocab_size - 1 _UpperCamelCase : Optional[Any] = 0.01 def __SCREAMING_SNAKE_CASE ( self : str ) -> int: _UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase : Union[str, Any] = None if self.use_labels: _UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase : Dict = TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: random.seed(self.seed ) tf.random.set_seed(self.seed ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : int , __a : int , __a : Dict , __a : Tuple ) -> List[str]: _UpperCamelCase : str = TFTransfoXLModel(__a ) _UpperCamelCase, _UpperCamelCase : Tuple = model(__a ).to_tuple() _UpperCamelCase : Optional[int] = {"input_ids": input_ids_a, "mems": mems_a} _UpperCamelCase, _UpperCamelCase : List[Any] = model(__a ).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def __SCREAMING_SNAKE_CASE ( self : Any , __a : str , __a : Dict , __a : List[Any] , __a : List[str] ) -> List[Any]: _UpperCamelCase : Tuple = TFTransfoXLLMHeadModel(__a ) _UpperCamelCase, _UpperCamelCase : int = model(__a ).to_tuple() _UpperCamelCase : List[Any] = {"input_ids": input_ids_a, "labels": lm_labels} _UpperCamelCase, _UpperCamelCase : List[Any] = model(__a ).to_tuple() _UpperCamelCase, _UpperCamelCase : List[Any] = model([input_ids_a, mems_a] ).to_tuple() _UpperCamelCase : Any = {"input_ids": input_ids_a, "mems": mems_a, "labels": lm_labels} _UpperCamelCase, _UpperCamelCase : Any = model(__a ).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def __SCREAMING_SNAKE_CASE ( self : int , __a : Any , __a : Optional[Any] , __a : Tuple , __a : List[str] ) -> Optional[int]: _UpperCamelCase : List[Any] = TFTransfoXLForSequenceClassification(__a ) _UpperCamelCase : Optional[Any] = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: _UpperCamelCase : List[str] = self.prepare_config_and_inputs() ((_UpperCamelCase), (_UpperCamelCase), (_UpperCamelCase), (_UpperCamelCase)) : Optional[Any] = config_and_inputs _UpperCamelCase : List[str] = {"input_ids": input_ids_a} return config, inputs_dict @require_tf class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[Any] = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) SCREAMING_SNAKE_CASE__ :Tuple = () if is_tf_available() else () SCREAMING_SNAKE_CASE__ :Dict = ( { "feature-extraction": TFTransfoXLModel, "text-classification": TFTransfoXLForSequenceClassification, "text-generation": TFTransfoXLLMHeadModel, "zero-shot": TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented SCREAMING_SNAKE_CASE__ :Union[str, Any] = False SCREAMING_SNAKE_CASE__ :Tuple = False SCREAMING_SNAKE_CASE__ :Any = False SCREAMING_SNAKE_CASE__ :str = False def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : Optional[Any] , __a : Dict , __a : int , __a : Tuple , __a : Dict ) -> int: if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: _UpperCamelCase : int = TFTransfoXLModelTester(self ) _UpperCamelCase : List[Any] = ConfigTester(self , config_class=__a , d_embed=37 ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: self.model_tester.set_seed() _UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> str: self.model_tester.set_seed() _UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*__a ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: _UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*__a ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: _UpperCamelCase, _UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase : Tuple = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: _UpperCamelCase : Any = model_class(__a ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: _UpperCamelCase : Union[str, Any] = model.get_output_embeddings() assert isinstance(__a , tf.keras.layers.Layer ) _UpperCamelCase : Any = model.get_bias() assert name is None else: _UpperCamelCase : Optional[int] = model.get_output_embeddings() assert x is None _UpperCamelCase : Optional[int] = model.get_bias() assert name is None def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: # TODO JP: Make TransfoXL XLA compliant pass @slow def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase : Dict = TFTransfoXLModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @unittest.skip(reason="This model doesn't play well with fit() due to not returning a single loss." ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: pass @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @unittest.skip("Skip test until #12651 is resolved." ) @slow def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: _UpperCamelCase : Union[str, Any] = TFTransfoXLLMHeadModel.from_pretrained("transfo-xl-wt103" ) # fmt: off _UpperCamelCase : Tuple = tf.convert_to_tensor([[33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0]] , dtype=tf.intaa ) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off _UpperCamelCase : str = [33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0,33,1,1857,2,1,1009,4,1109,1_1739,4762,358,5,25,245,28,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> _UpperCamelCase : Union[str, Any] = model.generate(__a , max_length=200 , do_sample=__a ) self.assertListEqual(output_ids[0].numpy().tolist() , __a )
707
"""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 lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "hustvl/yolos-small": "https://huggingface.co/hustvl/yolos-small/resolve/main/config.json", # See all YOLOS models at https://huggingface.co/models?filter=yolos } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = "yolos" def __init__( self : Dict , __a : Optional[Any]=768 , __a : List[Any]=12 , __a : Any=12 , __a : List[Any]=3072 , __a : Optional[int]="gelu" , __a : Dict=0.0 , __a : Optional[Any]=0.0 , __a : Any=0.02 , __a : Optional[int]=1e-1_2 , __a : List[Any]=[512, 864] , __a : List[str]=16 , __a : str=3 , __a : Optional[Any]=True , __a : Optional[Any]=100 , __a : List[str]=True , __a : Any=False , __a : List[str]=1 , __a : str=5 , __a : Optional[Any]=2 , __a : Tuple=5 , __a : Any=2 , __a : Union[str, Any]=0.1 , **__a : List[str] , ) -> List[str]: super().__init__(**__a ) _UpperCamelCase : Dict = hidden_size _UpperCamelCase : Any = num_hidden_layers _UpperCamelCase : str = num_attention_heads _UpperCamelCase : Dict = intermediate_size _UpperCamelCase : List[str] = hidden_act _UpperCamelCase : List[str] = hidden_dropout_prob _UpperCamelCase : str = attention_probs_dropout_prob _UpperCamelCase : Tuple = initializer_range _UpperCamelCase : List[str] = layer_norm_eps _UpperCamelCase : Tuple = image_size _UpperCamelCase : Tuple = patch_size _UpperCamelCase : Dict = num_channels _UpperCamelCase : Any = qkv_bias _UpperCamelCase : str = num_detection_tokens _UpperCamelCase : str = use_mid_position_embeddings _UpperCamelCase : List[str] = auxiliary_loss # Hungarian matcher _UpperCamelCase : List[Any] = class_cost _UpperCamelCase : int = bbox_cost _UpperCamelCase : Optional[int] = giou_cost # Loss coefficients _UpperCamelCase : List[Any] = bbox_loss_coefficient _UpperCamelCase : str = giou_loss_coefficient _UpperCamelCase : Dict = eos_coefficient class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[str] = version.parse("1.11" ) @property def __SCREAMING_SNAKE_CASE ( self : str ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> float: return 1e-4 @property def __SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return 12
51
0
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {'vocab_file': 'sentencepiece.model'} lowerCamelCase__ = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } lowerCamelCase__ = { 'google/rembert': 256, } class __SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[Any] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ :Any = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ :Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Tuple , __a : List[Any] , __a : Optional[int]=False , __a : Dict=True , __a : Union[str, Any]=True , __a : Tuple="[CLS]" , __a : Optional[int]="[SEP]" , __a : Union[str, Any]="[UNK]" , __a : List[str]="[SEP]" , __a : Any="[PAD]" , __a : Any="[CLS]" , __a : Optional[int]="[MASK]" , **__a : Any , ) -> str: super().__init__( do_lower_case=_SCREAMING_SNAKE_CASE , remove_space=_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) _UpperCamelCase : List[str] = do_lower_case _UpperCamelCase : List[Any] = remove_space _UpperCamelCase : Tuple = keep_accents _UpperCamelCase : str = vocab_file _UpperCamelCase : int = spm.SentencePieceProcessor() self.sp_model.Load(_SCREAMING_SNAKE_CASE ) @property def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: return len(self.sp_model ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: _UpperCamelCase : Optional[Any] = {self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Any ) -> Optional[Any]: _UpperCamelCase : Dict = self.__dict__.copy() _UpperCamelCase : List[Any] = None return state def __setstate__( self : Any , __a : Union[str, Any] ) -> Optional[Any]: _UpperCamelCase : List[Any] = d _UpperCamelCase : int = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : Optional[int] , __a : Union[str, Any]=False ) -> Union[str, Any]: _UpperCamelCase : int = self.sp_model.EncodeAsPieces(_SCREAMING_SNAKE_CASE ) return pieces def __SCREAMING_SNAKE_CASE ( self : Any , __a : Optional[Any] ) -> Optional[int]: return self.sp_model.PieceToId(_SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : Any ) -> Union[str, Any]: return self.sp_model.IdToPiece(_SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : Optional[Any] ) -> List[str]: _UpperCamelCase : Union[str, Any] = self.sp_model.decode_pieces(_SCREAMING_SNAKE_CASE ) return out_string def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : Any , __a : List[Any] = None ) -> List[int]: _UpperCamelCase : Dict = [self.sep_token_id] _UpperCamelCase : 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 __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : Tuple , __a : Union[str, Any] = None , __a : List[Any] = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] def __SCREAMING_SNAKE_CASE ( self : Dict , __a : int , __a : Union[str, Any] = None ) -> List[int]: _UpperCamelCase : Tuple = [self.sep_token_id] _UpperCamelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : Tuple , __a : Optional[Any] = None ) -> Tuple[str]: if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("Vocabulary path ({}) should be a directory".format(_SCREAMING_SNAKE_CASE ) ) return _UpperCamelCase : Optional[int] = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
708
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path lowerCamelCase__ = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) lowerCamelCase__ = [ord(letter) for letter in string.ascii_lowercase] lowerCamelCase__ = {ord(char) for char in VALID_CHARS} lowerCamelCase__ = ["the", "be", "to", "of", "and", "in", "that", "have"] def lowercase__ ( lowercase_ ,lowercase_ ) -> str | None: """simple docstring""" _UpperCamelCase : str = "" _UpperCamelCase : int _UpperCamelCase : int _UpperCamelCase : int for keychar, cipherchar in zip(cycle(lowercase_ ) ,lowercase_ ): _UpperCamelCase : Dict = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(lowercase_ ) return decoded def lowercase__ ( lowercase_ ) -> list[str]: """simple docstring""" _UpperCamelCase : list[str] = [] for key in product(lowercase_ ,repeat=3 ): _UpperCamelCase : int = try_key(lowercase_ ,lowercase_ ) if encoded is not None: possibles.append(lowercase_ ) return possibles def lowercase__ ( lowercase_ ,lowercase_ ) -> list[str]: """simple docstring""" return [possible for possible in possibles if common_word in possible.lower()] def lowercase__ ( lowercase_ = "p059_cipher.txt" ) -> int: """simple docstring""" _UpperCamelCase : list[int] _UpperCamelCase : list[str] _UpperCamelCase : str _UpperCamelCase : str _UpperCamelCase : str = Path(lowercase_ ).parent.joinpath(lowercase_ ).read_text(encoding="utf-8" ) _UpperCamelCase : Optional[Any] = [int(lowercase_ ) for number in data.strip().split("," )] _UpperCamelCase : List[str] = filter_valid_chars(lowercase_ ) for common_word in COMMON_WORDS: _UpperCamelCase : Union[str, Any] = filter_common_word(lowercase_ ,lowercase_ ) if len(lowercase_ ) == 1: break _UpperCamelCase : Union[str, Any] = possibles[0] return sum(ord(lowercase_ ) for char in decoded_text ) if __name__ == "__main__": print(f"""{solution() = }""")
51
0
import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model from transformers.utils import logging logging.set_verbosity_info() # should not include what is already done by the `from_pt` argument lowerCamelCase__ = { '/attention/': '/0/SelfAttention/', '/self_attention/': '/0/SelfAttention/', '/encoder_decoder_attention/': '/1/EncDecAttention/', 'value': 'v', 'query': 'q', 'key': 'k', 'out': 'o', 'pre_self_attention_layer_norm': '0/layer_norm', 'pre_cross_attention_layer_norm': '1/layer_norm', 'pre_attention_layer_norm': '0/layer_norm', # previously 1, but seems wrong 'token_embedder': 'shared', 'encoder_norm': 'final_layer_norm', 'decoder_norm': 'final_layer_norm', 'relpos_bias/rel_embedding': 'block/0/layer/0/SelfAttention/relative_attention_bias/weight', 'router/router_weights/w/': 'router/classifier/', 'roer/roer_weights/w/': 'router/classifier/', 'logits_dense': 'lm_head', } def lowercase__ ( lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : str = list(s_dict.keys() ) for key in keys: _UpperCamelCase : Any = r".*/layers_(\d+)" _UpperCamelCase : Union[str, Any] = key if re.match(A_ ,A_ ): _UpperCamelCase : Optional[int] = re.sub(r"layers_(\d+)" ,r"block/\1/layer" ,A_ ) _UpperCamelCase : Optional[int] = r"(encoder|decoder)\/" if re.match(A_ ,A_ ): _UpperCamelCase : List[Any] = re.match(A_ ,A_ ).groups() if groups[0] == "encoder": _UpperCamelCase : int = re.sub(r"/mlp/" ,r"/1/mlp/" ,A_ ) _UpperCamelCase : Optional[int] = re.sub(r"/pre_mlp_layer_norm/" ,r"/1/layer_norm/" ,A_ ) elif groups[0] == "decoder": _UpperCamelCase : List[Any] = re.sub(r"/mlp/" ,r"/2/mlp/" ,A_ ) _UpperCamelCase : Tuple = re.sub(r"/pre_mlp_layer_norm/" ,r"/2/layer_norm/" ,A_ ) # 2. Convert other classic mappings for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items(): if old_key in new_key: _UpperCamelCase : str = new_key.replace(A_ ,A_ ) print(F'''{key} -> {new_key}''' ) _UpperCamelCase : Union[str, Any] = s_dict.pop(A_ ) if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: _UpperCamelCase : str = s_dict[ "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" ].T if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: _UpperCamelCase : Optional[int] = s_dict[ "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" ].T # 3. Take extra care of the EXPERTS layer for key in list(s_dict.keys() ): if "expert" in key: _UpperCamelCase : List[Any] = s_dict[key].shape[0] _UpperCamelCase : Any = s_dict[key] for idx in range(A_ ): _UpperCamelCase : Union[str, Any] = expert_weihts[idx] print(F'''{key} -> {key.replace('expert/' ,'nested fstring' )}''' ) s_dict.pop(A_ ) return s_dict lowerCamelCase__ = { 'NUM_ENCODER_LAYERS': 'num_layers', 'NUM_DECODER_LAYERS': 'num_decoder_layers', 'NUM_HEADS': 'num_heads', 'HEAD_DIM': 'd_kv', 'EMBED_DIM': 'd_model', 'MLP_DIM': 'd_ff', 'NUM_SELECTED_EXPERTS': 'num_selected_experts', 'NUM_ENCODER_SPARSE_LAYERS': 'num_sparse_encoder_layers', 'NUM_DECODER_SPARSE_LAYERS': 'num_sparse_decoder_layers', 'dense.MlpBlock.activations': 'feed_forward_proj', } def lowercase__ ( lowercase_ ,lowercase_ ) -> Optional[int]: """simple docstring""" import regex as re with open(A_ ,"r" ) as f: _UpperCamelCase : List[str] = f.read() _UpperCamelCase : Dict = re.findall(r"(.*) = ([0-9.]*)" ,A_ ) _UpperCamelCase : Union[str, Any] = {} for param, value in regex_match: if param in GIN_TO_CONFIG_MAPPING and value != "": _UpperCamelCase : Optional[Any] = float(A_ ) if "." in value else int(A_ ) _UpperCamelCase : Tuple = re.findall(r"(.*activations) = \(\'(.*)\',\)" ,A_ )[0] _UpperCamelCase : Tuple = str(activation[1] ) _UpperCamelCase : List[str] = num_experts _UpperCamelCase : Tuple = SwitchTransformersConfig(**A_ ) return config def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_=None ,lowercase_="./" ,lowercase_=8 ) -> str: """simple docstring""" print(F'''Loading flax weights from : {flax_checkpoint_path}''' ) _UpperCamelCase : Optional[int] = checkpoints.load_tax_checkpoint(A_ ) if gin_file is not None: _UpperCamelCase : Optional[int] = convert_gin_to_config(A_ ,A_ ) else: _UpperCamelCase : Union[str, Any] = SwitchTransformersConfig.from_pretrained(A_ ) _UpperCamelCase : int = SwitchTransformersForConditionalGeneration(A_ ) _UpperCamelCase : Optional[Any] = flax_params["target"] _UpperCamelCase : Optional[Any] = flatten_dict(A_ ,sep="/" ) _UpperCamelCase : Union[str, Any] = rename_keys(A_ ) _UpperCamelCase : Dict = unflatten_dict(A_ ,sep="/" ) # Load the flax params in the PT model load_flax_weights_in_pytorch_model(A_ ,A_ ) print(F'''Save PyTorch model to {pytorch_dump_path}''' ) pt_model.save_pretrained(A_ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--switch_t5x_checkpoint_path", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the" " model architecture. If not provided, a `gin_file` has to be provided." ), ) parser.add_argument( "--gin_file", default=None, type=str, required=False, help="Path to the gin config file. If not provided, a `config_file` has to be passed ", ) parser.add_argument( "--config_name", default=None, type=str, required=False, help="Config name of SwitchTransformers model." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output pytorch model." ) parser.add_argument("--num_experts", default=8, type=int, required=False, help="Number of experts") lowerCamelCase__ = parser.parse_args() convert_flax_checkpoint_to_pytorch( args.switch_tax_checkpoint_path, args.config_name, args.gin_file, args.pytorch_dump_folder_path, args.num_experts, )
709
"""simple docstring""" def lowercase__ ( lowercase_ ,lowercase_ ) -> None: """simple docstring""" _UpperCamelCase : List[Any] = len(lowercase_ ) print("The following activities are selected:" ) # The first activity is always selected _UpperCamelCase : List[Any] = 0 print(lowercase_ ,end="," ) # Consider rest of the activities for j in range(lowercase_ ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(lowercase_ ,end="," ) _UpperCamelCase : Optional[Any] = j if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase__ = [1, 3, 0, 5, 8, 5] lowerCamelCase__ = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
51
0
"""simple docstring""" import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex lowerCamelCase__ = logging.getLogger(__name__) class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Dict ) -> Dict: _UpperCamelCase : Optional[int] = False def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Tuple , __a : Union[str, Any] , __a : Optional[Any] , __a : Tuple ) -> Tuple: if not self.initialized: _UpperCamelCase : List[str] = RagRetriever( _A , question_encoder_tokenizer=_A , generator_tokenizer=_A , index=_A , init_retrieval=_A , ) _UpperCamelCase : List[str] = True def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: self.retriever.index.init_index() def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : Optional[Any] , __a : str ) -> List[str]: _UpperCamelCase : str = self.retriever._main_retrieve(_A , _A ) return doc_ids, retrieved_doc_embeds class __SCREAMING_SNAKE_CASE ( snake_case__ ): '''simple docstring''' def __init__( self : Optional[Any] , __a : Optional[Any] , __a : Any , __a : Dict , __a : List[Any] , __a : Any=None ) -> Optional[Any]: if index is not None and index.is_initialized() and len(_A ) > 0: raise ValueError( "When using Ray for distributed fine-tuning, " "you\'ll need to provide the paths instead, " "as the dataset and the index are loaded " "separately. More info in examples/rag/use_own_knowledge_dataset.py " ) super().__init__( _A , question_encoder_tokenizer=_A , generator_tokenizer=_A , index=_A , init_retrieval=_A , ) _UpperCamelCase : int = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(_A , _A , _A , _A ) for worker in self.retrieval_workers ] ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: logger.info("initializing retrieval" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __SCREAMING_SNAKE_CASE ( self : int , __a : str , __a : List[Any] ) -> int: if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. _UpperCamelCase : List[str] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] _UpperCamelCase : List[str] = ray.get(random_worker.retrieve.remote(_A , _A ) ) else: _UpperCamelCase : Optional[int] = self._main_retrieve(_A , _A ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(_A ) @classmethod def __SCREAMING_SNAKE_CASE ( cls : Optional[int] , __a : Union[str, Any] , __a : List[Any]=None , **__a : Union[str, Any] ) -> List[str]: return super(_A , cls ).get_tokenizers(_A , _A , **_A ) @classmethod def __SCREAMING_SNAKE_CASE ( cls : Union[str, Any] , __a : Optional[int] , __a : int , __a : str=None , **__a : int ) -> List[str]: _UpperCamelCase : List[str] = kwargs.pop("config" , _A ) or RagConfig.from_pretrained(_A , **_A ) _UpperCamelCase : str = RagTokenizer.from_pretrained(_A , config=_A ) _UpperCamelCase : Any = rag_tokenizer.question_encoder _UpperCamelCase : List[Any] = rag_tokenizer.generator if indexed_dataset is not None: _UpperCamelCase : str = 'custom' _UpperCamelCase : Dict = CustomHFIndex(config.retrieval_vector_size , _A ) else: _UpperCamelCase : Any = cls._build_index(_A ) return cls( _A , question_encoder_tokenizer=_A , generator_tokenizer=_A , retrieval_workers=_A , index=_A , )
710
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :torch.FloatTensor class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : Dict=3 , __a : Any=3 , __a : Union[str, Any]=("DownEncoderBlock2D",) , __a : Optional[int]=(64,) , __a : int=2 , __a : Tuple=32 , __a : int="silu" , __a : str=True , ) -> Dict: super().__init__() _UpperCamelCase : List[str] = layers_per_block _UpperCamelCase : Dict = torch.nn.Convad( __a , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) _UpperCamelCase : int = None _UpperCamelCase : Any = nn.ModuleList([] ) # down _UpperCamelCase : List[str] = block_out_channels[0] for i, down_block_type in enumerate(__a ): _UpperCamelCase : Tuple = output_channel _UpperCamelCase : int = block_out_channels[i] _UpperCamelCase : int = i == len(__a ) - 1 _UpperCamelCase : Dict = get_down_block( __a , num_layers=self.layers_per_block , in_channels=__a , out_channels=__a , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=__a , resnet_groups=__a , attention_head_dim=__a , temb_channels=__a , ) self.down_blocks.append(__a ) # mid _UpperCamelCase : Union[str, Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__a , output_scale_factor=1 , resnet_time_scale_shift="default" , attention_head_dim=block_out_channels[-1] , resnet_groups=__a , temb_channels=__a , ) # out _UpperCamelCase : Any = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__a , eps=1e-6 ) _UpperCamelCase : Any = nn.SiLU() _UpperCamelCase : Union[str, Any] = 2 * out_channels if double_z else out_channels _UpperCamelCase : Tuple = nn.Convad(block_out_channels[-1] , __a , 3 , padding=1 ) _UpperCamelCase : Optional[int] = False def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Dict ) -> List[str]: _UpperCamelCase : int = x _UpperCamelCase : Optional[int] = self.conv_in(__a ) if self.training and self.gradient_checkpointing: def create_custom_forward(__a : Tuple ): def custom_forward(*__a : Any ): return module(*__a ) return custom_forward # down if is_torch_version(">=" , "1.11.0" ): for down_block in self.down_blocks: _UpperCamelCase : Optional[int] = torch.utils.checkpoint.checkpoint( create_custom_forward(__a ) , __a , use_reentrant=__a ) # middle _UpperCamelCase : Tuple = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , use_reentrant=__a ) else: for down_block in self.down_blocks: _UpperCamelCase : Any = torch.utils.checkpoint.checkpoint(create_custom_forward(__a ) , __a ) # middle _UpperCamelCase : int = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __a ) else: # down for down_block in self.down_blocks: _UpperCamelCase : int = down_block(__a ) # middle _UpperCamelCase : int = self.mid_block(__a ) # post-process _UpperCamelCase : Any = self.conv_norm_out(__a ) _UpperCamelCase : Any = self.conv_act(__a ) _UpperCamelCase : Optional[Any] = self.conv_out(__a ) return sample class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : int=3 , __a : Any=3 , __a : str=("UpDecoderBlock2D",) , __a : Optional[int]=(64,) , __a : int=2 , __a : Optional[int]=32 , __a : Tuple="silu" , __a : Union[str, Any]="group" , ) -> str: super().__init__() _UpperCamelCase : List[Any] = layers_per_block _UpperCamelCase : Tuple = nn.Convad( __a , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) _UpperCamelCase : List[str] = None _UpperCamelCase : Dict = nn.ModuleList([] ) _UpperCamelCase : List[Any] = in_channels if norm_type == "spatial" else None # mid _UpperCamelCase : Optional[Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__a , output_scale_factor=1 , resnet_time_scale_shift="default" if norm_type == "group" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__a , temb_channels=__a , ) # up _UpperCamelCase : List[str] = list(reversed(__a ) ) _UpperCamelCase : int = reversed_block_out_channels[0] for i, up_block_type in enumerate(__a ): _UpperCamelCase : int = output_channel _UpperCamelCase : Union[str, Any] = reversed_block_out_channels[i] _UpperCamelCase : Optional[Any] = i == len(__a ) - 1 _UpperCamelCase : Union[str, Any] = get_up_block( __a , num_layers=self.layers_per_block + 1 , in_channels=__a , out_channels=__a , prev_output_channel=__a , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=__a , resnet_groups=__a , attention_head_dim=__a , temb_channels=__a , resnet_time_scale_shift=__a , ) self.up_blocks.append(__a ) _UpperCamelCase : Optional[Any] = output_channel # out if norm_type == "spatial": _UpperCamelCase : Optional[int] = SpatialNorm(block_out_channels[0] , __a ) else: _UpperCamelCase : Optional[int] = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__a , eps=1e-6 ) _UpperCamelCase : str = nn.SiLU() _UpperCamelCase : str = nn.Convad(block_out_channels[0] , __a , 3 , padding=1 ) _UpperCamelCase : Dict = False def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : List[Any] , __a : Union[str, Any]=None ) -> Tuple: _UpperCamelCase : List[str] = z _UpperCamelCase : Dict = self.conv_in(__a ) _UpperCamelCase : Any = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__a : Any ): def custom_forward(*__a : Tuple ): return module(*__a ) return custom_forward if is_torch_version(">=" , "1.11.0" ): # middle _UpperCamelCase : str = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , __a , use_reentrant=__a ) _UpperCamelCase : Optional[int] = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(__a ) , __a , __a , use_reentrant=__a ) else: # middle _UpperCamelCase : Optional[int] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , __a ) _UpperCamelCase : Union[str, Any] = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : str = torch.utils.checkpoint.checkpoint(create_custom_forward(__a ) , __a , __a ) else: # middle _UpperCamelCase : str = self.mid_block(__a , __a ) _UpperCamelCase : int = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : Any = up_block(__a , __a ) # post-process if latent_embeds is None: _UpperCamelCase : List[str] = self.conv_norm_out(__a ) else: _UpperCamelCase : Optional[int] = self.conv_norm_out(__a , __a ) _UpperCamelCase : Tuple = self.conv_act(__a ) _UpperCamelCase : List[Any] = self.conv_out(__a ) return sample class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : Tuple , __a : List[str] , __a : List[str] , __a : str=None , __a : Optional[int]="random" , __a : Any=False , __a : Optional[Any]=True ) -> List[Any]: super().__init__() _UpperCamelCase : Tuple = n_e _UpperCamelCase : Tuple = vq_embed_dim _UpperCamelCase : Union[str, Any] = beta _UpperCamelCase : str = legacy _UpperCamelCase : Dict = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) _UpperCamelCase : Any = remap if self.remap is not None: self.register_buffer("used" , torch.tensor(np.load(self.remap ) ) ) _UpperCamelCase : Dict = self.used.shape[0] _UpperCamelCase : Optional[int] = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": _UpperCamelCase : Optional[int] = self.re_embed _UpperCamelCase : Any = self.re_embed + 1 print( F'''Remapping {self.n_e} indices to {self.re_embed} indices. ''' F'''Using {self.unknown_index} for unknown indices.''' ) else: _UpperCamelCase : Union[str, Any] = n_e _UpperCamelCase : List[str] = sane_index_shape def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : Optional[Any] ) -> Optional[int]: _UpperCamelCase : str = inds.shape assert len(__a ) > 1 _UpperCamelCase : Union[str, Any] = inds.reshape(ishape[0] , -1 ) _UpperCamelCase : Optional[Any] = self.used.to(__a ) _UpperCamelCase : List[str] = (inds[:, :, None] == used[None, None, ...]).long() _UpperCamelCase : Optional[Any] = match.argmax(-1 ) _UpperCamelCase : Any = match.sum(2 ) < 1 if self.unknown_index == "random": _UpperCamelCase : Optional[int] = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: _UpperCamelCase : Dict = self.unknown_index return new.reshape(__a ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : Optional[int] ) -> Optional[int]: _UpperCamelCase : int = inds.shape assert len(__a ) > 1 _UpperCamelCase : List[Any] = inds.reshape(ishape[0] , -1 ) _UpperCamelCase : Optional[int] = self.used.to(__a ) if self.re_embed > self.used.shape[0]: # extra token _UpperCamelCase : int = 0 # simply set to zero _UpperCamelCase : Union[str, Any] = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __a ) return back.reshape(__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : str ) -> Optional[int]: # reshape z -> (batch, height, width, channel) and flatten _UpperCamelCase : List[str] = z.permute(0 , 2 , 3 , 1 ).contiguous() _UpperCamelCase : int = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z _UpperCamelCase : Optional[int] = torch.argmin(torch.cdist(__a , self.embedding.weight ) , dim=1 ) _UpperCamelCase : int = self.embedding(__a ).view(z.shape ) _UpperCamelCase : str = None _UpperCamelCase : Any = None # compute loss for embedding if not self.legacy: _UpperCamelCase : List[str] = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: _UpperCamelCase : str = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients _UpperCamelCase : List[str] = z + (z_q - z).detach() # reshape back to match original input shape _UpperCamelCase : Optional[Any] = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: _UpperCamelCase : Tuple = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis _UpperCamelCase : Dict = self.remap_to_used(__a ) _UpperCamelCase : List[str] = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: _UpperCamelCase : str = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : List[str] , __a : str ) -> Any: # shape specifying (batch, height, width, channel) if self.remap is not None: _UpperCamelCase : str = indices.reshape(shape[0] , -1 ) # add batch axis _UpperCamelCase : str = self.unmap_to_all(__a ) _UpperCamelCase : int = indices.reshape(-1 ) # flatten again # get quantized latent vectors _UpperCamelCase : Optional[int] = self.embedding(__a ) if shape is not None: _UpperCamelCase : Tuple = z_q.view(__a ) # reshape back to match original input shape _UpperCamelCase : Tuple = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __init__( self : Optional[int] , __a : List[str] , __a : Optional[Any]=False ) -> int: _UpperCamelCase : Dict = parameters _UpperCamelCase, _UpperCamelCase : str = torch.chunk(__a , 2 , dim=1 ) _UpperCamelCase : Tuple = torch.clamp(self.logvar , -30.0 , 20.0 ) _UpperCamelCase : Union[str, Any] = deterministic _UpperCamelCase : Dict = torch.exp(0.5 * self.logvar ) _UpperCamelCase : Any = torch.exp(self.logvar ) if self.deterministic: _UpperCamelCase : List[Any] = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : Optional[torch.Generator] = None ) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype _UpperCamelCase : List[Any] = randn_tensor( self.mean.shape , generator=__a , device=self.parameters.device , dtype=self.parameters.dtype ) _UpperCamelCase : List[Any] = self.mean + self.std * sample return x def __SCREAMING_SNAKE_CASE ( self : Any , __a : List[str]=None ) -> List[Any]: if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def __SCREAMING_SNAKE_CASE ( self : str , __a : Tuple , __a : List[str]=[1, 2, 3] ) -> int: if self.deterministic: return torch.Tensor([0.0] ) _UpperCamelCase : List[str] = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: return self.mean
51
0
"""simple docstring""" def lowercase__ ( lowercase_ = 600_851_475_143 ) -> int: """simple docstring""" try: _UpperCamelCase : Dict = int(__snake_case ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) _UpperCamelCase : int = 2 _UpperCamelCase : Union[str, Any] = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 _UpperCamelCase : List[Any] = i while n % i == 0: _UpperCamelCase : str = n // i i += 1 return int(__snake_case ) if __name__ == "__main__": print(f"""{solution() = }""")
711
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''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 __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict[str, str]: return {self.text_column: "text", self.summary_column: "summary"}
51
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "weiweishi/roc-bert-base-zh": "https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json", } class __SCREAMING_SNAKE_CASE ( lowercase_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = "roc_bert" def __init__( self : int , __a : str=3_0522 , __a : List[str]=768 , __a : Optional[Any]=12 , __a : str=12 , __a : Dict=3072 , __a : Dict="gelu" , __a : Tuple=0.1 , __a : Optional[int]=0.1 , __a : Union[str, Any]=512 , __a : int=2 , __a : Union[str, Any]=0.02 , __a : Any=1e-1_2 , __a : Any=True , __a : Dict=0 , __a : Union[str, Any]="absolute" , __a : List[str]=None , __a : Union[str, Any]=True , __a : Optional[Any]=True , __a : Dict=768 , __a : Optional[Any]=910 , __a : Optional[Any]=512 , __a : Optional[Any]=2_4858 , __a : str=True , **__a : Tuple , ) -> int: _UpperCamelCase : List[Any] = vocab_size _UpperCamelCase : List[str] = max_position_embeddings _UpperCamelCase : Dict = hidden_size _UpperCamelCase : Optional[Any] = num_hidden_layers _UpperCamelCase : List[str] = num_attention_heads _UpperCamelCase : Any = intermediate_size _UpperCamelCase : Tuple = hidden_act _UpperCamelCase : Optional[int] = hidden_dropout_prob _UpperCamelCase : List[str] = attention_probs_dropout_prob _UpperCamelCase : Optional[Any] = initializer_range _UpperCamelCase : List[str] = type_vocab_size _UpperCamelCase : Any = layer_norm_eps _UpperCamelCase : str = use_cache _UpperCamelCase : Optional[int] = enable_pronunciation _UpperCamelCase : Dict = enable_shape _UpperCamelCase : Optional[int] = pronunciation_embed_dim _UpperCamelCase : List[str] = pronunciation_vocab_size _UpperCamelCase : Optional[Any] = shape_embed_dim _UpperCamelCase : Tuple = shape_vocab_size _UpperCamelCase : List[str] = concat_input _UpperCamelCase : Dict = position_embedding_type _UpperCamelCase : List[str] = classifier_dropout super().__init__(pad_token_id=lowerCamelCase_ , **lowerCamelCase_ )
712
"""simple docstring""" def lowercase__ ( lowercase_ ) -> set: """simple docstring""" _UpperCamelCase : Union[str, Any] = set() # edges = list of graph's edges _UpperCamelCase : Union[str, Any] = get_edges(lowercase_ ) # 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: _UpperCamelCase, _UpperCamelCase : str = edges.pop() chosen_vertices.add(lowercase_ ) chosen_vertices.add(lowercase_ ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(lowercase_ ) return chosen_vertices def lowercase__ ( lowercase_ ) -> set: """simple docstring""" _UpperCamelCase : List[str] = 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)}")
51
0
"""simple docstring""" from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class __SCREAMING_SNAKE_CASE ( __lowerCamelCase ): '''simple docstring''' @slow @require_torch def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: _UpperCamelCase : Optional[int] = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny" , "prajjwal1/bert-tiny" ) _UpperCamelCase : Union[str, Any] = BertTokenizer.from_pretrained("bert-base-uncased" ) _UpperCamelCase : List[str] = bertabert.config.encoder.vocab_size _UpperCamelCase : List[Any] = tokenizer.sep_token_id _UpperCamelCase : Union[str, Any] = tokenizer.cls_token_id _UpperCamelCase : Dict = 128 _UpperCamelCase : List[Any] = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="train[:1%]" ) _UpperCamelCase : str = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="validation[:1%]" ) _UpperCamelCase : Tuple = train_dataset.select(range(32 ) ) _UpperCamelCase : Tuple = val_dataset.select(range(16 ) ) _UpperCamelCase : Any = 4 def _map_to_encoder_decoder_inputs(__a : List[Any] ): # Tokenizer will automatically set [BOS] <text> [EOS] _UpperCamelCase : int = tokenizer(batch["article"] , padding="max_length" , truncation=UpperCamelCase_ , max_length=512 ) _UpperCamelCase : int = tokenizer(batch["highlights"] , padding="max_length" , truncation=UpperCamelCase_ , max_length=128 ) _UpperCamelCase : Tuple = inputs.input_ids _UpperCamelCase : Any = inputs.attention_mask _UpperCamelCase : Any = outputs.input_ids _UpperCamelCase : Optional[Any] = outputs.input_ids.copy() _UpperCamelCase : Union[str, Any] = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] ] _UpperCamelCase : Tuple = outputs.attention_mask assert all(len(UpperCamelCase_ ) == 512 for x in inputs.input_ids ) assert all(len(UpperCamelCase_ ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(__a : int ): _UpperCamelCase : Tuple = pred.label_ids _UpperCamelCase : Union[str, Any] = pred.predictions # all unnecessary tokens are removed _UpperCamelCase : Any = tokenizer.batch_decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ ) _UpperCamelCase : Union[str, Any] = tokenizer.batch_decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ ) _UpperCamelCase : Dict = sum([int(pred_str[i] == label_str[i] ) for i in range(len(UpperCamelCase_ ) )] ) / len(UpperCamelCase_ ) return {"accuracy": accuracy} # map train dataset _UpperCamelCase : List[Any] = train_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCamelCase_ , batch_size=UpperCamelCase_ , remove_columns=["article", "highlights"] , ) train_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) # same for validation dataset _UpperCamelCase : str = val_dataset.map( _map_to_encoder_decoder_inputs , batched=UpperCamelCase_ , batch_size=UpperCamelCase_ , remove_columns=["article", "highlights"] , ) val_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) _UpperCamelCase : int = self.get_auto_remove_tmp_dir() _UpperCamelCase : Union[str, Any] = SeqaSeqTrainingArguments( output_dir=UpperCamelCase_ , per_device_train_batch_size=UpperCamelCase_ , per_device_eval_batch_size=UpperCamelCase_ , predict_with_generate=UpperCamelCase_ , evaluation_strategy="steps" , do_train=UpperCamelCase_ , do_eval=UpperCamelCase_ , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer _UpperCamelCase : List[Any] = SeqaSeqTrainer( model=UpperCamelCase_ , args=UpperCamelCase_ , compute_metrics=_compute_metrics , train_dataset=UpperCamelCase_ , eval_dataset=UpperCamelCase_ , tokenizer=UpperCamelCase_ , ) # start training trainer.train()
713
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCamelCase__ = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["OwlViTFeatureExtractor"] lowerCamelCase__ = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
51
0
"""simple docstring""" def lowercase__ ( lowercase_ = 10 ) -> List[str]: """simple docstring""" if not isinstance(lowerCamelCase__ ,lowerCamelCase__ ) or n < 0: raise ValueError("Invalid input" ) _UpperCamelCase : List[str] = 10**n _UpperCamelCase : Tuple = 28_433 * (pow(2 ,7_830_457 ,lowerCamelCase__ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f"""{solution(10) = }""")
714
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowercase__ ( lowercase_ = 1_000_000 ,lowercase_ = 10 ) -> int: """simple docstring""" _UpperCamelCase : defaultdict = defaultdict(lowercase_ ) for outer_width in range(3 ,(t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: _UpperCamelCase : Any = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) ,1 ) else: _UpperCamelCase : str = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowercase_ ,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() = }""")
51
0
"""simple docstring""" import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) -> Tuple: """simple docstring""" _UpperCamelCase : List[Any] = StableDiffusionPipeline.from_pretrained(a__ ,torch_dtype=torch.floataa ) # load LoRA weight from .safetensors _UpperCamelCase : List[str] = load_file(a__ ) _UpperCamelCase : int = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: _UpperCamelCase : Optional[int] = key.split("." )[0].split(LORA_PREFIX_TEXT_ENCODER + "_" )[-1].split("_" ) _UpperCamelCase : List[str] = pipeline.text_encoder else: _UpperCamelCase : Any = key.split("." )[0].split(LORA_PREFIX_UNET + "_" )[-1].split("_" ) _UpperCamelCase : Union[str, Any] = pipeline.unet # find the target layer _UpperCamelCase : List[Any] = layer_infos.pop(0 ) while len(a__ ) > -1: try: _UpperCamelCase : Any = curr_layer.__getattr__(a__ ) if len(a__ ) > 0: _UpperCamelCase : Optional[int] = layer_infos.pop(0 ) elif len(a__ ) == 0: break except Exception: if len(a__ ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: _UpperCamelCase : int = layer_infos.pop(0 ) _UpperCamelCase : Optional[int] = [] if "lora_down" in key: pair_keys.append(key.replace("lora_down" ,"lora_up" ) ) pair_keys.append(a__ ) else: pair_keys.append(a__ ) pair_keys.append(key.replace("lora_up" ,"lora_down" ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: _UpperCamelCase : List[str] = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) _UpperCamelCase : Optional[int] = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(a__ ,a__ ).unsqueeze(2 ).unsqueeze(3 ) else: _UpperCamelCase : Any = state_dict[pair_keys[0]].to(torch.floataa ) _UpperCamelCase : str = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(a__ ,a__ ) # update visited list for item in pair_keys: visited.append(a__ ) return pipeline if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument( "--base_model_path", default=None, type=str, required=True, help="Path to the base model in diffusers format." ) parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument( "--lora_prefix_unet", default="lora_unet", type=str, help="The prefix of UNet weight in safetensors" ) parser.add_argument( "--lora_prefix_text_encoder", default="lora_te", type=str, help="The prefix of text encoder weight in safetensors", ) parser.add_argument("--alpha", default=0.7_5, type=float, help="The merging ratio in W = W0 + alpha * deltaW") parser.add_argument( "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not." ) parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)") lowerCamelCase__ = parser.parse_args() lowerCamelCase__ = args.base_model_path lowerCamelCase__ = args.checkpoint_path lowerCamelCase__ = args.dump_path lowerCamelCase__ = args.lora_prefix_unet lowerCamelCase__ = args.lora_prefix_text_encoder lowerCamelCase__ = args.alpha lowerCamelCase__ = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) lowerCamelCase__ = pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
715
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar lowerCamelCase__ = TypeVar("KEY") lowerCamelCase__ = TypeVar("VAL") @dataclass(frozen=_UpperCamelCase , slots=_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( Generic[KEY, VAL] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :KEY SCREAMING_SNAKE_CASE__ :VAL class __SCREAMING_SNAKE_CASE ( _Item ): '''simple docstring''' def __init__( self : List[str] ) -> None: super().__init__(__a , __a ) def __bool__( self : Dict ) -> bool: return False lowerCamelCase__ = _DeletedItem() class __SCREAMING_SNAKE_CASE ( MutableMapping[KEY, VAL] ): '''simple docstring''' def __init__( self : int , __a : int = 8 , __a : float = 0.75 ) -> None: _UpperCamelCase : str = initial_block_size _UpperCamelCase : list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 _UpperCamelCase : List[str] = capacity_factor _UpperCamelCase : Dict = 0 def __SCREAMING_SNAKE_CASE ( self : int , __a : KEY ) -> int: return hash(__a ) % len(self._buckets ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : int ) -> int: return (ind + 1) % len(self._buckets ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : int , __a : KEY , __a : VAL ) -> bool: _UpperCamelCase : List[Any] = self._buckets[ind] if not stored: _UpperCamelCase : Tuple = _Item(__a , __a ) self._len += 1 return True elif stored.key == key: _UpperCamelCase : Union[str, Any] = _Item(__a , __a ) return True else: return False def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> bool: _UpperCamelCase : Any = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False _UpperCamelCase : List[str] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : int ) -> None: _UpperCamelCase : Any = self._buckets _UpperCamelCase : List[Any] = [None] * new_size _UpperCamelCase : List[str] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __SCREAMING_SNAKE_CASE ( self : int ) -> None: self._resize(len(self._buckets ) * 2 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: self._resize(len(self._buckets ) // 2 ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : KEY ) -> Iterator[int]: _UpperCamelCase : str = self._get_bucket_index(__a ) for _ in range(len(self._buckets ) ): yield ind _UpperCamelCase : Tuple = self._get_next_ind(__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : KEY , __a : VAL ) -> None: for ind in self._iterate_buckets(__a ): if self._try_set(__a , __a , __a ): break def __setitem__( self : int , __a : KEY , __a : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(__a , __a ) def __delitem__( self : str , __a : KEY ) -> None: for ind in self._iterate_buckets(__a ): _UpperCamelCase : Tuple = self._buckets[ind] if item is None: raise KeyError(__a ) if item is _deleted: continue if item.key == key: _UpperCamelCase : List[Any] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : str , __a : KEY ) -> VAL: for ind in self._iterate_buckets(__a ): _UpperCamelCase : Tuple = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__a ) def __len__( self : List[Any] ) -> int: return self._len def __iter__( self : List[str] ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : List[str] ) -> str: _UpperCamelCase : Optional[int] = " ,".join( F'''{item.key}: {item.val}''' for item in self._buckets if item ) return F'''HashMap({val_string})'''
51
0
"""simple docstring""" import inspect import os import re from transformers.configuration_utils import PretrainedConfig 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/check_config_docstrings.py lowerCamelCase__ = "src/transformers" # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase__ = direct_transformers_import(PATH_TO_TRANSFORMERS) lowerCamelCase__ = transformers.models.auto.configuration_auto.CONFIG_MAPPING lowerCamelCase__ = { # used to compute the property `self.chunk_length` "EncodecConfig": ["overlap"], # used as `self.bert_model = BertModel(config, ...)` "DPRConfig": True, # not used in modeling files, but it's an important information "FSMTConfig": ["langs"], # used internally in the configuration class file "GPTNeoConfig": ["attention_types"], # used internally in the configuration class file "EsmConfig": ["is_folding_model"], # used during training (despite we don't have training script for these models yet) "Mask2FormerConfig": ["ignore_value"], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) "OneFormerConfig": ["ignore_value", "norm"], # used during preprocessing and collation, see `collating_graphormer.py` "GraphormerConfig": ["spatial_pos_max"], # used internally in the configuration class file "T5Config": ["feed_forward_proj"], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally "MT5Config": ["feed_forward_proj", "tokenizer_class"], "UMT5Config": ["feed_forward_proj", "tokenizer_class"], # used internally in the configuration class file "LongT5Config": ["feed_forward_proj"], # used internally in the configuration class file "SwitchTransformersConfig": ["feed_forward_proj"], # having default values other than `1e-5` - we can't fix them without breaking "BioGptConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "GLPNConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "SegformerConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "CvtConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "PerceiverConfig": ["layer_norm_eps"], # used internally to calculate the feature size "InformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate the feature size "TimeSeriesTransformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate the feature size "AutoformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate `mlp_dim` "SamVisionConfig": ["mlp_ratio"], # For (head) training, but so far not implemented "ClapAudioConfig": ["num_classes"], # Not used, but providing useful information to users "SpeechT5HifiGanConfig": ["sampling_rate"], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { "CLIPSegConfig": True, "DeformableDetrConfig": True, "DetaConfig": True, "DinatConfig": True, "DonutSwinConfig": True, "EfficientFormerConfig": True, "FSMTConfig": True, "JukeboxConfig": True, "LayoutLMv2Config": True, "MaskFormerSwinConfig": True, "MT5Config": True, "NatConfig": True, "OneFormerConfig": True, "PerceiverConfig": True, "RagConfig": True, "SpeechT5Config": True, "SwinConfig": True, "Swin2SRConfig": True, "Swinv2Config": True, "SwitchTransformersConfig": True, "TableTransformerConfig": True, "TapasConfig": True, "TransfoXLConfig": True, "UniSpeechConfig": True, "UniSpeechSatConfig": True, "WavLMConfig": True, "WhisperConfig": True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) "JukeboxPriorConfig": True, # TODO: @Younes (for `is_decoder`) "Pix2StructTextConfig": True, } ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) -> List[str]: """simple docstring""" _UpperCamelCase : List[Any] = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( F'''config.{attribute}''' in modeling_source or F'''getattr(config, "{attribute}"''' in modeling_source or F'''getattr(self.config, "{attribute}"''' in modeling_source ): _UpperCamelCase : Dict = True # Deal with multi-line cases elif ( re.search( rF'''getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"''' ,snake_case__ ,) is not None ): _UpperCamelCase : Any = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: _UpperCamelCase : Optional[int] = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files _UpperCamelCase : List[Any] = [ "bos_index", "eos_index", "pad_index", "unk_index", "mask_index", "image_size", "use_cache", "out_features", "out_indices", ] _UpperCamelCase : int = ["encoder_no_repeat_ngram_size"] # Special cases to be allowed _UpperCamelCase : Tuple = True if not attribute_used: _UpperCamelCase : List[Any] = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: _UpperCamelCase : Optional[Any] = True elif attribute in ["tie_word_embeddings"] and default_value is False: _UpperCamelCase : Optional[Any] = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: _UpperCamelCase : List[Any] = True elif attribute.endswith("_token_id" ): _UpperCamelCase : Dict = True # configuration class specific cases if not case_allowed: _UpperCamelCase : Union[str, Any] = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ ,[] ) _UpperCamelCase : Optional[Any] = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def lowercase__ ( lowercase_ ) -> List[str]: """simple docstring""" _UpperCamelCase : Optional[int] = dict(inspect.signature(config_class.__init__ ).parameters ) _UpperCamelCase : Optional[int] = [x for x in list(signature.keys() ) if x not in ["self", "kwargs"]] _UpperCamelCase : Tuple = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass _UpperCamelCase : Union[str, Any] = {} if len(config_class.attribute_map ) > 0: _UpperCamelCase : Dict = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files _UpperCamelCase : Optional[int] = inspect.getsourcefile(snake_case__ ) _UpperCamelCase : Union[str, Any] = os.path.dirname(snake_case__ ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. _UpperCamelCase : Optional[int] = [os.path.join(snake_case__ ,snake_case__ ) for fn in os.listdir(snake_case__ ) if fn.startswith("modeling_" )] # Get the source code strings _UpperCamelCase : Union[str, Any] = [] for path in modeling_paths: if os.path.isfile(snake_case__ ): with open(snake_case__ ) as fp: modeling_sources.append(fp.read() ) _UpperCamelCase : Union[str, Any] = [] for config_param, default_value in zip(snake_case__ ,snake_case__ ): # `attributes` here is all the variant names for `config_param` _UpperCamelCase : Union[str, Any] = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(snake_case__ ,snake_case__ ,snake_case__ ,snake_case__ ): unused_attributes.append(attributes[0] ) return sorted(snake_case__ ) def lowercase__ ( ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Dict = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) _UpperCamelCase : Dict = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) ,lambda lowercase_ : inspect.isclass(snake_case__ ) and issubclass(snake_case__ ,snake_case__ ) and inspect.getmodule(snake_case__ ) == inspect.getmodule(_config_class ) ,) ] for config_class in config_classes_in_module: _UpperCamelCase : int = check_config_attributes_being_used(snake_case__ ) if len(snake_case__ ) > 0: _UpperCamelCase : str = unused_attributes if len(snake_case__ ) > 0: _UpperCamelCase : str = "The following configuration classes contain unused attributes in the corresponding modeling files:\n" for name, attributes in configs_with_unused_attributes.items(): error += F'''{name}: {attributes}\n''' raise ValueError(snake_case__ ) if __name__ == "__main__": check_config_attributes()
716
"""simple docstring""" class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , __a : list[int] ) -> None: _UpperCamelCase : Tuple = len(__a ) _UpperCamelCase : Dict = [0] * len_array if len_array > 0: _UpperCamelCase : Optional[Any] = array[0] for i in range(1 , __a ): _UpperCamelCase : Tuple = self.prefix_sum[i - 1] + array[i] def __SCREAMING_SNAKE_CASE ( self : Dict , __a : int , __a : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : int ) -> bool: _UpperCamelCase : int = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(__a ) return False if __name__ == "__main__": import doctest doctest.testmod()
51
0
"""simple docstring""" from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar lowerCamelCase__ = TypeVar("T") lowerCamelCase__ = TypeVar("U") class __SCREAMING_SNAKE_CASE ( Generic[T, U] ): '''simple docstring''' def __init__( self : List[Any] , __a : T | None , __a : U | None ) -> Optional[Any]: _UpperCamelCase : List[Any] = key _UpperCamelCase : Union[str, Any] = val _UpperCamelCase : DoubleLinkedListNode[T, U] | None = None _UpperCamelCase : DoubleLinkedListNode[T, U] | None = None def __repr__( self : int ) -> Dict: return ( F'''Node: key: {self.key}, val: {self.val}, ''' F'''has next: {bool(self.next )}, has prev: {bool(self.prev )}''' ) class __SCREAMING_SNAKE_CASE ( Generic[T, U] ): '''simple docstring''' def __init__( self : Optional[Any] ) -> List[str]: _UpperCamelCase : DoubleLinkedListNode[T, U] = DoubleLinkedListNode(UpperCAmelCase__ , UpperCAmelCase__ ) _UpperCamelCase : DoubleLinkedListNode[T, U] = DoubleLinkedListNode(UpperCAmelCase__ , UpperCAmelCase__ ) _UpperCamelCase : Any = self.rear, self.head def __repr__( self : str ) -> int: _UpperCamelCase : Optional[int] = ['''DoubleLinkedList'''] _UpperCamelCase : str = self.head while node.next is not None: rep.append(str(UpperCAmelCase__ ) ) _UpperCamelCase : Union[str, Any] = node.next rep.append(str(self.rear ) ) return ",\n ".join(UpperCAmelCase__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : DoubleLinkedListNode[T, U] ) -> Optional[Any]: _UpperCamelCase : Optional[Any] = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None _UpperCamelCase : Tuple = node _UpperCamelCase : Union[str, Any] = previous _UpperCamelCase : List[str] = node _UpperCamelCase : Tuple = self.rear def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : DoubleLinkedListNode[T, U] ) -> Optional[int]: if node.prev is None or node.next is None: return None _UpperCamelCase : Union[str, Any] = node.next _UpperCamelCase : Dict = node.prev _UpperCamelCase : List[str] = None _UpperCamelCase : Optional[Any] = None return node class __SCREAMING_SNAKE_CASE ( Generic[T, U] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :dict[Callable[[T], U], LRUCache[T, U]] = {} def __init__( self : Dict , __a : int ) -> List[str]: _UpperCamelCase : DoubleLinkedList[T, U] = DoubleLinkedList() _UpperCamelCase : List[Any] = capacity _UpperCamelCase : Tuple = 0 _UpperCamelCase : Union[str, Any] = 0 _UpperCamelCase : List[str] = 0 _UpperCamelCase : dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__( self : Tuple ) -> Optional[int]: return ( F'''CacheInfo(hits={self.hits}, misses={self.miss}, ''' F'''capacity={self.capacity}, current size={self.num_keys})''' ) def __contains__( self : Dict , __a : T ) -> Tuple: return key in self.cache def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : T ) -> str: # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 _UpperCamelCase : DoubleLinkedListNode[T, U] = self.cache[key] _UpperCamelCase : Optional[int] = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(UpperCAmelCase__ ) return node.val self.miss += 1 return None def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : T , __a : U ) -> Any: if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity _UpperCamelCase : Dict = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(UpperCAmelCase__ ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 _UpperCamelCase : Dict = DoubleLinkedListNode(UpperCAmelCase__ , UpperCAmelCase__ ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value _UpperCamelCase : Dict = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list _UpperCamelCase : List[Any] = value self.list.add(UpperCAmelCase__ ) @classmethod def __SCREAMING_SNAKE_CASE ( cls : Dict , __a : int = 128 ) -> int: def cache_decorator_inner(__a : Callable[[T], U] ) -> Callable[..., U]: def cache_decorator_wrapper(*__a : T ) -> U: if func not in cls.decorator_function_to_instance_map: _UpperCamelCase : str = LRUCache(UpperCAmelCase__ ) _UpperCamelCase : str = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: _UpperCamelCase : List[str] = func(*UpperCAmelCase__ ) cls.decorator_function_to_instance_map[func].put(args[0] , UpperCAmelCase__ ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(UpperCAmelCase__ , "cache_info" , UpperCAmelCase__ ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
717
"""simple docstring""" import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def lowercase__ ( lowercase_ ,lowercase_=7 ) -> Tuple: """simple docstring""" _UpperCamelCase : Optional[int] = None if token is not None: _UpperCamelCase : Optional[Any] = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} # The id of a workflow (not of a workflow run) _UpperCamelCase : Any = "636036" _UpperCamelCase : Tuple = F'''https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs''' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'''?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}''' _UpperCamelCase : Dict = requests.get(lowercase_ ,headers=lowercase_ ).json() return result["workflow_runs"] def lowercase__ ( lowercase_ ) -> List[str]: """simple docstring""" _UpperCamelCase : List[Any] = get_daily_ci_runs(lowercase_ ) _UpperCamelCase : Tuple = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": _UpperCamelCase : Union[str, Any] = workflow_run["id"] break return workflow_run_id def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Optional[int]: """simple docstring""" _UpperCamelCase : str = get_last_daily_ci_runs(lowercase_ ) if workflow_run_id is not None: _UpperCamelCase : int = get_artifacts_links(worflow_run_id=lowercase_ ,token=lowercase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: _UpperCamelCase : Dict = artifacts_links[artifact_name] download_artifact( artifact_name=lowercase_ ,artifact_url=lowercase_ ,output_dir=lowercase_ ,token=lowercase_ ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> int: """simple docstring""" get_last_daily_ci_artifacts(lowercase_ ,lowercase_ ,lowercase_ ) _UpperCamelCase : Dict = {} for artifact_name in artifact_names: _UpperCamelCase : Union[str, Any] = os.path.join(lowercase_ ,F'''{artifact_name}.zip''' ) if os.path.isfile(lowercase_ ): _UpperCamelCase : int = {} with zipfile.ZipFile(lowercase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowercase_ ): # read the file with z.open(lowercase_ ) as f: _UpperCamelCase : int = f.read().decode("UTF-8" ) return results
51
0
"""simple docstring""" def lowercase__ ( lowercase_ ,lowercase_ = False ) -> str: """simple docstring""" if not isinstance(lowercase_ ,lowercase_ ): _UpperCamelCase : Optional[int] = F'''Expected string as input, found {type(lowercase_ )}''' raise ValueError(lowercase_ ) if not isinstance(lowercase_ ,lowercase_ ): _UpperCamelCase : Union[str, Any] = F'''Expected boolean as use_pascal parameter, found {type(lowercase_ )}''' raise ValueError(lowercase_ ) _UpperCamelCase : List[str] = input_str.split("_" ) _UpperCamelCase : Optional[int] = 0 if use_pascal else 1 _UpperCamelCase : List[str] = words[start_index:] _UpperCamelCase : Any = [word[0].upper() + word[1:] for word in words_to_capitalize] _UpperCamelCase : str = "" if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
718
"""simple docstring""" import math class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Any , __a : list[list[float]] , __a : list[int] ) -> int: _UpperCamelCase : List[Any] = 0.0 _UpperCamelCase : Union[str, Any] = 0.0 for i in range(len(__a ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : list[list[int | float]] , __a : list[int] , __a : int , __a : float ) -> list[list[int | float]]: for i in range(len(__a ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def lowercase__ ( ) -> None: """simple docstring""" _UpperCamelCase : Optional[int] = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) _UpperCamelCase : List[str] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training _UpperCamelCase : List[Any] = SelfOrganizingMap() _UpperCamelCase : int = 3 _UpperCamelCase : List[Any] = 0.5 for _ in range(lowercase_ ): for j in range(len(lowercase_ ) ): # training sample _UpperCamelCase : int = training_samples[j] # Compute the winning vector _UpperCamelCase : Tuple = self_organizing_map.get_winner(lowercase_ ,lowercase_ ) # Update the winning vector _UpperCamelCase : int = self_organizing_map.update(lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) # classify test sample _UpperCamelCase : Optional[int] = [0, 0, 0, 1] _UpperCamelCase : Dict = self_organizing_map.get_winner(lowercase_ ,lowercase_ ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
51
0
"""simple docstring""" import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: _UpperCamelCase : Tuple = FlaxXLMRobertaModel.from_pretrained("xlm-roberta-base" ) _UpperCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained("xlm-roberta-base" ) _UpperCamelCase : int = "The dog is cute and lives in the garden house" _UpperCamelCase : Optional[Any] = jnp.array([tokenizer.encode(SCREAMING_SNAKE_CASE_ )] ) _UpperCamelCase : Optional[int] = (1, 12, 768) # batch_size, sequence_length, embedding_vector_dim _UpperCamelCase : Tuple = jnp.array( [[-0.01_01, 0.12_18, -0.08_03, 0.08_01, 0.13_27, 0.07_76, -0.12_15, 0.23_83, 0.33_38, 0.31_06, 0.03_00, 0.02_52]] ) _UpperCamelCase : str = model(SCREAMING_SNAKE_CASE_ )["last_hidden_state"] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) )
719
"""simple docstring""" import argparse import collections import os import re 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/check_table.py lowerCamelCase__ = "src/transformers" lowerCamelCase__ = "docs/source/en" lowerCamelCase__ = "." def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> List[str]: """simple docstring""" with open(lowercase_ ,"r" ,encoding="utf-8" ,newline="\n" ) as f: _UpperCamelCase : Union[str, Any] = f.readlines() # Find the start prompt. _UpperCamelCase : Dict = 0 while not lines[start_index].startswith(lowercase_ ): start_index += 1 start_index += 1 _UpperCamelCase : Optional[int] = start_index while not lines[end_index].startswith(lowercase_ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | lowerCamelCase__ = "Model|Encoder|Decoder|ForConditionalGeneration" # 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)") # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase__ = direct_transformers_import(TRANSFORMERS_PATH) def lowercase__ ( lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Tuple = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)" ,lowercase_ ) return [m.group(0 ) for m in matches] def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : str = 2 if text == "✅" or text == "❌" else len(lowercase_ ) _UpperCamelCase : Union[str, Any] = (width - text_length) // 2 _UpperCamelCase : Dict = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def lowercase__ ( ) -> str: """simple docstring""" _UpperCamelCase : Optional[Any] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _UpperCamelCase : str = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } _UpperCamelCase : Dict = {name: config.replace("Config" ,"" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. _UpperCamelCase : int = collections.defaultdict(lowercase_ ) _UpperCamelCase : Dict = collections.defaultdict(lowercase_ ) _UpperCamelCase : Dict = collections.defaultdict(lowercase_ ) _UpperCamelCase : int = collections.defaultdict(lowercase_ ) _UpperCamelCase : str = collections.defaultdict(lowercase_ ) # Let's lookup through all transformers object (once). for attr_name in dir(lowercase_ ): _UpperCamelCase : List[str] = None if attr_name.endswith("Tokenizer" ): _UpperCamelCase : Tuple = slow_tokenizers _UpperCamelCase : Any = attr_name[:-9] elif attr_name.endswith("TokenizerFast" ): _UpperCamelCase : Optional[Any] = fast_tokenizers _UpperCamelCase : List[str] = attr_name[:-13] elif _re_tf_models.match(lowercase_ ) is not None: _UpperCamelCase : List[Any] = tf_models _UpperCamelCase : Dict = _re_tf_models.match(lowercase_ ).groups()[0] elif _re_flax_models.match(lowercase_ ) is not None: _UpperCamelCase : Dict = flax_models _UpperCamelCase : Union[str, Any] = _re_flax_models.match(lowercase_ ).groups()[0] elif _re_pt_models.match(lowercase_ ) is not None: _UpperCamelCase : Optional[int] = pt_models _UpperCamelCase : Any = _re_pt_models.match(lowercase_ ).groups()[0] if lookup_dict is not None: while len(lowercase_ ) > 0: if attr_name in model_name_to_prefix.values(): _UpperCamelCase : Dict = True break # Try again after removing the last word in the name _UpperCamelCase : List[str] = "".join(camel_case_split(lowercase_ )[:-1] ) # Let's build that table! _UpperCamelCase : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) _UpperCamelCase : List[str] = ["Model", "Tokenizer slow", "Tokenizer fast", "PyTorch support", "TensorFlow support", "Flax Support"] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). _UpperCamelCase : Union[str, Any] = [len(lowercase_ ) + 2 for c in columns] _UpperCamelCase : Any = max([len(lowercase_ ) for name in model_names] ) + 2 # Build the table per se _UpperCamelCase : Tuple = "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for c, w in zip(lowercase_ ,lowercase_ )] ) + "|\n" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths] ) + "|\n" _UpperCamelCase : Union[str, Any] = {True: "✅", False: "❌"} for name in model_names: _UpperCamelCase : Optional[int] = model_name_to_prefix[name] _UpperCamelCase : Tuple = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for l, w in zip(lowercase_ ,lowercase_ )] ) + "|\n" return table def lowercase__ ( lowercase_=False ) -> List[Any]: """simple docstring""" _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : str = _find_text_in_file( filename=os.path.join(lowercase_ ,"index.md" ) ,start_prompt="<!--This table is updated automatically from the auto modules" ,end_prompt="<!-- End table-->" ,) _UpperCamelCase : Any = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(lowercase_ ,"index.md" ) ,"w" ,encoding="utf-8" ,newline="\n" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( "The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this." ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") lowerCamelCase__ = parser.parse_args() check_model_table(args.fix_and_overwrite)
51
0
"""simple docstring""" from itertools import count def lowercase__ ( lowercase_ = 50 ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Dict = [1] * min_block_length for n in count(lowercase_ ): fill_count_functions.append(1 ) for block_length in range(lowercase_ ,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] > 1_000_000: break return n if __name__ == "__main__": print(f"""{solution() = }""")
720
"""simple docstring""" from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. lowerCamelCase__ = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. lowerCamelCase__ = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. lowerCamelCase__ = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def lowercase__ ( lowercase_ ,lowercase_ ) -> tuple[str, float]: """simple docstring""" _UpperCamelCase : str = len([g for position, g in enumerate(lowercase_ ) if g == main_target[position]] ) return (item, float(lowercase_ )) def lowercase__ ( lowercase_ ,lowercase_ ) -> tuple[str, str]: """simple docstring""" _UpperCamelCase : Tuple = random.randint(0 ,len(lowercase_ ) - 1 ) _UpperCamelCase : Dict = parent_a[:random_slice] + parent_a[random_slice:] _UpperCamelCase : Tuple = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def lowercase__ ( lowercase_ ,lowercase_ ) -> str: """simple docstring""" _UpperCamelCase : int = list(lowercase_ ) if random.uniform(0 ,1 ) < MUTATION_PROBABILITY: _UpperCamelCase : int = random.choice(lowercase_ ) return "".join(lowercase_ ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,) -> list[str]: """simple docstring""" _UpperCamelCase : Optional[Any] = [] # Generate more children proportionally to the fitness score. _UpperCamelCase : List[str] = int(parent_a[1] * 100 ) + 1 _UpperCamelCase : Union[str, Any] = 10 if child_n >= 10 else child_n for _ in range(lowercase_ ): _UpperCamelCase : Dict = population_score[random.randint(0 ,lowercase_ )][0] _UpperCamelCase, _UpperCamelCase : Dict = crossover(parent_a[0] ,lowercase_ ) # Append new string to the population list. pop.append(mutate(lowercase_ ,lowercase_ ) ) pop.append(mutate(lowercase_ ,lowercase_ ) ) return pop def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ = True ) -> tuple[int, int, str]: """simple docstring""" if N_POPULATION < N_SELECTED: _UpperCamelCase : List[str] = F'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(lowercase_ ) # Verify that the target contains no genes besides the ones inside genes variable. _UpperCamelCase : int = sorted({c for c in target if c not in genes} ) if not_in_genes_list: _UpperCamelCase : int = F'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(lowercase_ ) # Generate random starting population. _UpperCamelCase : Union[str, Any] = [] for _ in range(lowercase_ ): population.append("".join([random.choice(lowercase_ ) for i in range(len(lowercase_ ) )] ) ) # Just some logs to know what the algorithms is doing. _UpperCamelCase, _UpperCamelCase : str = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowercase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. _UpperCamelCase : int = [evaluate(lowercase_ ,lowercase_ ) for item in population] # Check if there is a matching evolution. _UpperCamelCase : Optional[Any] = sorted(lowercase_ ,key=lambda lowercase_ : x[1] ,reverse=lowercase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'''\nGeneration: {generation}''' F'''\nTotal Population:{total_population}''' F'''\nBest score: {population_score[0][1]}''' F'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. _UpperCamelCase : str = population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowercase_ ) # Normalize population score to be between 0 and 1. _UpperCamelCase : str = [ (item, score / len(lowercase_ )) for item, score in population_score ] # This is selection for i in range(lowercase_ ): population.extend(select(population_score[int(lowercase_ )] ,lowercase_ ,lowercase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowercase_ ) > N_POPULATION: break if __name__ == "__main__": lowerCamelCase__ = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) lowerCamelCase__ = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = basic(target_str, genes_list) print( f"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}""" )
51
0
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Union[str, Any] = StableDiffusionSAGPipeline SCREAMING_SNAKE_CASE__ :Dict = TEXT_TO_IMAGE_PARAMS SCREAMING_SNAKE_CASE__ :Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS SCREAMING_SNAKE_CASE__ :Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS SCREAMING_SNAKE_CASE__ :Any = TEXT_TO_IMAGE_IMAGE_PARAMS SCREAMING_SNAKE_CASE__ :Union[str, Any] = False def __SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: torch.manual_seed(0 ) _UpperCamelCase : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) _UpperCamelCase : Union[str, Any] = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase__ , set_alpha_to_one=UpperCAmelCase__ , ) torch.manual_seed(0 ) _UpperCamelCase : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) _UpperCamelCase : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) _UpperCamelCase : str = CLIPTextModel(UpperCAmelCase__ ) _UpperCamelCase : Tuple = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) _UpperCamelCase : int = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __SCREAMING_SNAKE_CASE ( self : Any , __a : Any , __a : List[str]=0 ) -> Tuple: if str(UpperCAmelCase__ ).startswith("mps" ): _UpperCamelCase : List[Any] = torch.manual_seed(UpperCAmelCase__ ) else: _UpperCamelCase : Optional[Any] = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) _UpperCamelCase : Any = { '''prompt''': '''.''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 1.0, '''sag_scale''': 1.0, '''output_type''': '''numpy''', } return inputs def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE ( self : Dict ) -> int: _UpperCamelCase : int = StableDiffusionSAGPipeline.from_pretrained("CompVis/stable-diffusion-v1-4" ) _UpperCamelCase : Tuple = sag_pipe.to(UpperCAmelCase__ ) sag_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _UpperCamelCase : str = '''.''' _UpperCamelCase : int = torch.manual_seed(0 ) _UpperCamelCase : Optional[int] = sag_pipe( [prompt] , generator=UpperCAmelCase__ , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="np" ) _UpperCamelCase : str = output.images _UpperCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _UpperCamelCase : Optional[int] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __SCREAMING_SNAKE_CASE ( self : str ) -> int: _UpperCamelCase : Any = StableDiffusionSAGPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) _UpperCamelCase : Tuple = sag_pipe.to(UpperCAmelCase__ ) sag_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _UpperCamelCase : Optional[int] = '''.''' _UpperCamelCase : List[Any] = torch.manual_seed(0 ) _UpperCamelCase : Optional[int] = sag_pipe( [prompt] , generator=UpperCAmelCase__ , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="np" ) _UpperCamelCase : List[Any] = output.images _UpperCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _UpperCamelCase : Any = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: _UpperCamelCase : List[str] = StableDiffusionSAGPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) _UpperCamelCase : List[str] = sag_pipe.to(UpperCAmelCase__ ) sag_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) _UpperCamelCase : List[str] = '''.''' _UpperCamelCase : List[str] = torch.manual_seed(0 ) _UpperCamelCase : List[Any] = sag_pipe( [prompt] , width=768 , height=512 , generator=UpperCAmelCase__ , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="np" , ) _UpperCamelCase : Any = output.images assert image.shape == (1, 512, 768, 3)
721
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = ["model.decoder.embed_positions.weights"] def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" if "emb" in name: _UpperCamelCase : List[str] = name.replace("emb" ,"model.decoder.embed_tokens" ) if "transformer" in name: _UpperCamelCase : Optional[int] = name.replace("transformer" ,"model.decoder" ) if "cross_attention" in name: _UpperCamelCase : Optional[int] = name.replace("cross_attention" ,"encoder_attn" ) if "linear1" in name: _UpperCamelCase : Optional[Any] = name.replace("linear1" ,"fc1" ) if "linear2" in name: _UpperCamelCase : Union[str, Any] = name.replace("linear2" ,"fc2" ) if "norm1" in name: _UpperCamelCase : Optional[Any] = name.replace("norm1" ,"self_attn_layer_norm" ) if "norm_cross" in name: _UpperCamelCase : Dict = name.replace("norm_cross" ,"encoder_attn_layer_norm" ) if "norm2" in name: _UpperCamelCase : Union[str, Any] = name.replace("norm2" ,"final_layer_norm" ) if "out_norm" in name: _UpperCamelCase : Union[str, Any] = name.replace("out_norm" ,"model.decoder.layer_norm" ) if "linears" in name: _UpperCamelCase : List[str] = name.replace("linears" ,"lm_heads" ) if "condition_provider.conditioners.description.output_proj" in name: _UpperCamelCase : Any = name.replace("condition_provider.conditioners.description.output_proj" ,"enc_to_dec_proj" ) return name def lowercase__ ( lowercase_ ,lowercase_ ) -> Tuple[Dict, Dict]: """simple docstring""" _UpperCamelCase : str = list(state_dict.keys() ) _UpperCamelCase : Optional[Any] = {} for key in keys: _UpperCamelCase : Optional[int] = state_dict.pop(lowercase_ ) _UpperCamelCase : List[Any] = rename_keys(lowercase_ ) if "in_proj_weight" in key: # split fused qkv proj _UpperCamelCase : Tuple = val[:hidden_size, :] _UpperCamelCase : Optional[Any] = val[hidden_size : 2 * hidden_size, :] _UpperCamelCase : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _UpperCamelCase : Optional[Any] = val else: _UpperCamelCase : List[str] = val return state_dict, enc_dec_proj_state_dict def lowercase__ ( lowercase_ ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values _UpperCamelCase : List[Any] = 1_024 _UpperCamelCase : List[str] = 24 _UpperCamelCase : Any = 16 elif checkpoint == "medium": _UpperCamelCase : Tuple = 1_536 _UpperCamelCase : Dict = 48 _UpperCamelCase : Tuple = 24 elif checkpoint == "large": _UpperCamelCase : int = 2_048 _UpperCamelCase : Optional[int] = 48 _UpperCamelCase : Dict = 32 else: raise ValueError(F'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' ) _UpperCamelCase : str = MusicgenDecoderConfig( hidden_size=lowercase_ ,ffn_dim=hidden_size * 4 ,num_hidden_layers=lowercase_ ,num_attention_heads=lowercase_ ,) return config @torch.no_grad() def lowercase__ ( lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_="cpu" ) -> List[str]: """simple docstring""" _UpperCamelCase : str = MusicGen.get_pretrained(lowercase_ ,device=lowercase_ ) _UpperCamelCase : Union[str, Any] = decoder_config_from_checkpoint(lowercase_ ) _UpperCamelCase : Optional[int] = fairseq_model.lm.state_dict() _UpperCamelCase, _UpperCamelCase : Optional[Any] = rename_state_dict( lowercase_ ,hidden_size=decoder_config.hidden_size ) _UpperCamelCase : Tuple = TaEncoderModel.from_pretrained("t5-base" ) _UpperCamelCase : Union[str, Any] = EncodecModel.from_pretrained("facebook/encodec_32khz" ) _UpperCamelCase : str = MusicgenForCausalLM(lowercase_ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _UpperCamelCase, _UpperCamelCase : str = decoder.load_state_dict(lowercase_ ,strict=lowercase_ ) for key in missing_keys.copy(): if key.startswith(("text_encoder", "audio_encoder") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(lowercase_ ) if len(lowercase_ ) > 0: raise ValueError(F'''Missing key(s) in state_dict: {missing_keys}''' ) if len(lowercase_ ) > 0: raise ValueError(F'''Unexpected key(s) in state_dict: {unexpected_keys}''' ) # init the composite model _UpperCamelCase : str = MusicgenForConditionalGeneration(text_encoder=lowercase_ ,audio_encoder=lowercase_ ,decoder=lowercase_ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(lowercase_ ) # check we can do a forward pass _UpperCamelCase : List[str] = torch.arange(0 ,8 ,dtype=torch.long ).reshape(2 ,-1 ) _UpperCamelCase : Dict = input_ids.reshape(2 * 4 ,-1 ) with torch.no_grad(): _UpperCamelCase : Tuple = model(input_ids=lowercase_ ,decoder_input_ids=lowercase_ ).logits if logits.shape != (8, 1, 2_048): raise ValueError("Incorrect shape for logits" ) # now construct the processor _UpperCamelCase : int = AutoTokenizer.from_pretrained("t5-base" ) _UpperCamelCase : str = AutoFeatureExtractor.from_pretrained("facebook/encodec_32khz" ,padding_side="left" ) _UpperCamelCase : Optional[int] = MusicgenProcessor(feature_extractor=lowercase_ ,tokenizer=lowercase_ ) # set the appropriate bos/pad token ids _UpperCamelCase : str = 2_048 _UpperCamelCase : str = 2_048 # set other default generation config params _UpperCamelCase : Optional[Any] = int(30 * audio_encoder.config.frame_rate ) _UpperCamelCase : List[str] = True _UpperCamelCase : int = 3.0 if pytorch_dump_folder is not None: Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) logger.info(F'''Saving model {checkpoint} to {pytorch_dump_folder}''' ) model.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) if repo_id: logger.info(F'''Pushing model {checkpoint} to {repo_id}''' ) model.push_to_hub(lowercase_ ) processor.push_to_hub(lowercase_ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) lowerCamelCase__ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
51
0
"""simple docstring""" import requests def lowercase__ ( lowercase_ ,lowercase_ ) -> Optional[int]: """simple docstring""" _UpperCamelCase : Optional[Any] = {"Content-Type": "application/json"} _UpperCamelCase : List[str] = requests.post(_lowerCAmelCase ,json={"text": message_body} ,headers=_lowerCAmelCase ) if response.status_code != 200: _UpperCamelCase : Any = ( "Request to slack returned an error " F'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(_lowerCAmelCase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
700
"""simple docstring""" from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowerCamelCase__ = input("Enter image url: ").strip() print(f"""Downloading image from {url} ...""") lowerCamelCase__ = BeautifulSoup(requests.get(url).content, "html.parser") # The image URL is in the content field of the first meta tag with property og:image lowerCamelCase__ = soup.find("meta", {"property": "og:image"})["content"] lowerCamelCase__ = requests.get(image_url).content lowerCamelCase__ = f"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, "wb") as fp: fp.write(image_data) print(f"""Done. Image saved to disk as {file_name}.""")
51
0
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :int = AutoencoderKL SCREAMING_SNAKE_CASE__ :List[str] = "sample" SCREAMING_SNAKE_CASE__ :List[Any] = 1e-2 @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: _UpperCamelCase : str = 4 _UpperCamelCase : int = 3 _UpperCamelCase : List[Any] = (32, 32) _UpperCamelCase : Tuple = floats_tensor((batch_size, num_channels) + sizes ).to(__lowerCamelCase ) return {"sample": image} @property def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: return (3, 32, 32) @property def __SCREAMING_SNAKE_CASE ( self : str ) -> str: return (3, 32, 32) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Dict: _UpperCamelCase : int = { '''block_out_channels''': [32, 64], '''in_channels''': 3, '''out_channels''': 3, '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''], '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''], '''latent_channels''': 4, } _UpperCamelCase : str = self.dummy_input return init_dict, inputs_dict def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: pass def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: _UpperCamelCase : int = self.prepare_init_args_and_inputs_for_common() _UpperCamelCase : Tuple = self.model_class(**__lowerCamelCase ) model.to(__lowerCamelCase ) assert not model.is_gradient_checkpointing and model.training _UpperCamelCase : Tuple = model(**__lowerCamelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() _UpperCamelCase : Optional[Any] = torch.randn_like(__lowerCamelCase ) _UpperCamelCase : Tuple = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing _UpperCamelCase : str = self.model_class(**__lowerCamelCase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__lowerCamelCase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training _UpperCamelCase : Dict = model_a(**__lowerCamelCase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() _UpperCamelCase : Any = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1e-5 ) _UpperCamelCase : List[str] = dict(model.named_parameters() ) _UpperCamelCase : Optional[Any] = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5 ) ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: _UpperCamelCase : str = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(__lowerCamelCase ) _UpperCamelCase : Optional[int] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]: _UpperCamelCase : str = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) _UpperCamelCase : Tuple = model.to(__lowerCamelCase ) model.eval() if torch_device == "mps": _UpperCamelCase : Union[str, Any] = torch.manual_seed(0 ) else: _UpperCamelCase : Any = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) _UpperCamelCase : Optional[int] = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) _UpperCamelCase : Dict = image.to(__lowerCamelCase ) with torch.no_grad(): _UpperCamelCase : List[Any] = model(__lowerCamelCase , sample_posterior=__lowerCamelCase , generator=__lowerCamelCase ).sample _UpperCamelCase : Optional[Any] = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": _UpperCamelCase : List[str] = torch.tensor( [ -4.0_0_7_8e-0_1, -3.8_3_2_3e-0_4, -1.2_6_8_1e-0_1, -1.1_4_6_2e-0_1, 2.0_0_9_5e-0_1, 1.0_8_9_3e-0_1, -8.8_2_4_7e-0_2, -3.0_3_6_1e-0_1, -9.8_6_4_4e-0_3, ] ) elif torch_device == "cpu": _UpperCamelCase : str = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: _UpperCamelCase : Any = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(__lowerCamelCase , __lowerCamelCase , rtol=1e-2 ) ) @slow class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Union[str, Any] , __a : str ) -> List[Any]: return F'''gaussian_noise_s={seed}_shape={'_'.join([str(__lowerCamelCase ) for s in shape] )}.npy''' def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE ( self : int , __a : Union[str, Any]=0 , __a : Tuple=(4, 3, 512, 512) , __a : Tuple=False ) -> Any: _UpperCamelCase : Optional[int] = torch.floataa if fpaa else torch.floataa _UpperCamelCase : Dict = torch.from_numpy(load_hf_numpy(self.get_file_format(__lowerCamelCase , __lowerCamelCase ) ) ).to(__lowerCamelCase ).to(__lowerCamelCase ) return image def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Dict="CompVis/stable-diffusion-v1-4" , __a : int=False ) -> List[str]: _UpperCamelCase : Dict = '''fp16''' if fpaa else None _UpperCamelCase : Optional[Any] = torch.floataa if fpaa else torch.floataa _UpperCamelCase : List[Any] = AutoencoderKL.from_pretrained( __lowerCamelCase , subfolder="vae" , torch_dtype=__lowerCamelCase , revision=__lowerCamelCase , ) model.to(__lowerCamelCase ).eval() return model def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : Optional[Any]=0 ) -> str: if torch_device == "mps": return torch.manual_seed(__lowerCamelCase ) return torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : int , __a : int , __a : List[Any] ) -> Union[str, Any]: _UpperCamelCase : Optional[int] = self.get_sd_vae_model() _UpperCamelCase : Any = self.get_sd_image(__lowerCamelCase ) _UpperCamelCase : List[str] = self.get_generator(__lowerCamelCase ) with torch.no_grad(): _UpperCamelCase : Dict = model(__lowerCamelCase , generator=__lowerCamelCase , sample_posterior=__lowerCamelCase ).sample assert sample.shape == image.shape _UpperCamelCase : Optional[Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() _UpperCamelCase : Any = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__lowerCamelCase , __lowerCamelCase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : List[Any] , __a : str ) -> Dict: _UpperCamelCase : Union[str, Any] = self.get_sd_vae_model(fpaa=__lowerCamelCase ) _UpperCamelCase : List[str] = self.get_sd_image(__lowerCamelCase , fpaa=__lowerCamelCase ) _UpperCamelCase : List[Any] = self.get_generator(__lowerCamelCase ) with torch.no_grad(): _UpperCamelCase : Optional[Any] = model(__lowerCamelCase , generator=__lowerCamelCase , sample_posterior=__lowerCamelCase ).sample assert sample.shape == image.shape _UpperCamelCase : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() _UpperCamelCase : Any = torch.tensor(__lowerCamelCase ) assert torch_all_close(__lowerCamelCase , __lowerCamelCase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Tuple , __a : Any , __a : Any ) -> Optional[Any]: _UpperCamelCase : int = self.get_sd_vae_model() _UpperCamelCase : Dict = self.get_sd_image(__lowerCamelCase ) with torch.no_grad(): _UpperCamelCase : Tuple = model(__lowerCamelCase ).sample assert sample.shape == image.shape _UpperCamelCase : Dict = sample[-1, -2:, -2:, :2].flatten().float().cpu() _UpperCamelCase : List[Any] = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__lowerCamelCase , __lowerCamelCase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : Dict , __a : List[str] ) -> Any: _UpperCamelCase : Tuple = self.get_sd_vae_model() _UpperCamelCase : Union[str, Any] = self.get_sd_image(__lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): _UpperCamelCase : str = model.decode(__lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] _UpperCamelCase : Dict = sample[-1, -2:, :2, -2:].flatten().cpu() _UpperCamelCase : Any = torch.tensor(__lowerCamelCase ) assert torch_all_close(__lowerCamelCase , __lowerCamelCase , atol=1e-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def __SCREAMING_SNAKE_CASE ( self : str , __a : Tuple , __a : str ) -> Optional[int]: _UpperCamelCase : Any = self.get_sd_vae_model(fpaa=__lowerCamelCase ) _UpperCamelCase : Dict = self.get_sd_image(__lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=__lowerCamelCase ) with torch.no_grad(): _UpperCamelCase : Optional[Any] = model.decode(__lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] _UpperCamelCase : Dict = sample[-1, -2:, :2, -2:].flatten().float().cpu() _UpperCamelCase : Union[str, Any] = torch.tensor(__lowerCamelCase ) assert torch_all_close(__lowerCamelCase , __lowerCamelCase , atol=5e-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : Union[str, Any] ) -> Any: _UpperCamelCase : Any = self.get_sd_vae_model(fpaa=__lowerCamelCase ) _UpperCamelCase : str = self.get_sd_image(__lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=__lowerCamelCase ) with torch.no_grad(): _UpperCamelCase : Any = model.decode(__lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): _UpperCamelCase : Optional[Any] = model.decode(__lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__lowerCamelCase , __lowerCamelCase , atol=1e-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : Tuple ) -> Optional[Any]: _UpperCamelCase : Optional[int] = self.get_sd_vae_model() _UpperCamelCase : Dict = self.get_sd_image(__lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): _UpperCamelCase : Tuple = model.decode(__lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): _UpperCamelCase : Optional[Any] = model.decode(__lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__lowerCamelCase , __lowerCamelCase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def __SCREAMING_SNAKE_CASE ( self : str , __a : List[Any] , __a : Optional[int] ) -> List[str]: _UpperCamelCase : Tuple = self.get_sd_vae_model() _UpperCamelCase : Tuple = self.get_sd_image(__lowerCamelCase ) _UpperCamelCase : Optional[Any] = self.get_generator(__lowerCamelCase ) with torch.no_grad(): _UpperCamelCase : List[Any] = model.encode(__lowerCamelCase ).latent_dist _UpperCamelCase : int = dist.sample(generator=__lowerCamelCase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] _UpperCamelCase : Optional[int] = sample[0, -1, -3:, -3:].flatten().cpu() _UpperCamelCase : int = torch.tensor(__lowerCamelCase ) _UpperCamelCase : Any = 3e-3 if torch_device != '''mps''' else 1e-2 assert torch_all_close(__lowerCamelCase , __lowerCamelCase , atol=__lowerCamelCase )
701
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append(".") def lowercase__ ( lowercase_ ) -> int: """simple docstring""" _UpperCamelCase : Any = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " F'''{test_file} instead.''' ) _UpperCamelCase : str = components[-1] if not test_fn.endswith("py" ): raise ValueError(F'''`test_file` should be a python file. Got {test_fn} instead.''' ) if not test_fn.startswith("test_modeling_" ): raise ValueError( F'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.''' ) _UpperCamelCase : Dict = components[:-1] + [test_fn.replace(".py" ,"" )] _UpperCamelCase : List[str] = ".".join(lowercase_ ) return test_module_path def lowercase__ ( lowercase_ ) -> List[Any]: """simple docstring""" _UpperCamelCase : Optional[Any] = get_module_path(lowercase_ ) _UpperCamelCase : str = importlib.import_module(lowercase_ ) return test_module def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : Union[str, Any] = [] _UpperCamelCase : List[Any] = get_test_module(lowercase_ ) for attr in dir(lowercase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowercase_ ,lowercase_ ) ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Tuple: """simple docstring""" _UpperCamelCase : Optional[Any] = [] _UpperCamelCase : Any = get_test_module(lowercase_ ) for attr in dir(lowercase_ ): _UpperCamelCase : int = getattr(lowercase_ ,lowercase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). _UpperCamelCase : Optional[Any] = getattr(lowercase_ ,"all_model_classes" ,[] ) if len(lowercase_ ) > 0: test_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Dict = get_test_classes(lowercase_ ) _UpperCamelCase : int = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : List[str] = test_class() if hasattr(lowercase_ ,"setUp" ): test.setUp() _UpperCamelCase : Tuple = None if hasattr(lowercase_ ,"model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: _UpperCamelCase : Tuple = test.model_tester.__class__ return model_tester def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : str = get_test_classes(lowercase_ ) _UpperCamelCase : Dict = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ,lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : Any = get_test_classes_for_model(lowercase_ ,lowercase_ ) _UpperCamelCase : List[Any] = [] for test_class in test_classes: _UpperCamelCase : List[Any] = get_model_tester_from_test_class(lowercase_ ) if tester_class is not None: tester_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Any = get_test_classes(lowercase_ ) _UpperCamelCase : Tuple = {test_class: get_model_tester_from_test_class(lowercase_ ) for test_class in test_classes} return test_tester_mapping def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : List[Any] = get_model_classes(lowercase_ ) _UpperCamelCase : Optional[int] = { model_class: get_test_classes_for_model(lowercase_ ,lowercase_ ) for model_class in model_classes } return model_test_mapping def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Optional[Any] = get_model_classes(lowercase_ ) _UpperCamelCase : Tuple = { model_class: get_tester_classes_for_model(lowercase_ ,lowercase_ ) for model_class in model_classes } return model_to_tester_mapping def lowercase__ ( lowercase_ ) -> Optional[int]: """simple docstring""" if isinstance(lowercase_ ,lowercase_ ): return o elif isinstance(lowercase_ ,lowercase_ ): return o.__name__ elif isinstance(lowercase_ ,(list, tuple) ): return [to_json(lowercase_ ) for x in o] elif isinstance(lowercase_ ,lowercase_ ): return {to_json(lowercase_ ): to_json(lowercase_ ) for k, v in o.items()} else: return o
51
0
from queue import PriorityQueue from typing import Any import numpy as np def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,) -> float | int: """simple docstring""" for nxt, d in graph[v]: if nxt in visited_forward: continue _UpperCamelCase : List[str] = cst_fwd.get(UpperCamelCase__ ,np.inf ) _UpperCamelCase : str = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) _UpperCamelCase : List[Any] = new_cost_f _UpperCamelCase : Tuple = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: _UpperCamelCase : Any = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) -> int: """simple docstring""" _UpperCamelCase : Any = -1 _UpperCamelCase : Dict = set() _UpperCamelCase : int = set() _UpperCamelCase : Tuple = {source: 0} _UpperCamelCase : Optional[Any] = {destination: 0} _UpperCamelCase : Dict = {source: None} _UpperCamelCase : List[Any] = {destination: None} _UpperCamelCase : List[Any] = PriorityQueue() _UpperCamelCase : int = PriorityQueue() _UpperCamelCase : Dict = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): _UpperCamelCase, _UpperCamelCase : Optional[int] = queue_forward.get() visited_forward.add(UpperCamelCase__ ) _UpperCamelCase, _UpperCamelCase : str = queue_backward.get() visited_backward.add(UpperCamelCase__ ) _UpperCamelCase : str = pass_and_relaxation( UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,) _UpperCamelCase : List[str] = pass_and_relaxation( UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,UpperCamelCase__ ,) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: _UpperCamelCase : Any = shortest_distance return shortest_path_distance lowerCamelCase__ = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } lowerCamelCase__ = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
702
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure)
51
0
"""simple docstring""" def lowercase__ ( lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : Tuple = generate_pascal_triangle(__SCREAMING_SNAKE_CASE ) for row_idx in range(__SCREAMING_SNAKE_CASE ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=" " ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] ,end=" " ) else: print(triangle[row_idx][col_idx] ,end="" ) print() def lowercase__ ( lowercase_ ) -> Optional[int]: """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) _UpperCamelCase : list[list[int]] = [] for current_row_idx in range(__SCREAMING_SNAKE_CASE ): _UpperCamelCase : Dict = populate_current_row(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) triangle.append(__SCREAMING_SNAKE_CASE ) return triangle def lowercase__ ( lowercase_ ,lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : Dict = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 _UpperCamelCase : Union[str, Any] = 1, 1 for current_col_idx in range(1 ,__SCREAMING_SNAKE_CASE ): calculate_current_element( __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) return current_row def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,) -> Dict: """simple docstring""" _UpperCamelCase : Dict = triangle[current_row_idx - 1][current_col_idx - 1] _UpperCamelCase : Optional[Any] = triangle[current_row_idx - 1][current_col_idx] _UpperCamelCase : List[Any] = above_to_left_elt + above_to_right_elt def lowercase__ ( lowercase_ ) -> Tuple: """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) _UpperCamelCase : list[list[int]] = [[1]] for row_index in range(1 ,__SCREAMING_SNAKE_CASE ): _UpperCamelCase : Any = [0] + result[-1] + [0] _UpperCamelCase : Dict = row_index + 1 # Calculate the number of distinct elements in a row _UpperCamelCase : Any = sum(divmod(__SCREAMING_SNAKE_CASE ,2 ) ) _UpperCamelCase : Tuple = [ temp_row[i - 1] + temp_row[i] for i in range(1 ,distinct_elements + 1 ) ] _UpperCamelCase : Dict = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() _UpperCamelCase : Optional[int] = row_first_half + row_second_half result.append(__SCREAMING_SNAKE_CASE ) return result def lowercase__ ( ) -> Optional[int]: """simple docstring""" from collections.abc import Callable from timeit import timeit def benchmark_a_function(lowercase_ ,lowercase_ ) -> None: _UpperCamelCase : int = F'''{func.__name__}({value})''' _UpperCamelCase : List[Any] = timeit(F'''__main__.{call}''' ,setup="import __main__" ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(F'''{call:38} -- {timing:.4f} seconds''' ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
703
"""simple docstring""" lowerCamelCase__ = "\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCamelCase__ = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase__ = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
51
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any , __a : str , __a : Dict=7 , __a : Optional[int]=3 , __a : Optional[Any]=18 , __a : Union[str, Any]=30 , __a : Union[str, Any]=400 , __a : Tuple=True , __a : Union[str, Any]=None , __a : Any=True , ) -> Any: _UpperCamelCase : Any = size if size is not None else {"height": 18, "width": 18} _UpperCamelCase : List[Any] = parent _UpperCamelCase : str = batch_size _UpperCamelCase : Optional[int] = num_channels _UpperCamelCase : Union[str, Any] = image_size _UpperCamelCase : int = min_resolution _UpperCamelCase : Dict = max_resolution _UpperCamelCase : Union[str, Any] = do_resize _UpperCamelCase : Optional[int] = size _UpperCamelCase : Union[str, Any] = apply_ocr def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __SCREAMING_SNAKE_CASE ( _UpperCAmelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[int] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def __SCREAMING_SNAKE_CASE ( self : str ) -> Any: _UpperCamelCase : Optional[int] = LayoutLMvaImageProcessingTester(self ) @property def __SCREAMING_SNAKE_CASE ( self : int ) -> Dict: return self.image_processor_tester.prepare_image_processor_dict() def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: _UpperCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A_ , "do_resize" ) ) self.assertTrue(hasattr(A_ , "size" ) ) self.assertTrue(hasattr(A_ , "apply_ocr" ) ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: _UpperCamelCase : str = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) _UpperCamelCase : int = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: pass def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: # Initialize image_processing _UpperCamelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCamelCase : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ ) for image in image_inputs: self.assertIsInstance(A_ , Image.Image ) # Test not batched input _UpperCamelCase : Tuple = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , A_ ) self.assertIsInstance(encoding.boxes , A_ ) # Test batched _UpperCamelCase : Tuple = image_processing(A_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: # Initialize image_processing _UpperCamelCase : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCamelCase : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ , numpify=A_ ) for image in image_inputs: self.assertIsInstance(A_ , np.ndarray ) # Test not batched input _UpperCamelCase : Any = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched _UpperCamelCase : str = image_processing(A_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: # Initialize image_processing _UpperCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCamelCase : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=A_ , torchify=A_ ) for image in image_inputs: self.assertIsInstance(A_ , torch.Tensor ) # Test not batched input _UpperCamelCase : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched _UpperCamelCase : Tuple = image_processing(A_ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: # with apply_OCR = True _UpperCamelCase : int = LayoutLMvaImageProcessor() from datasets import load_dataset _UpperCamelCase : Optional[Any] = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) _UpperCamelCase : Union[str, Any] = Image.open(ds[0]["file"] ).convert("RGB" ) _UpperCamelCase : int = image_processing(A_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 _UpperCamelCase : int = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 _UpperCamelCase : int = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , A_ ) self.assertListEqual(encoding.boxes , A_ ) # with apply_OCR = False _UpperCamelCase : Any = LayoutLMvaImageProcessor(apply_ocr=A_ ) _UpperCamelCase : Optional[int] = image_processing(A_ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
704
"""simple docstring""" import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: _UpperCamelCase : Tuple = tempfile.mkdtemp() _UpperCamelCase : str = 5 # Realm tok _UpperCamelCase : Tuple = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "test", "question", "this", "is", "the", "first", "second", "third", "fourth", "fifth", "record", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _UpperCamelCase : Optional[int] = os.path.join(self.tmpdirname , "realm_tokenizer" ) os.makedirs(__a , exist_ok=__a ) _UpperCamelCase : Optional[Any] = os.path.join(__a , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) _UpperCamelCase : Optional[int] = os.path.join(self.tmpdirname , "realm_block_records" ) os.makedirs(__a , exist_ok=__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , "realm_tokenizer" ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: shutil.rmtree(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: _UpperCamelCase : Optional[Any] = RealmConfig(num_block_records=self.num_block_records ) return config def __SCREAMING_SNAKE_CASE ( self : int ) -> int: _UpperCamelCase : Any = Dataset.from_dict( { "id": ["0", "1"], "question": ["foo", "bar"], "answers": [["Foo", "Bar"], ["Bar"]], } ) return dataset def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: _UpperCamelCase : int = np.array( [ b"This is the first record", b"This is the second record", b"This is the third record", b"This is the fourth record", b"This is the fifth record", b"This is a longer longer longer record", ] , dtype=__a , ) return block_records def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: _UpperCamelCase : List[str] = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: _UpperCamelCase : Tuple = self.get_config() _UpperCamelCase : int = self.get_dummy_retriever() _UpperCamelCase : Tuple = retriever.tokenizer _UpperCamelCase : List[str] = np.array([0, 3] , dtype="long" ) _UpperCamelCase : Union[str, Any] = tokenizer(["Test question"] ).input_ids _UpperCamelCase : List[str] = tokenizer( ["the fourth"] , add_special_tokens=__a , return_token_type_ids=__a , return_attention_mask=__a , ).input_ids _UpperCamelCase : str = config.reader_seq_len _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : List[Any] = retriever( __a , __a , answer_ids=__a , max_length=__a , return_tensors="np" ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "first", "record", "[SEP]"] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "fourth", "record", "[SEP]"] , ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: _UpperCamelCase : Any = self.get_config() _UpperCamelCase : Dict = self.get_dummy_retriever() _UpperCamelCase : Dict = retriever.tokenizer _UpperCamelCase : List[Any] = np.array([0, 3, 5] , dtype="long" ) _UpperCamelCase : Optional[int] = tokenizer(["Test question"] ).input_ids _UpperCamelCase : str = tokenizer( ["the fourth", "longer longer"] , add_special_tokens=__a , return_token_type_ids=__a , return_attention_mask=__a , ).input_ids _UpperCamelCase : Union[str, Any] = config.reader_seq_len _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : Optional[Any] = retriever( __a , __a , answer_ids=__a , max_length=__a , return_tensors="np" ) self.assertEqual([False, True, True] , __a ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , __a ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , __a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: _UpperCamelCase : List[Any] = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) # Test local path _UpperCamelCase : int = retriever.from_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) self.assertEqual(retriever.block_records[0] , b"This is the first record" ) # Test mocked remote path with patch("transformers.models.realm.retrieval_realm.hf_hub_download" ) as mock_hf_hub_download: _UpperCamelCase : List[Any] = os.path.join( os.path.join(self.tmpdirname , "realm_block_records" ) , _REALM_BLOCK_RECORDS_FILENAME ) _UpperCamelCase : int = RealmRetriever.from_pretrained("google/realm-cc-news-pretrained-openqa" ) self.assertEqual(retriever.block_records[0] , b"This is the first record" )
51
0
"""simple docstring""" from __future__ import annotations def lowercase__ ( lowercase_ ) -> list[int]: """simple docstring""" if len(_lowerCamelCase ) == 0: return array _UpperCamelCase : Optional[int] = min(_lowerCamelCase ), max(_lowerCamelCase ) # Compute the variables _UpperCamelCase : Any = _max - _min + 1 _UpperCamelCase : List[str] = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: _UpperCamelCase : Union[str, Any] = i - _min _UpperCamelCase : str = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. _UpperCamelCase : List[Any] = 0 for i in range(_lowerCamelCase ): while holes_repeat[i] > 0: _UpperCamelCase : Tuple = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase__ = input("Enter numbers separated by comma:\n") lowerCamelCase__ = [int(x) for x in user_input.split(",")] print(pigeon_sort(unsorted))
705
"""simple docstring""" from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class __SCREAMING_SNAKE_CASE : '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = LEDConfig SCREAMING_SNAKE_CASE__ :str = {} SCREAMING_SNAKE_CASE__ :List[str] = "gelu" def __init__( self : List[Any] , __a : Union[str, Any] , __a : List[Any]=13 , __a : int=7 , __a : str=True , __a : Any=False , __a : str=99 , __a : str=32 , __a : Union[str, Any]=2 , __a : Optional[Any]=4 , __a : List[Any]=37 , __a : List[Any]=0.1 , __a : Tuple=0.1 , __a : Dict=20 , __a : str=2 , __a : Dict=1 , __a : Any=0 , __a : List[Any]=4 , ) -> List[Any]: _UpperCamelCase : Optional[Any] = parent _UpperCamelCase : List[str] = batch_size _UpperCamelCase : str = seq_length _UpperCamelCase : str = is_training _UpperCamelCase : Any = use_labels _UpperCamelCase : Any = vocab_size _UpperCamelCase : List[str] = hidden_size _UpperCamelCase : Optional[Any] = num_hidden_layers _UpperCamelCase : Dict = num_attention_heads _UpperCamelCase : Optional[Any] = intermediate_size _UpperCamelCase : int = hidden_dropout_prob _UpperCamelCase : Dict = attention_probs_dropout_prob _UpperCamelCase : str = max_position_embeddings _UpperCamelCase : int = eos_token_id _UpperCamelCase : Dict = pad_token_id _UpperCamelCase : Optional[Any] = bos_token_id _UpperCamelCase : str = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after _UpperCamelCase : List[str] = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests _UpperCamelCase : int = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __SCREAMING_SNAKE_CASE ( self : int ) -> str: _UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _UpperCamelCase : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _UpperCamelCase : Tuple = tf.concat([input_ids, eos_tensor] , axis=1 ) _UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase : List[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) _UpperCamelCase : Dict = prepare_led_inputs_dict(__a , __a , __a ) _UpperCamelCase : Union[str, Any] = tf.concat( [tf.zeros_like(__a )[:, :-1], tf.ones_like(__a )[:, -1:]] , axis=-1 , ) _UpperCamelCase : Union[str, Any] = global_attention_mask return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : List[Any] , __a : int ) -> Tuple: _UpperCamelCase : Tuple = TFLEDModel(config=__a ).get_decoder() _UpperCamelCase : Tuple = inputs_dict["input_ids"] _UpperCamelCase : int = input_ids[:1, :] _UpperCamelCase : List[str] = inputs_dict["attention_mask"][:1, :] _UpperCamelCase : List[Any] = 1 # first forward pass _UpperCamelCase : Any = model(__a , attention_mask=__a , use_cache=__a ) _UpperCamelCase, _UpperCamelCase : Union[str, Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _UpperCamelCase : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) _UpperCamelCase : Any = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _UpperCamelCase : List[str] = tf.concat([input_ids, next_tokens] , axis=-1 ) _UpperCamelCase : Union[str, Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _UpperCamelCase : Tuple = model(__a , attention_mask=__a )[0] _UpperCamelCase : int = model(__a , attention_mask=__a , past_key_values=__a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _UpperCamelCase : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _UpperCamelCase : List[str] = output_from_no_past[:, -3:, random_slice_idx] _UpperCamelCase : Optional[int] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__a , __a , rtol=1e-3 ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_=None ,lowercase_=None ,) -> Dict: """simple docstring""" if attention_mask is None: _UpperCamelCase : str = tf.cast(tf.math.not_equal(lowercase_ ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: _UpperCamelCase : str = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: _UpperCamelCase : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _UpperCamelCase : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :List[str] = (TFLEDForConditionalGeneration,) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :List[str] = ( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ :Tuple = True SCREAMING_SNAKE_CASE__ :str = False SCREAMING_SNAKE_CASE__ :Optional[Any] = False SCREAMING_SNAKE_CASE__ :int = False def __SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: _UpperCamelCase : int = TFLEDModelTester(self ) _UpperCamelCase : Any = ConfigTester(self , config_class=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: _UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__a ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase, _UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase : Optional[int] = tf.zeros_like(inputs_dict["attention_mask"] ) _UpperCamelCase : Union[str, Any] = 2 _UpperCamelCase : str = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) _UpperCamelCase : Dict = True _UpperCamelCase : str = self.model_tester.seq_length _UpperCamelCase : Union[str, Any] = self.model_tester.encoder_seq_length def check_decoder_attentions_output(__a : Optional[int] ): _UpperCamelCase : Optional[int] = outputs.decoder_attentions self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(__a : Optional[Any] ): _UpperCamelCase : Union[str, Any] = [t.numpy() for t in outputs.encoder_attentions] _UpperCamelCase : List[Any] = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: _UpperCamelCase : Dict = True _UpperCamelCase : Optional[Any] = False _UpperCamelCase : int = False _UpperCamelCase : Optional[int] = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) _UpperCamelCase : Any = len(__a ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) if self.is_encoder_decoder: _UpperCamelCase : Optional[Any] = model_class(__a ) _UpperCamelCase : List[Any] = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_decoder_attentions_output(__a ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _UpperCamelCase : int = True _UpperCamelCase : Tuple = model_class(__a ) _UpperCamelCase : str = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) # Check attention is always last and order is fine _UpperCamelCase : Any = True _UpperCamelCase : List[str] = True _UpperCamelCase : Tuple = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__a ) ) self.assertEqual(model.config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: pass def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: # TODO: Head-masking not yet implement pass def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" return tf.constant(lowercase_ ,dtype=tf.intaa ) lowerCamelCase__ = 1E-4 @slow @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: _UpperCamelCase : Any = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here _UpperCamelCase : int = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Tuple = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Optional[Any] = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Optional[int] = model(**__a )[0] _UpperCamelCase : Optional[int] = (1, 1024, 768) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : Tuple = tf.convert_to_tensor( [[2.30_50, 2.82_79, 0.65_31], [-1.84_57, -0.14_55, -3.56_61], [-1.01_86, 0.45_86, -2.20_43]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> str: _UpperCamelCase : Optional[int] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here _UpperCamelCase : Optional[int] = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : List[str] = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Optional[Any] = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Union[str, Any] = model(**__a )[0] _UpperCamelCase : int = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : Optional[int] = tf.convert_to_tensor( [[33.65_07, 6.45_72, 16.80_89], [5.87_39, -2.42_38, 11.29_02], [-3.21_39, -4.31_49, 4.27_83]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 , rtol=1e-3 )
51
0
"""simple docstring""" def lowercase__ ( lowercase_ ,lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : Optional[int] = len(_SCREAMING_SNAKE_CASE ) _UpperCamelCase : Union[str, Any] = [] for i in range(len(_SCREAMING_SNAKE_CASE ) - pat_len + 1 ): _UpperCamelCase : List[Any] = True for j in range(_SCREAMING_SNAKE_CASE ): if s[i + j] != pattern[j]: _UpperCamelCase : List[str] = False break if match_found: position.append(_SCREAMING_SNAKE_CASE ) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
706
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Union[str, Any] = RoCBertTokenizer SCREAMING_SNAKE_CASE__ :Dict = None SCREAMING_SNAKE_CASE__ :List[Any] = False SCREAMING_SNAKE_CASE__ :Union[str, Any] = True SCREAMING_SNAKE_CASE__ :Union[str, Any] = filter_non_english def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: super().setUp() _UpperCamelCase : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] _UpperCamelCase : List[str] = {} _UpperCamelCase : Tuple = {} for i, value in enumerate(__a ): _UpperCamelCase : List[str] = i _UpperCamelCase : Optional[Any] = i _UpperCamelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) _UpperCamelCase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(__a , __a , ensure_ascii=__a ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(__a , __a , ensure_ascii=__a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: _UpperCamelCase : Tuple = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : int = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(__a , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__a ) , [5, 6, 2, 5, 7, 8] ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: _UpperCamelCase : Dict = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: _UpperCamelCase : List[Any] = RoCBertBasicTokenizer(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 : Optional[Any] ) -> Tuple: _UpperCamelCase : Optional[Any] = RoCBertBasicTokenizer(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 : Dict ) -> str: _UpperCamelCase : Dict = RoCBertBasicTokenizer(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 : Union[str, Any] ) -> Union[str, Any]: _UpperCamelCase : List[str] = RoCBertBasicTokenizer(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[int]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase : Union[str, Any] = RoCBertBasicTokenizer(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 : Tuple ) -> List[Any]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(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 : Optional[Any] ) -> int: _UpperCamelCase : int = RoCBertBasicTokenizer(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 : List[str] ) -> Optional[Any]: _UpperCamelCase : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] _UpperCamelCase : Any = {} for i, token in enumerate(__a ): _UpperCamelCase : str = i _UpperCamelCase : Optional[int] = RoCBertWordpieceTokenizer(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 : Dict ) -> Optional[Any]: 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: 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 : Optional[int] ) -> Optional[int]: 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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = self.get_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]"]] ) if self.test_rust_tokenizer: _UpperCamelCase : Tuple = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__a ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Union[str, Any] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' _UpperCamelCase : Optional[Any] = tokenizer_r.encode_plus( __a , return_attention_mask=__a , return_token_type_ids=__a , return_offsets_mapping=__a , add_special_tokens=__a , ) _UpperCamelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(__a , "do_lower_case" ) else False _UpperCamelCase : Dict = ( [ ((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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = ["的", "人", "有"] _UpperCamelCase : int = "".join(__a ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = True _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : int = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : int = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : List[Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Union[str, Any] = 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 ) _UpperCamelCase : Any = False _UpperCamelCase : Dict = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Any = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Dict = tokenizer_p.convert_ids_to_tokens(__a ) # it is expected that only the first Chinese character is not preceded by "##". _UpperCamelCase : Any = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(__a ) ] self.assertListEqual(__a , __a ) self.assertListEqual(__a , __a ) @slow def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: _UpperCamelCase : Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : Optional[int] = tokenizer.encode("你好" , add_special_tokens=__a ) _UpperCamelCase : Dict = tokenizer.encode("你是谁" , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__a ) _UpperCamelCase : Tuple = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: _UpperCamelCase : Optional[Any] = self.get_tokenizers(do_lower_case=__a ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): _UpperCamelCase : int = "你好,你是谁" _UpperCamelCase : Any = tokenizer.tokenize(__a ) _UpperCamelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(__a ) _UpperCamelCase : List[str] = tokenizer.convert_tokens_to_shape_ids(__a ) _UpperCamelCase : Any = tokenizer.convert_tokens_to_pronunciation_ids(__a ) _UpperCamelCase : Optional[int] = tokenizer.prepare_for_model( __a , __a , __a , add_special_tokens=__a ) _UpperCamelCase : Tuple = tokenizer.encode_plus(__a , add_special_tokens=__a ) self.assertEqual(__a , __a )
51
0
"""simple docstring""" from random import randint from tempfile import TemporaryFile import numpy as np def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : List[Any] = 0 if start < end: _UpperCamelCase : Optional[int] = randint(lowercase_ ,lowercase_ ) _UpperCamelCase : Union[str, Any] = a[end] _UpperCamelCase : Optional[Any] = a[pivot] _UpperCamelCase : Any = temp _UpperCamelCase : List[str] = _in_place_partition(lowercase_ ,lowercase_ ,lowercase_ ) count += _in_place_quick_sort(lowercase_ ,lowercase_ ,p - 1 ) count += _in_place_quick_sort(lowercase_ ,p + 1 ,lowercase_ ) return count def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : Optional[int] = 0 _UpperCamelCase : List[Any] = randint(lowercase_ ,lowercase_ ) _UpperCamelCase : Optional[Any] = a[end] _UpperCamelCase : Any = a[pivot] _UpperCamelCase : Optional[int] = temp _UpperCamelCase : int = start - 1 for index in range(lowercase_ ,lowercase_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value _UpperCamelCase : List[str] = new_pivot_index + 1 _UpperCamelCase : Union[str, Any] = a[new_pivot_index] _UpperCamelCase : Tuple = a[index] _UpperCamelCase : Union[str, Any] = temp _UpperCamelCase : List[str] = a[new_pivot_index + 1] _UpperCamelCase : str = a[end] _UpperCamelCase : Any = temp return new_pivot_index + 1, count lowerCamelCase__ = TemporaryFile() lowerCamelCase__ = 100 # 1000 elements are to be sorted lowerCamelCase__ , lowerCamelCase__ = 0, 1 # mean and standard deviation lowerCamelCase__ = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array lowerCamelCase__ = np.load(outfile) lowerCamelCase__ = len(M) - 1 lowerCamelCase__ = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
707
"""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 lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "hustvl/yolos-small": "https://huggingface.co/hustvl/yolos-small/resolve/main/config.json", # See all YOLOS models at https://huggingface.co/models?filter=yolos } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = "yolos" def __init__( self : Dict , __a : Optional[Any]=768 , __a : List[Any]=12 , __a : Any=12 , __a : List[Any]=3072 , __a : Optional[int]="gelu" , __a : Dict=0.0 , __a : Optional[Any]=0.0 , __a : Any=0.02 , __a : Optional[int]=1e-1_2 , __a : List[Any]=[512, 864] , __a : List[str]=16 , __a : str=3 , __a : Optional[Any]=True , __a : Optional[Any]=100 , __a : List[str]=True , __a : Any=False , __a : List[str]=1 , __a : str=5 , __a : Optional[Any]=2 , __a : Tuple=5 , __a : Any=2 , __a : Union[str, Any]=0.1 , **__a : List[str] , ) -> List[str]: super().__init__(**__a ) _UpperCamelCase : Dict = hidden_size _UpperCamelCase : Any = num_hidden_layers _UpperCamelCase : str = num_attention_heads _UpperCamelCase : Dict = intermediate_size _UpperCamelCase : List[str] = hidden_act _UpperCamelCase : List[str] = hidden_dropout_prob _UpperCamelCase : str = attention_probs_dropout_prob _UpperCamelCase : Tuple = initializer_range _UpperCamelCase : List[str] = layer_norm_eps _UpperCamelCase : Tuple = image_size _UpperCamelCase : Tuple = patch_size _UpperCamelCase : Dict = num_channels _UpperCamelCase : Any = qkv_bias _UpperCamelCase : str = num_detection_tokens _UpperCamelCase : str = use_mid_position_embeddings _UpperCamelCase : List[str] = auxiliary_loss # Hungarian matcher _UpperCamelCase : List[Any] = class_cost _UpperCamelCase : int = bbox_cost _UpperCamelCase : Optional[int] = giou_cost # Loss coefficients _UpperCamelCase : List[Any] = bbox_loss_coefficient _UpperCamelCase : str = giou_loss_coefficient _UpperCamelCase : Dict = eos_coefficient class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[str] = version.parse("1.11" ) @property def __SCREAMING_SNAKE_CASE ( self : str ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> float: return 1e-4 @property def __SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return 12
51
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ = { "configuration_conditional_detr": [ "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConditionalDetrConfig", "ConditionalDetrOnnxConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["ConditionalDetrFeatureExtractor"] lowerCamelCase__ = ["ConditionalDetrImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST", "ConditionalDetrForObjectDetection", "ConditionalDetrForSegmentation", "ConditionalDetrModel", "ConditionalDetrPreTrainedModel", ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
708
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path lowerCamelCase__ = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) lowerCamelCase__ = [ord(letter) for letter in string.ascii_lowercase] lowerCamelCase__ = {ord(char) for char in VALID_CHARS} lowerCamelCase__ = ["the", "be", "to", "of", "and", "in", "that", "have"] def lowercase__ ( lowercase_ ,lowercase_ ) -> str | None: """simple docstring""" _UpperCamelCase : str = "" _UpperCamelCase : int _UpperCamelCase : int _UpperCamelCase : int for keychar, cipherchar in zip(cycle(lowercase_ ) ,lowercase_ ): _UpperCamelCase : Dict = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(lowercase_ ) return decoded def lowercase__ ( lowercase_ ) -> list[str]: """simple docstring""" _UpperCamelCase : list[str] = [] for key in product(lowercase_ ,repeat=3 ): _UpperCamelCase : int = try_key(lowercase_ ,lowercase_ ) if encoded is not None: possibles.append(lowercase_ ) return possibles def lowercase__ ( lowercase_ ,lowercase_ ) -> list[str]: """simple docstring""" return [possible for possible in possibles if common_word in possible.lower()] def lowercase__ ( lowercase_ = "p059_cipher.txt" ) -> int: """simple docstring""" _UpperCamelCase : list[int] _UpperCamelCase : list[str] _UpperCamelCase : str _UpperCamelCase : str _UpperCamelCase : str = Path(lowercase_ ).parent.joinpath(lowercase_ ).read_text(encoding="utf-8" ) _UpperCamelCase : Optional[Any] = [int(lowercase_ ) for number in data.strip().split("," )] _UpperCamelCase : List[str] = filter_valid_chars(lowercase_ ) for common_word in COMMON_WORDS: _UpperCamelCase : Union[str, Any] = filter_common_word(lowercase_ ,lowercase_ ) if len(lowercase_ ) == 1: break _UpperCamelCase : Union[str, Any] = possibles[0] return sum(ord(lowercase_ ) for char in decoded_text ) if __name__ == "__main__": print(f"""{solution() = }""")
51
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class __SCREAMING_SNAKE_CASE ( a__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :int = "vit_mae" def __init__( self : Any , __a : List[str]=768 , __a : Tuple=12 , __a : List[str]=12 , __a : Tuple=3072 , __a : int="gelu" , __a : Any=0.0 , __a : List[Any]=0.0 , __a : List[Any]=0.02 , __a : Tuple=1e-1_2 , __a : Union[str, Any]=224 , __a : List[Any]=16 , __a : Any=3 , __a : Union[str, Any]=True , __a : Tuple=16 , __a : Optional[int]=512 , __a : Optional[Any]=8 , __a : Any=2048 , __a : Dict=0.75 , __a : str=False , **__a : Optional[Any] , ) -> List[str]: super().__init__(**lowerCamelCase_ ) _UpperCamelCase : Any = hidden_size _UpperCamelCase : str = num_hidden_layers _UpperCamelCase : Any = num_attention_heads _UpperCamelCase : Optional[Any] = intermediate_size _UpperCamelCase : Any = hidden_act _UpperCamelCase : List[str] = hidden_dropout_prob _UpperCamelCase : List[str] = attention_probs_dropout_prob _UpperCamelCase : Union[str, Any] = initializer_range _UpperCamelCase : int = layer_norm_eps _UpperCamelCase : Union[str, Any] = image_size _UpperCamelCase : List[str] = patch_size _UpperCamelCase : Any = num_channels _UpperCamelCase : List[str] = qkv_bias _UpperCamelCase : Union[str, Any] = decoder_num_attention_heads _UpperCamelCase : str = decoder_hidden_size _UpperCamelCase : Optional[int] = decoder_num_hidden_layers _UpperCamelCase : str = decoder_intermediate_size _UpperCamelCase : Tuple = mask_ratio _UpperCamelCase : Union[str, Any] = norm_pix_loss
709
"""simple docstring""" def lowercase__ ( lowercase_ ,lowercase_ ) -> None: """simple docstring""" _UpperCamelCase : List[Any] = len(lowercase_ ) print("The following activities are selected:" ) # The first activity is always selected _UpperCamelCase : List[Any] = 0 print(lowercase_ ,end="," ) # Consider rest of the activities for j in range(lowercase_ ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(lowercase_ ,end="," ) _UpperCamelCase : Optional[Any] = j if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase__ = [1, 3, 0, 5, 8, 5] lowerCamelCase__ = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
51
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "google/pegasus-large": "https://huggingface.co/google/pegasus-large/resolve/main/config.json", # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class __SCREAMING_SNAKE_CASE ( lowercase_ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[Any] = '''pegasus''' SCREAMING_SNAKE_CASE__ :Tuple = ['''past_key_values'''] SCREAMING_SNAKE_CASE__ :int = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self : Optional[int] , __a : int=5_0265 , __a : Dict=1024 , __a : List[str]=12 , __a : str=4096 , __a : Union[str, Any]=16 , __a : Any=12 , __a : Tuple=4096 , __a : Union[str, Any]=16 , __a : Optional[int]=0.0 , __a : List[str]=0.0 , __a : Any=True , __a : Optional[Any]=True , __a : List[str]="gelu" , __a : Optional[int]=1024 , __a : Optional[Any]=0.1 , __a : Optional[int]=0.0 , __a : List[Any]=0.0 , __a : Optional[Any]=0.02 , __a : Any=0 , __a : Tuple=False , __a : List[Any]=0 , __a : str=1 , __a : Any=1 , **__a : str , ) -> Optional[Any]: _UpperCamelCase : int = vocab_size _UpperCamelCase : str = max_position_embeddings _UpperCamelCase : Dict = d_model _UpperCamelCase : str = encoder_ffn_dim _UpperCamelCase : Union[str, Any] = encoder_layers _UpperCamelCase : Optional[int] = encoder_attention_heads _UpperCamelCase : str = decoder_ffn_dim _UpperCamelCase : List[Any] = decoder_layers _UpperCamelCase : str = decoder_attention_heads _UpperCamelCase : str = dropout _UpperCamelCase : Tuple = attention_dropout _UpperCamelCase : int = activation_dropout _UpperCamelCase : List[str] = activation_function _UpperCamelCase : Tuple = init_std _UpperCamelCase : int = encoder_layerdrop _UpperCamelCase : str = decoder_layerdrop _UpperCamelCase : Optional[Any] = use_cache _UpperCamelCase : List[Any] = encoder_layers _UpperCamelCase : Any = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , forced_eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: return self.encoder_attention_heads @property def __SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: return self.d_model
710
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :torch.FloatTensor class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : Dict=3 , __a : Any=3 , __a : Union[str, Any]=("DownEncoderBlock2D",) , __a : Optional[int]=(64,) , __a : int=2 , __a : Tuple=32 , __a : int="silu" , __a : str=True , ) -> Dict: super().__init__() _UpperCamelCase : List[str] = layers_per_block _UpperCamelCase : Dict = torch.nn.Convad( __a , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) _UpperCamelCase : int = None _UpperCamelCase : Any = nn.ModuleList([] ) # down _UpperCamelCase : List[str] = block_out_channels[0] for i, down_block_type in enumerate(__a ): _UpperCamelCase : Tuple = output_channel _UpperCamelCase : int = block_out_channels[i] _UpperCamelCase : int = i == len(__a ) - 1 _UpperCamelCase : Dict = get_down_block( __a , num_layers=self.layers_per_block , in_channels=__a , out_channels=__a , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=__a , resnet_groups=__a , attention_head_dim=__a , temb_channels=__a , ) self.down_blocks.append(__a ) # mid _UpperCamelCase : Union[str, Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__a , output_scale_factor=1 , resnet_time_scale_shift="default" , attention_head_dim=block_out_channels[-1] , resnet_groups=__a , temb_channels=__a , ) # out _UpperCamelCase : Any = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__a , eps=1e-6 ) _UpperCamelCase : Any = nn.SiLU() _UpperCamelCase : Union[str, Any] = 2 * out_channels if double_z else out_channels _UpperCamelCase : Tuple = nn.Convad(block_out_channels[-1] , __a , 3 , padding=1 ) _UpperCamelCase : Optional[int] = False def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Dict ) -> List[str]: _UpperCamelCase : int = x _UpperCamelCase : Optional[int] = self.conv_in(__a ) if self.training and self.gradient_checkpointing: def create_custom_forward(__a : Tuple ): def custom_forward(*__a : Any ): return module(*__a ) return custom_forward # down if is_torch_version(">=" , "1.11.0" ): for down_block in self.down_blocks: _UpperCamelCase : Optional[int] = torch.utils.checkpoint.checkpoint( create_custom_forward(__a ) , __a , use_reentrant=__a ) # middle _UpperCamelCase : Tuple = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , use_reentrant=__a ) else: for down_block in self.down_blocks: _UpperCamelCase : Any = torch.utils.checkpoint.checkpoint(create_custom_forward(__a ) , __a ) # middle _UpperCamelCase : int = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __a ) else: # down for down_block in self.down_blocks: _UpperCamelCase : int = down_block(__a ) # middle _UpperCamelCase : int = self.mid_block(__a ) # post-process _UpperCamelCase : Any = self.conv_norm_out(__a ) _UpperCamelCase : Any = self.conv_act(__a ) _UpperCamelCase : Optional[Any] = self.conv_out(__a ) return sample class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : int=3 , __a : Any=3 , __a : str=("UpDecoderBlock2D",) , __a : Optional[int]=(64,) , __a : int=2 , __a : Optional[int]=32 , __a : Tuple="silu" , __a : Union[str, Any]="group" , ) -> str: super().__init__() _UpperCamelCase : List[Any] = layers_per_block _UpperCamelCase : Tuple = nn.Convad( __a , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) _UpperCamelCase : List[str] = None _UpperCamelCase : Dict = nn.ModuleList([] ) _UpperCamelCase : List[Any] = in_channels if norm_type == "spatial" else None # mid _UpperCamelCase : Optional[Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__a , output_scale_factor=1 , resnet_time_scale_shift="default" if norm_type == "group" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__a , temb_channels=__a , ) # up _UpperCamelCase : List[str] = list(reversed(__a ) ) _UpperCamelCase : int = reversed_block_out_channels[0] for i, up_block_type in enumerate(__a ): _UpperCamelCase : int = output_channel _UpperCamelCase : Union[str, Any] = reversed_block_out_channels[i] _UpperCamelCase : Optional[Any] = i == len(__a ) - 1 _UpperCamelCase : Union[str, Any] = get_up_block( __a , num_layers=self.layers_per_block + 1 , in_channels=__a , out_channels=__a , prev_output_channel=__a , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=__a , resnet_groups=__a , attention_head_dim=__a , temb_channels=__a , resnet_time_scale_shift=__a , ) self.up_blocks.append(__a ) _UpperCamelCase : Optional[Any] = output_channel # out if norm_type == "spatial": _UpperCamelCase : Optional[int] = SpatialNorm(block_out_channels[0] , __a ) else: _UpperCamelCase : Optional[int] = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__a , eps=1e-6 ) _UpperCamelCase : str = nn.SiLU() _UpperCamelCase : str = nn.Convad(block_out_channels[0] , __a , 3 , padding=1 ) _UpperCamelCase : Dict = False def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : List[Any] , __a : Union[str, Any]=None ) -> Tuple: _UpperCamelCase : List[str] = z _UpperCamelCase : Dict = self.conv_in(__a ) _UpperCamelCase : Any = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__a : Any ): def custom_forward(*__a : Tuple ): return module(*__a ) return custom_forward if is_torch_version(">=" , "1.11.0" ): # middle _UpperCamelCase : str = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , __a , use_reentrant=__a ) _UpperCamelCase : Optional[int] = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(__a ) , __a , __a , use_reentrant=__a ) else: # middle _UpperCamelCase : Optional[int] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , __a ) _UpperCamelCase : Union[str, Any] = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : str = torch.utils.checkpoint.checkpoint(create_custom_forward(__a ) , __a , __a ) else: # middle _UpperCamelCase : str = self.mid_block(__a , __a ) _UpperCamelCase : int = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : Any = up_block(__a , __a ) # post-process if latent_embeds is None: _UpperCamelCase : List[str] = self.conv_norm_out(__a ) else: _UpperCamelCase : Optional[int] = self.conv_norm_out(__a , __a ) _UpperCamelCase : Tuple = self.conv_act(__a ) _UpperCamelCase : List[Any] = self.conv_out(__a ) return sample class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : Tuple , __a : List[str] , __a : List[str] , __a : str=None , __a : Optional[int]="random" , __a : Any=False , __a : Optional[Any]=True ) -> List[Any]: super().__init__() _UpperCamelCase : Tuple = n_e _UpperCamelCase : Tuple = vq_embed_dim _UpperCamelCase : Union[str, Any] = beta _UpperCamelCase : str = legacy _UpperCamelCase : Dict = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) _UpperCamelCase : Any = remap if self.remap is not None: self.register_buffer("used" , torch.tensor(np.load(self.remap ) ) ) _UpperCamelCase : Dict = self.used.shape[0] _UpperCamelCase : Optional[int] = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": _UpperCamelCase : Optional[int] = self.re_embed _UpperCamelCase : Any = self.re_embed + 1 print( F'''Remapping {self.n_e} indices to {self.re_embed} indices. ''' F'''Using {self.unknown_index} for unknown indices.''' ) else: _UpperCamelCase : Union[str, Any] = n_e _UpperCamelCase : List[str] = sane_index_shape def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : Optional[Any] ) -> Optional[int]: _UpperCamelCase : str = inds.shape assert len(__a ) > 1 _UpperCamelCase : Union[str, Any] = inds.reshape(ishape[0] , -1 ) _UpperCamelCase : Optional[Any] = self.used.to(__a ) _UpperCamelCase : List[str] = (inds[:, :, None] == used[None, None, ...]).long() _UpperCamelCase : Optional[Any] = match.argmax(-1 ) _UpperCamelCase : Any = match.sum(2 ) < 1 if self.unknown_index == "random": _UpperCamelCase : Optional[int] = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: _UpperCamelCase : Dict = self.unknown_index return new.reshape(__a ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : Optional[int] ) -> Optional[int]: _UpperCamelCase : int = inds.shape assert len(__a ) > 1 _UpperCamelCase : List[Any] = inds.reshape(ishape[0] , -1 ) _UpperCamelCase : Optional[int] = self.used.to(__a ) if self.re_embed > self.used.shape[0]: # extra token _UpperCamelCase : int = 0 # simply set to zero _UpperCamelCase : Union[str, Any] = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __a ) return back.reshape(__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : str ) -> Optional[int]: # reshape z -> (batch, height, width, channel) and flatten _UpperCamelCase : List[str] = z.permute(0 , 2 , 3 , 1 ).contiguous() _UpperCamelCase : int = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z _UpperCamelCase : Optional[int] = torch.argmin(torch.cdist(__a , self.embedding.weight ) , dim=1 ) _UpperCamelCase : int = self.embedding(__a ).view(z.shape ) _UpperCamelCase : str = None _UpperCamelCase : Any = None # compute loss for embedding if not self.legacy: _UpperCamelCase : List[str] = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: _UpperCamelCase : str = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients _UpperCamelCase : List[str] = z + (z_q - z).detach() # reshape back to match original input shape _UpperCamelCase : Optional[Any] = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: _UpperCamelCase : Tuple = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis _UpperCamelCase : Dict = self.remap_to_used(__a ) _UpperCamelCase : List[str] = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: _UpperCamelCase : str = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : List[str] , __a : str ) -> Any: # shape specifying (batch, height, width, channel) if self.remap is not None: _UpperCamelCase : str = indices.reshape(shape[0] , -1 ) # add batch axis _UpperCamelCase : str = self.unmap_to_all(__a ) _UpperCamelCase : int = indices.reshape(-1 ) # flatten again # get quantized latent vectors _UpperCamelCase : Optional[int] = self.embedding(__a ) if shape is not None: _UpperCamelCase : Tuple = z_q.view(__a ) # reshape back to match original input shape _UpperCamelCase : Tuple = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __init__( self : Optional[int] , __a : List[str] , __a : Optional[Any]=False ) -> int: _UpperCamelCase : Dict = parameters _UpperCamelCase, _UpperCamelCase : str = torch.chunk(__a , 2 , dim=1 ) _UpperCamelCase : Tuple = torch.clamp(self.logvar , -30.0 , 20.0 ) _UpperCamelCase : Union[str, Any] = deterministic _UpperCamelCase : Dict = torch.exp(0.5 * self.logvar ) _UpperCamelCase : Any = torch.exp(self.logvar ) if self.deterministic: _UpperCamelCase : List[Any] = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : Optional[torch.Generator] = None ) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype _UpperCamelCase : List[Any] = randn_tensor( self.mean.shape , generator=__a , device=self.parameters.device , dtype=self.parameters.dtype ) _UpperCamelCase : List[Any] = self.mean + self.std * sample return x def __SCREAMING_SNAKE_CASE ( self : Any , __a : List[str]=None ) -> List[Any]: if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def __SCREAMING_SNAKE_CASE ( self : str , __a : Tuple , __a : List[str]=[1, 2, 3] ) -> int: if self.deterministic: return torch.Tensor([0.0] ) _UpperCamelCase : List[str] = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: return self.mean
51
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = "▁" lowerCamelCase__ = {"vocab_file": "spiece.model"} lowerCamelCase__ = { "vocab_file": { "google/reformer-crime-and-punishment": ( "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model" ) } } lowerCamelCase__ = { "google/reformer-crime-and-punishment": 52_4288, } class __SCREAMING_SNAKE_CASE ( __UpperCAmelCase ): SCREAMING_SNAKE_CASE__ :str = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ :int = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ :List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ :Optional[int] = ["input_ids", "attention_mask"] def __init__( self : int , __a : Any , __a : Dict="</s>" , __a : Dict="<unk>" , __a : Dict=[] , __a : Optional[Dict[str, Any]] = None , **__a : List[str] , ) -> Optional[int]: _UpperCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=lowerCAmelCase_ , unk_token=lowerCAmelCase_ , additional_special_tokens=lowerCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCAmelCase_ , ) _UpperCamelCase : Optional[int] = vocab_file _UpperCamelCase : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowerCAmelCase_ ) @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: return self.sp_model.get_piece_size() def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: _UpperCamelCase : List[str] = {self.convert_ids_to_tokens(lowerCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> int: _UpperCamelCase : Tuple = self.__dict__.copy() _UpperCamelCase : Optional[Any] = None return state def __setstate__( self : Optional[Any] , __a : int ) -> int: _UpperCamelCase : List[Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _UpperCamelCase : str = {} _UpperCamelCase : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : str ) -> Optional[Any]: return self.sp_model.encode(lowerCAmelCase_ , out_type=lowerCAmelCase_ ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : List[str] ) -> Union[str, Any]: return self.sp_model.piece_to_id(lowerCAmelCase_ ) def __SCREAMING_SNAKE_CASE ( self : str , __a : Any ) -> List[Any]: if index < self.sp_model.get_piece_size(): _UpperCamelCase : List[str] = self.sp_model.IdToPiece(lowerCAmelCase_ ) return token def __SCREAMING_SNAKE_CASE ( self : int , __a : Any ) -> Optional[int]: _UpperCamelCase : Tuple = [] _UpperCamelCase : Union[str, Any] = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(lowerCAmelCase_ ) + token _UpperCamelCase : int = [] else: current_sub_tokens.append(lowerCAmelCase_ ) out_string += self.sp_model.decode(lowerCAmelCase_ ) return out_string.strip() def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> int: if not os.path.isdir(lowerCAmelCase_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return _UpperCamelCase : Union[str, Any] = os.path.join( lowerCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(lowerCAmelCase_ , "wb" ) as fi: _UpperCamelCase : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase_ ) return (out_vocab_file,)
711
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''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 __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict[str, str]: return {self.text_column: "text", self.summary_column: "summary"}
51
0
"""simple docstring""" from math import log from scipy.constants import Boltzmann, physical_constants lowerCamelCase__ = 300 # TEMPERATURE (unit = K) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,) -> float: """simple docstring""" if donor_conc <= 0: raise ValueError("Donor concentration should be positive" ) elif acceptor_conc <= 0: raise ValueError("Acceptor concentration should be positive" ) elif intrinsic_conc <= 0: raise ValueError("Intrinsic concentration should be positive" ) elif donor_conc <= intrinsic_conc: raise ValueError( "Donor concentration should be greater than intrinsic concentration" ) elif acceptor_conc <= intrinsic_conc: raise ValueError( "Acceptor concentration should be greater than intrinsic concentration" ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2 ) / physical_constants["electron volt"][0] ) if __name__ == "__main__": import doctest doctest.testmod()
712
"""simple docstring""" def lowercase__ ( lowercase_ ) -> set: """simple docstring""" _UpperCamelCase : Union[str, Any] = set() # edges = list of graph's edges _UpperCamelCase : Union[str, Any] = get_edges(lowercase_ ) # 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: _UpperCamelCase, _UpperCamelCase : str = edges.pop() chosen_vertices.add(lowercase_ ) chosen_vertices.add(lowercase_ ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(lowercase_ ) return chosen_vertices def lowercase__ ( lowercase_ ) -> set: """simple docstring""" _UpperCamelCase : List[str] = 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)}")
51
0
"""simple docstring""" import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __SCREAMING_SNAKE_CASE ( _a ): '''simple docstring''' def __init__( self : int , __a : Optional[Any] , __a : Optional[Any] , __a : Dict = None , __a : Union[str, Any] = None , __a : Dict = False , **__a : Union[str, Any] , ) -> Dict: super().__init__(features=_A , cache_dir=_A , keep_in_memory=_A , **_A ) _UpperCamelCase : List[str] = Sql( cache_dir=_A , features=_A , sql=_A , con=_A , **_A , ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: _UpperCamelCase : Any = None _UpperCamelCase : Optional[int] = None _UpperCamelCase : Optional[int] = None _UpperCamelCase : int = None self.builder.download_and_prepare( download_config=_A , download_mode=_A , verification_mode=_A , base_path=_A , ) # Build dataset for splits _UpperCamelCase : int = self.builder.as_dataset( split="train" , verification_mode=_A , in_memory=self.keep_in_memory ) return dataset class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] , __a : Dict , __a : Dict , __a : Any , __a : Union[str, Any] = None , __a : Optional[int] = None , **__a : int , ) -> Tuple: if num_proc is not None and num_proc <= 0: raise ValueError(F'''num_proc {num_proc} must be an integer > 0.''' ) _UpperCamelCase : List[Any] = dataset _UpperCamelCase : List[str] = name _UpperCamelCase : Any = con _UpperCamelCase : Tuple = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _UpperCamelCase : List[str] = num_proc _UpperCamelCase : Optional[int] = to_sql_kwargs def __SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: _UpperCamelCase : Optional[int] = self.to_sql_kwargs.pop("sql" , _A ) _UpperCamelCase : int = self.to_sql_kwargs.pop("con" , _A ) _UpperCamelCase : List[str] = self.to_sql_kwargs.pop("index" , _A ) _UpperCamelCase : Tuple = self._write(index=_A , **self.to_sql_kwargs ) return written def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : Optional[Any] ) -> List[Any]: _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : str = args _UpperCamelCase : Optional[int] = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs _UpperCamelCase : List[Any] = query_table( table=self.dataset.data , key=slice(_A , offset + self.batch_size ) , indices=self.dataset._indices , ) _UpperCamelCase : List[Any] = batch.to_pandas() _UpperCamelCase : Dict = df.to_sql(self.name , self.con , index=_A , **_A ) return num_rows or len(_A ) def __SCREAMING_SNAKE_CASE ( self : str , __a : Optional[Any] , **__a : Any ) -> Union[str, Any]: _UpperCamelCase : Any = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: _UpperCamelCase, _UpperCamelCase : Optional[Any] = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _A , _A )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
713
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCamelCase__ = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["OwlViTFeatureExtractor"] lowerCamelCase__ = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
51
0
"""simple docstring""" import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[int] , __a : str , __a : str=13 , __a : Any=64 , __a : List[str]=2 , __a : Dict=3 , __a : List[Any]=True , __a : Optional[Any]=True , __a : Optional[int]=32 , __a : List[str]=5 , __a : int=4 , __a : Dict=37 , __a : List[Any]="gelu" , __a : Any=0.1 , __a : Optional[Any]=0.1 , __a : int=10 , __a : Optional[int]=0.02 , __a : Dict=[1, 16, 4, 4] , __a : Optional[int]=None , ) -> str: _UpperCamelCase : str = parent _UpperCamelCase : Optional[Any] = batch_size _UpperCamelCase : List[str] = image_size _UpperCamelCase : Optional[int] = patch_size _UpperCamelCase : Union[str, Any] = num_channels _UpperCamelCase : Optional[int] = is_training _UpperCamelCase : List[Any] = use_labels _UpperCamelCase : Dict = hidden_size _UpperCamelCase : List[str] = num_hidden_layers _UpperCamelCase : Optional[int] = num_attention_heads _UpperCamelCase : Union[str, Any] = intermediate_size _UpperCamelCase : Optional[int] = hidden_act _UpperCamelCase : Tuple = hidden_dropout_prob _UpperCamelCase : Dict = attention_probs_dropout_prob _UpperCamelCase : Optional[Any] = type_sequence_label_size _UpperCamelCase : Optional[int] = initializer_range _UpperCamelCase : Optional[Any] = scope _UpperCamelCase : int = backbone_featmap_shape # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) # the number of patches is based on the feature map of the backbone, which by default uses an output stride # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size _UpperCamelCase : Dict = (self.image_size // 32) ** 2 _UpperCamelCase : str = num_patches + 1 def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: _UpperCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCamelCase : List[str] = None if self.use_labels: _UpperCamelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCamelCase : Any = self.get_config() return config, pixel_values, labels def __SCREAMING_SNAKE_CASE ( self : int ) -> Any: _UpperCamelCase : Dict = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, "hidden_sizes": [4, 8, 16, 32], "num_groups": 2, } return ViTHybridConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__UpperCamelCase , initializer_range=self.initializer_range , backbone_featmap_shape=self.backbone_featmap_shape , backbone_config=__UpperCamelCase , ) def __SCREAMING_SNAKE_CASE ( self : int , __a : List[Any] , __a : List[Any] , __a : Union[str, Any] ) -> int: _UpperCamelCase : Any = ViTHybridModel(config=__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() _UpperCamelCase : Optional[Any] = model(__UpperCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE ( self : Any , __a : str , __a : int , __a : Dict ) -> Dict: _UpperCamelCase : Optional[Any] = self.type_sequence_label_size _UpperCamelCase : Tuple = ViTHybridForImageClassification(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() _UpperCamelCase : List[Any] = model(__UpperCamelCase , labels=__UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: _UpperCamelCase : str = self.prepare_config_and_inputs() _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : Union[str, Any] = config_and_inputs _UpperCamelCase : Optional[int] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[Any] = (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else () SCREAMING_SNAKE_CASE__ :Tuple = ( {"feature-extraction": ViTHybridModel, "image-classification": ViTHybridForImageClassification} if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ :List[str] = False SCREAMING_SNAKE_CASE__ :int = False SCREAMING_SNAKE_CASE__ :Union[str, Any] = False def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: _UpperCamelCase : int = ViTHybridModelTester(self ) _UpperCamelCase : Optional[Any] = ConfigTester(self , config_class=__UpperCamelCase , has_text_modality=__UpperCamelCase , hidden_size=37 ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Any: pass def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[Any]: _UpperCamelCase, _UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase : Optional[Any] = model_class(__UpperCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _UpperCamelCase : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__UpperCamelCase , nn.Linear ) ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: _UpperCamelCase, _UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase : str = model_class(__UpperCamelCase ) _UpperCamelCase : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCamelCase : str = [*signature.parameters.keys()] _UpperCamelCase : int = ["pixel_values"] self.assertListEqual(arg_names[:1] , __UpperCamelCase ) def __SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: _UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCamelCase ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: _UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase ) def __SCREAMING_SNAKE_CASE ( self : str ) -> int: _UpperCamelCase, _UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase : Dict = _config_zero_init(__UpperCamelCase ) for model_class in self.all_model_classes: _UpperCamelCase : str = model_class(config=__UpperCamelCase ) # Skip the check for the backbone for name, module in model.named_modules(): if module.__class__.__name__ == "ViTHybridPatchEmbeddings": _UpperCamelCase : Optional[int] = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @slow def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase : Any = ViTHybridModel.from_pretrained(__UpperCamelCase ) self.assertIsNotNone(__UpperCamelCase ) def lowercase__ ( ) -> Tuple: """simple docstring""" _UpperCamelCase : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: return ( ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __SCREAMING_SNAKE_CASE ( self : int ) -> Dict: _UpperCamelCase : Any = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( __UpperCamelCase ) _UpperCamelCase : Dict = self.default_image_processor _UpperCamelCase : Optional[int] = prepare_img() _UpperCamelCase : int = image_processor(images=__UpperCamelCase , return_tensors="pt" ).to(__UpperCamelCase ) # forward pass with torch.no_grad(): _UpperCamelCase : Union[str, Any] = model(**__UpperCamelCase ) # verify the logits _UpperCamelCase : Optional[int] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __UpperCamelCase ) _UpperCamelCase : str = torch.tensor([-1.90_90, -0.49_93, -0.23_89] ).to(__UpperCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCamelCase , atol=1e-4 ) ) @slow @require_accelerate def __SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: _UpperCamelCase : int = ViTHybridImageProcessor.from_pretrained("google/vit-hybrid-base-bit-384" ) _UpperCamelCase : List[Any] = ViTHybridForImageClassification.from_pretrained("google/vit-hybrid-base-bit-384" , device_map="auto" ) _UpperCamelCase : List[Any] = prepare_img() _UpperCamelCase : Tuple = image_processor(images=__UpperCamelCase , return_tensors="pt" ) _UpperCamelCase : Dict = model(**__UpperCamelCase ) _UpperCamelCase : Union[str, Any] = outputs.logits # model predicts one of the 1000 ImageNet classes _UpperCamelCase : Union[str, Any] = logits.argmax(-1 ).item() self.assertTrue(model.config.idalabel[predicted_class_idx] , "tabby, tabby cat" )
714
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowercase__ ( lowercase_ = 1_000_000 ,lowercase_ = 10 ) -> int: """simple docstring""" _UpperCamelCase : defaultdict = defaultdict(lowercase_ ) for outer_width in range(3 ,(t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: _UpperCamelCase : Any = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) ,1 ) else: _UpperCamelCase : str = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowercase_ ,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() = }""")
51
0
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) 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 .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
715
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar lowerCamelCase__ = TypeVar("KEY") lowerCamelCase__ = TypeVar("VAL") @dataclass(frozen=_UpperCamelCase , slots=_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( Generic[KEY, VAL] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :KEY SCREAMING_SNAKE_CASE__ :VAL class __SCREAMING_SNAKE_CASE ( _Item ): '''simple docstring''' def __init__( self : List[str] ) -> None: super().__init__(__a , __a ) def __bool__( self : Dict ) -> bool: return False lowerCamelCase__ = _DeletedItem() class __SCREAMING_SNAKE_CASE ( MutableMapping[KEY, VAL] ): '''simple docstring''' def __init__( self : int , __a : int = 8 , __a : float = 0.75 ) -> None: _UpperCamelCase : str = initial_block_size _UpperCamelCase : list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 _UpperCamelCase : List[str] = capacity_factor _UpperCamelCase : Dict = 0 def __SCREAMING_SNAKE_CASE ( self : int , __a : KEY ) -> int: return hash(__a ) % len(self._buckets ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : int ) -> int: return (ind + 1) % len(self._buckets ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : int , __a : KEY , __a : VAL ) -> bool: _UpperCamelCase : List[Any] = self._buckets[ind] if not stored: _UpperCamelCase : Tuple = _Item(__a , __a ) self._len += 1 return True elif stored.key == key: _UpperCamelCase : Union[str, Any] = _Item(__a , __a ) return True else: return False def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> bool: _UpperCamelCase : Any = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False _UpperCamelCase : List[str] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : int ) -> None: _UpperCamelCase : Any = self._buckets _UpperCamelCase : List[Any] = [None] * new_size _UpperCamelCase : List[str] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __SCREAMING_SNAKE_CASE ( self : int ) -> None: self._resize(len(self._buckets ) * 2 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: self._resize(len(self._buckets ) // 2 ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : KEY ) -> Iterator[int]: _UpperCamelCase : str = self._get_bucket_index(__a ) for _ in range(len(self._buckets ) ): yield ind _UpperCamelCase : Tuple = self._get_next_ind(__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : KEY , __a : VAL ) -> None: for ind in self._iterate_buckets(__a ): if self._try_set(__a , __a , __a ): break def __setitem__( self : int , __a : KEY , __a : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(__a , __a ) def __delitem__( self : str , __a : KEY ) -> None: for ind in self._iterate_buckets(__a ): _UpperCamelCase : Tuple = self._buckets[ind] if item is None: raise KeyError(__a ) if item is _deleted: continue if item.key == key: _UpperCamelCase : List[Any] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : str , __a : KEY ) -> VAL: for ind in self._iterate_buckets(__a ): _UpperCamelCase : Tuple = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__a ) def __len__( self : List[Any] ) -> int: return self._len def __iter__( self : List[str] ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : List[str] ) -> str: _UpperCamelCase : Optional[int] = " ,".join( F'''{item.key}: {item.val}''' for item in self._buckets if item ) return F'''HashMap({val_string})'''
51
0
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] , __a : Any , __a : Tuple=2 , __a : Optional[Any]=True , __a : Tuple=False , __a : Optional[Any]=10 , __a : List[Any]=3 , __a : str=32 * 8 , __a : Optional[Any]=32 * 8 , __a : List[str]=4 , __a : Optional[Any]=64 , ) -> Optional[Any]: _UpperCamelCase : List[Any] = parent _UpperCamelCase : str = batch_size _UpperCamelCase : Dict = is_training _UpperCamelCase : List[Any] = use_auxiliary_loss _UpperCamelCase : Optional[int] = num_queries _UpperCamelCase : List[str] = num_channels _UpperCamelCase : Tuple = min_size _UpperCamelCase : List[str] = max_size _UpperCamelCase : Tuple = num_labels _UpperCamelCase : Any = hidden_dim _UpperCamelCase : List[str] = hidden_dim def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: _UpperCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __a ) _UpperCamelCase : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__a ) _UpperCamelCase : Union[str, Any] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__a ) > 0.5 ).float() _UpperCamelCase : Optional[Any] = (torch.rand((self.batch_size, self.num_labels) , device=__a ) > 0.5).long() _UpperCamelCase : Optional[Any] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: _UpperCamelCase : Any = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _UpperCamelCase : int = self.num_queries _UpperCamelCase : Optional[Any] = self.num_labels _UpperCamelCase : Optional[Any] = [1, 1, 1, 1] _UpperCamelCase : List[str] = self.num_channels _UpperCamelCase : Optional[Any] = 64 _UpperCamelCase : str = 128 _UpperCamelCase : Union[str, Any] = self.hidden_dim _UpperCamelCase : int = self.hidden_dim _UpperCamelCase : Any = self.hidden_dim return config def __SCREAMING_SNAKE_CASE ( self : int ) -> Dict: _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : Optional[Any] = self.prepare_config_and_inputs() _UpperCamelCase : Dict = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self : str , __a : Union[str, Any] , __a : str ) -> Dict: _UpperCamelCase : int = output.encoder_hidden_states _UpperCamelCase : Dict = output.pixel_decoder_hidden_states _UpperCamelCase : Union[str, Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(__a ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__a ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__a ) , config.decoder_layers ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : List[Any] , __a : Tuple , __a : List[Any] , __a : Tuple=False ) -> Dict: with torch.no_grad(): _UpperCamelCase : int = MaskaFormerModel(config=__a ) model.to(__a ) model.eval() _UpperCamelCase : Optional[Any] = model(pixel_values=__a , pixel_mask=__a ) _UpperCamelCase : int = model(__a , output_hidden_states=__a ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(__a , __a ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : int , __a : Union[str, Any] , __a : List[str] , __a : Dict , __a : Dict ) -> List[Any]: _UpperCamelCase : Tuple = MaskaFormerForUniversalSegmentation(config=__a ) model.to(__a ) model.eval() def comm_check_on_output(__a : List[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): _UpperCamelCase : Optional[int] = model(pixel_values=__a , pixel_mask=__a ) _UpperCamelCase : str = model(__a ) comm_check_on_output(__a ) _UpperCamelCase : Tuple = model( pixel_values=__a , pixel_mask=__a , mask_labels=__a , class_labels=__a ) comm_check_on_output(__a ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class __SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[Any] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () SCREAMING_SNAKE_CASE__ :int = {"feature-extraction": MaskaFormerModel} if is_torch_available() else {} SCREAMING_SNAKE_CASE__ :Optional[Any] = False SCREAMING_SNAKE_CASE__ :Tuple = False SCREAMING_SNAKE_CASE__ :Union[str, Any] = False SCREAMING_SNAKE_CASE__ :Optional[int] = False def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: _UpperCamelCase : Dict = MaskaFormerModelTester(self ) _UpperCamelCase : Any = ConfigTester(self , config_class=__a , has_text_modality=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : Any ) -> int: _UpperCamelCase, _UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__a , **__a , output_hidden_states=__a ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: _UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__a ) @unittest.skip(reason="Mask2Former does not use inputs_embeds" ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: pass @unittest.skip(reason="Mask2Former does not have a get_input_embeddings method" ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> int: pass @unittest.skip(reason="Mask2Former is not a generative model" ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: pass @unittest.skip(reason="Mask2Former does not use token embeddings" ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: pass @require_torch_multi_gpu @unittest.skip( reason="Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`" ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Any: pass def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: _UpperCamelCase, _UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase : Any = model_class(__a ) _UpperCamelCase : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCamelCase : Dict = [*signature.parameters.keys()] _UpperCamelCase : List[str] = ["pixel_values"] self.assertListEqual(arg_names[:1] , __a ) @slow def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Union[str, Any]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _UpperCamelCase : int = MaskaFormerModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: _UpperCamelCase : Union[str, Any] = (self.model_tester.min_size,) * 2 _UpperCamelCase : Dict = { "pixel_values": torch.randn((2, 3, *size) , device=__a ), "mask_labels": torch.randn((2, 10, *size) , device=__a ), "class_labels": torch.zeros(2 , 10 , device=__a ).long(), } _UpperCamelCase : Optional[int] = self.model_tester.get_config() _UpperCamelCase : Optional[Any] = MaskaFormerForUniversalSegmentation(__a ).to(__a ) _UpperCamelCase : Optional[Any] = model(**__a ) self.assertTrue(outputs.loss is not None ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> int: _UpperCamelCase, _UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__a , **__a , output_hidden_states=__a ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[Any]: _UpperCamelCase, _UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase : Optional[int] = model_class(__a ).to(__a ) _UpperCamelCase : Optional[int] = model(**__a , output_attentions=__a ) self.assertTrue(outputs.attentions is not None ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: if not self.model_tester.is_training: return _UpperCamelCase : str = self.all_model_classes[1] _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() _UpperCamelCase : int = model_class(__a ) model.to(__a ) model.train() _UpperCamelCase : Tuple = model(__a , mask_labels=__a , class_labels=__a ).loss loss.backward() def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: _UpperCamelCase : int = self.all_model_classes[1] _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() _UpperCamelCase : Union[str, Any] = True _UpperCamelCase : List[Any] = True _UpperCamelCase : List[Any] = model_class(__a ).to(__a ) model.train() _UpperCamelCase : str = model(__a , mask_labels=__a , class_labels=__a ) _UpperCamelCase : List[Any] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _UpperCamelCase : Any = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _UpperCamelCase : int = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _UpperCamelCase : List[str] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=__a ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) lowerCamelCase__ = 1E-4 def lowercase__ ( ) -> Tuple: """simple docstring""" _UpperCamelCase : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: return "facebook/mask2former-swin-small-coco-instance" @cached_property def __SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: _UpperCamelCase : Any = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(__a ) _UpperCamelCase : Optional[Any] = self.default_image_processor _UpperCamelCase : int = prepare_img() _UpperCamelCase : str = image_processor(__a , return_tensors="pt" ).to(__a ) _UpperCamelCase : List[str] = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__a , (1, 3, 384, 384) ) with torch.no_grad(): _UpperCamelCase : Dict = model(**__a ) _UpperCamelCase : List[Any] = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]] ).to(__a ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , __a , atol=__a ) ) _UpperCamelCase : List[str] = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]] ).to(__a ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __a , atol=__a ) ) _UpperCamelCase : Tuple = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]] ).to(__a ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __a , atol=__a ) ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[str]: _UpperCamelCase : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__a ).eval() _UpperCamelCase : List[str] = self.default_image_processor _UpperCamelCase : int = prepare_img() _UpperCamelCase : str = image_processor(__a , return_tensors="pt" ).to(__a ) _UpperCamelCase : Optional[Any] = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__a , (1, 3, 384, 384) ) with torch.no_grad(): _UpperCamelCase : List[Any] = model(**__a ) # masks_queries_logits _UpperCamelCase : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) _UpperCamelCase : str = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] _UpperCamelCase : Tuple = torch.tensor(__a ).to(__a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __a , atol=__a ) ) # class_queries_logits _UpperCamelCase : int = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) _UpperCamelCase : int = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ] ).to(__a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __a , atol=__a ) ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: _UpperCamelCase : List[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__a ).eval() _UpperCamelCase : int = self.default_image_processor _UpperCamelCase : Tuple = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , ) _UpperCamelCase : Tuple = inputs["pixel_values"].to(__a ) _UpperCamelCase : int = [el.to(__a ) for el in inputs["mask_labels"]] _UpperCamelCase : Tuple = [el.to(__a ) for el in inputs["class_labels"]] with torch.no_grad(): _UpperCamelCase : str = model(**__a ) self.assertTrue(outputs.loss is not None )
716
"""simple docstring""" class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , __a : list[int] ) -> None: _UpperCamelCase : Tuple = len(__a ) _UpperCamelCase : Dict = [0] * len_array if len_array > 0: _UpperCamelCase : Optional[Any] = array[0] for i in range(1 , __a ): _UpperCamelCase : Tuple = self.prefix_sum[i - 1] + array[i] def __SCREAMING_SNAKE_CASE ( self : Dict , __a : int , __a : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : int ) -> bool: _UpperCamelCase : int = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(__a ) return False if __name__ == "__main__": import doctest doctest.testmod()
51
0
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __init__( self : Dict , __a : List[Any] , __a : List[str]=7 , __a : int=3 , __a : List[str]=30 , __a : Optional[int]=400 , __a : str=True , __a : Union[str, Any]=None , __a : int=True , __a : int=1 / 255 , __a : Tuple=True , __a : Optional[int]=[0.5, 0.5, 0.5] , __a : Any=[0.5, 0.5, 0.5] , __a : int=True , ) -> List[str]: _UpperCamelCase : int = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1333} _UpperCamelCase : Any = parent _UpperCamelCase : Dict = batch_size _UpperCamelCase : Optional[int] = num_channels _UpperCamelCase : List[str] = min_resolution _UpperCamelCase : List[str] = max_resolution _UpperCamelCase : Dict = do_resize _UpperCamelCase : Union[str, Any] = size _UpperCamelCase : Optional[Any] = do_rescale _UpperCamelCase : str = rescale_factor _UpperCamelCase : List[str] = do_normalize _UpperCamelCase : str = image_mean _UpperCamelCase : Optional[int] = image_std _UpperCamelCase : Tuple = do_pad def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : List[Any] , __a : Any=False ) -> Dict: if not batched: _UpperCamelCase : Tuple = image_inputs[0] if isinstance(lowerCamelCase__ , Image.Image ): _UpperCamelCase : List[str] = image.size else: _UpperCamelCase : int = image.shape[1], image.shape[2] if w < h: _UpperCamelCase : int = int(self.size["shortest_edge"] * h / w ) _UpperCamelCase : Union[str, Any] = self.size['''shortest_edge'''] elif w > h: _UpperCamelCase : Optional[Any] = self.size['''shortest_edge'''] _UpperCamelCase : str = int(self.size["shortest_edge"] * w / h ) else: _UpperCamelCase : List[str] = self.size['''shortest_edge'''] _UpperCamelCase : Optional[Any] = self.size['''shortest_edge'''] else: _UpperCamelCase : Any = [] for image in image_inputs: _UpperCamelCase : Union[str, Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _UpperCamelCase : int = max(lowerCamelCase__ , key=lambda __a : item[0] )[0] _UpperCamelCase : Tuple = max(lowerCamelCase__ , key=lambda __a : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( __lowerCAmelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = DetrImageProcessor if is_vision_available() else None def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: _UpperCamelCase : Dict = DetrImageProcessingTester(self ) @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: _UpperCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase__ , "image_mean" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "image_std" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "do_normalize" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "do_rescale" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "rescale_factor" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "do_resize" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "size" ) ) self.assertTrue(hasattr(lowerCamelCase__ , "do_pad" ) ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: _UpperCamelCase : Dict = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1333} ) self.assertEqual(image_processor.do_pad , lowerCamelCase__ ) _UpperCamelCase : Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowerCamelCase__ ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , lowerCamelCase__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> str: pass def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: _UpperCamelCase : int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCamelCase : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , Image.Image ) # Test not batched input _UpperCamelCase : str = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _UpperCamelCase : int = self.image_processor_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCamelCase : str = self.image_processor_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) _UpperCamelCase : Dict = image_processing(lowerCamelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: _UpperCamelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCamelCase : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ , numpify=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , np.ndarray ) # Test not batched input _UpperCamelCase : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _UpperCamelCase : List[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCamelCase : Optional[Any] = image_processing(lowerCamelCase__ , return_tensors="pt" ).pixel_values _UpperCamelCase : Dict = self.image_processor_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __SCREAMING_SNAKE_CASE ( self : int ) -> int: _UpperCamelCase : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCamelCase : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ , torchify=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , torch.Tensor ) # Test not batched input _UpperCamelCase : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _UpperCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _UpperCamelCase : str = image_processing(lowerCamelCase__ , return_tensors="pt" ).pixel_values _UpperCamelCase : List[str] = self.image_processor_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: _UpperCamelCase : Dict = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: _UpperCamelCase : Any = json.loads(f.read() ) _UpperCamelCase : Union[str, Any] = {'''image_id''': 3_9769, '''annotations''': target} # encode them _UpperCamelCase : Optional[Any] = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50" ) _UpperCamelCase : int = image_processing(images=lowerCamelCase__ , annotations=lowerCamelCase__ , return_tensors="pt" ) # verify pixel values _UpperCamelCase : List[str] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase__ ) _UpperCamelCase : int = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase__ , atol=1e-4 ) ) # verify area _UpperCamelCase : Dict = torch.tensor([58_87.96_00, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase__ ) ) # verify boxes _UpperCamelCase : Optional[Any] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase__ ) _UpperCamelCase : List[Any] = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase__ , atol=1e-3 ) ) # verify image_id _UpperCamelCase : Union[str, Any] = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase__ ) ) # verify is_crowd _UpperCamelCase : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase__ ) ) # verify class_labels _UpperCamelCase : str = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase__ ) ) # verify orig_size _UpperCamelCase : List[str] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase__ ) ) # verify size _UpperCamelCase : List[Any] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase__ ) ) @slow def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: _UpperCamelCase : Union[str, Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: _UpperCamelCase : Tuple = json.loads(f.read() ) _UpperCamelCase : Optional[Any] = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9769, '''segments_info''': target} _UpperCamelCase : Tuple = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them _UpperCamelCase : Optional[Any] = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50-panoptic" ) _UpperCamelCase : Dict = image_processing(images=lowerCamelCase__ , annotations=lowerCamelCase__ , masks_path=lowerCamelCase__ , return_tensors="pt" ) # verify pixel values _UpperCamelCase : Tuple = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase__ ) _UpperCamelCase : int = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase__ , atol=1e-4 ) ) # verify area _UpperCamelCase : Optional[Any] = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase__ ) ) # verify boxes _UpperCamelCase : List[Any] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase__ , atol=1e-3 ) ) # verify image_id _UpperCamelCase : Union[str, Any] = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase__ ) ) # verify is_crowd _UpperCamelCase : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase__ ) ) # verify class_labels _UpperCamelCase : List[str] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase__ ) ) # verify masks _UpperCamelCase : Optional[int] = 82_2873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase__ ) # verify orig_size _UpperCamelCase : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase__ ) ) # verify size _UpperCamelCase : List[Any] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase__ ) )
717
"""simple docstring""" import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def lowercase__ ( lowercase_ ,lowercase_=7 ) -> Tuple: """simple docstring""" _UpperCamelCase : Optional[int] = None if token is not None: _UpperCamelCase : Optional[Any] = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} # The id of a workflow (not of a workflow run) _UpperCamelCase : Any = "636036" _UpperCamelCase : Tuple = F'''https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs''' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'''?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}''' _UpperCamelCase : Dict = requests.get(lowercase_ ,headers=lowercase_ ).json() return result["workflow_runs"] def lowercase__ ( lowercase_ ) -> List[str]: """simple docstring""" _UpperCamelCase : List[Any] = get_daily_ci_runs(lowercase_ ) _UpperCamelCase : Tuple = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": _UpperCamelCase : Union[str, Any] = workflow_run["id"] break return workflow_run_id def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Optional[int]: """simple docstring""" _UpperCamelCase : str = get_last_daily_ci_runs(lowercase_ ) if workflow_run_id is not None: _UpperCamelCase : int = get_artifacts_links(worflow_run_id=lowercase_ ,token=lowercase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: _UpperCamelCase : Dict = artifacts_links[artifact_name] download_artifact( artifact_name=lowercase_ ,artifact_url=lowercase_ ,output_dir=lowercase_ ,token=lowercase_ ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> int: """simple docstring""" get_last_daily_ci_artifacts(lowercase_ ,lowercase_ ,lowercase_ ) _UpperCamelCase : Dict = {} for artifact_name in artifact_names: _UpperCamelCase : Union[str, Any] = os.path.join(lowercase_ ,F'''{artifact_name}.zip''' ) if os.path.isfile(lowercase_ ): _UpperCamelCase : int = {} with zipfile.ZipFile(lowercase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowercase_ ): # read the file with z.open(lowercase_ ) as f: _UpperCamelCase : int = f.read().decode("UTF-8" ) return results
51
0
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class __SCREAMING_SNAKE_CASE ( UpperCamelCase_ ): SCREAMING_SNAKE_CASE__ :Any = (DEISMultistepScheduler,) SCREAMING_SNAKE_CASE__ :int = (("num_inference_steps", 25),) def __SCREAMING_SNAKE_CASE ( self : List[str] , **__a : List[Any] ) -> List[str]: _UpperCamelCase : Dict = { '''num_train_timesteps''': 1000, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''solver_order''': 2, } config.update(**__a ) return config def __SCREAMING_SNAKE_CASE ( self : int , __a : Dict=0 , **__a : Any ) -> Optional[Any]: _UpperCamelCase : str = dict(self.forward_default_kwargs ) _UpperCamelCase : Optional[int] = kwargs.pop("num_inference_steps" , __a ) _UpperCamelCase : str = self.dummy_sample _UpperCamelCase : str = 0.1 * sample _UpperCamelCase : List[str] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: _UpperCamelCase : str = self.get_scheduler_config(**__a ) _UpperCamelCase : Union[str, Any] = scheduler_class(**__a ) scheduler.set_timesteps(__a ) # copy over dummy past residuals _UpperCamelCase : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__a ) _UpperCamelCase : Optional[int] = scheduler_class.from_pretrained(__a ) new_scheduler.set_timesteps(__a ) # copy over dummy past residuals _UpperCamelCase : Tuple = dummy_past_residuals[: new_scheduler.config.solver_order] _UpperCamelCase : List[Any] = sample, sample for t in range(__a , time_step + scheduler.config.solver_order + 1 ): _UpperCamelCase : Optional[int] = scheduler.step(__a , __a , __a , **__a ).prev_sample _UpperCamelCase : str = 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 __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: pass def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : Dict=0 , **__a : Dict ) -> List[str]: _UpperCamelCase : str = dict(self.forward_default_kwargs ) _UpperCamelCase : List[str] = kwargs.pop("num_inference_steps" , __a ) _UpperCamelCase : Union[str, Any] = self.dummy_sample _UpperCamelCase : int = 0.1 * sample _UpperCamelCase : int = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: _UpperCamelCase : Tuple = self.get_scheduler_config() _UpperCamelCase : Union[str, Any] = scheduler_class(**__a ) scheduler.set_timesteps(__a ) # copy over dummy past residuals (must be after setting timesteps) _UpperCamelCase : List[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__a ) _UpperCamelCase : List[Any] = 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) _UpperCamelCase : Dict = dummy_past_residuals[: new_scheduler.config.solver_order] _UpperCamelCase : Tuple = scheduler.step(__a , __a , __a , **__a ).prev_sample _UpperCamelCase : Union[str, Any] = 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 __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : List[str]=None , **__a : List[Any] ) -> Any: if scheduler is None: _UpperCamelCase : Dict = self.scheduler_classes[0] _UpperCamelCase : Optional[Any] = self.get_scheduler_config(**__a ) _UpperCamelCase : int = scheduler_class(**__a ) _UpperCamelCase : Optional[int] = self.scheduler_classes[0] _UpperCamelCase : str = self.get_scheduler_config(**__a ) _UpperCamelCase : Any = scheduler_class(**__a ) _UpperCamelCase : Dict = 10 _UpperCamelCase : Optional[int] = self.dummy_model() _UpperCamelCase : Any = self.dummy_sample_deter scheduler.set_timesteps(__a ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase : List[str] = model(__a , __a ) _UpperCamelCase : Any = scheduler.step(__a , __a , __a ).prev_sample return sample def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[str]: _UpperCamelCase : List[Any] = dict(self.forward_default_kwargs ) _UpperCamelCase : Dict = kwargs.pop("num_inference_steps" , __a ) for scheduler_class in self.scheduler_classes: _UpperCamelCase : Optional[Any] = self.get_scheduler_config() _UpperCamelCase : List[Any] = scheduler_class(**__a ) _UpperCamelCase : str = self.dummy_sample _UpperCamelCase : List[str] = 0.1 * sample if num_inference_steps is not None and hasattr(__a , "set_timesteps" ): scheduler.set_timesteps(__a ) elif num_inference_steps is not None and not hasattr(__a , "set_timesteps" ): _UpperCamelCase : List[str] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) _UpperCamelCase : Tuple = [residual + 0.2, residual + 0.15, residual + 0.10] _UpperCamelCase : List[str] = dummy_past_residuals[: scheduler.config.solver_order] _UpperCamelCase : Dict = scheduler.timesteps[5] _UpperCamelCase : List[str] = scheduler.timesteps[6] _UpperCamelCase : List[str] = scheduler.step(__a , __a , __a , **__a ).prev_sample _UpperCamelCase : Optional[int] = scheduler.step(__a , __a , __a , **__a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: # make sure that iterating over schedulers with same config names gives same results # for defaults _UpperCamelCase : str = DEISMultistepScheduler(**self.get_scheduler_config() ) _UpperCamelCase : List[str] = self.full_loop(scheduler=__a ) _UpperCamelCase : Tuple = torch.mean(torch.abs(__a ) ) assert abs(result_mean.item() - 0.2_39_16 ) < 1e-3 _UpperCamelCase : int = DPMSolverSinglestepScheduler.from_config(scheduler.config ) _UpperCamelCase : int = DPMSolverMultistepScheduler.from_config(scheduler.config ) _UpperCamelCase : str = UniPCMultistepScheduler.from_config(scheduler.config ) _UpperCamelCase : str = DEISMultistepScheduler.from_config(scheduler.config ) _UpperCamelCase : Optional[int] = self.full_loop(scheduler=__a ) _UpperCamelCase : Tuple = torch.mean(torch.abs(__a ) ) assert abs(result_mean.item() - 0.2_39_16 ) < 1e-3 def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Union[str, Any]: for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=__a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: self.check_over_configs(thresholding=__a ) for order in [1, 2, 3]: for solver_type in ["logrho"]: 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="deis" , solver_order=__a , solver_type=__a , ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: for algorithm_type in ["deis"]: for solver_type in ["logrho"]: 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 , ) _UpperCamelCase : List[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 __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: self.check_over_configs(lower_order_final=__a ) self.check_over_configs(lower_order_final=__a ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> int: 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 __SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: _UpperCamelCase : List[Any] = self.full_loop() _UpperCamelCase : Optional[Any] = torch.mean(torch.abs(__a ) ) assert abs(result_mean.item() - 0.2_39_16 ) < 1e-3 def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: _UpperCamelCase : List[Any] = self.full_loop(prediction_type="v_prediction" ) _UpperCamelCase : str = torch.mean(torch.abs(__a ) ) assert abs(result_mean.item() - 0.0_91 ) < 1e-3 def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase : Union[str, Any] = self.scheduler_classes[0] _UpperCamelCase : Tuple = self.get_scheduler_config(thresholding=__a , dynamic_thresholding_ratio=0 ) _UpperCamelCase : str = scheduler_class(**__a ) _UpperCamelCase : List[Any] = 10 _UpperCamelCase : str = self.dummy_model() _UpperCamelCase : List[str] = self.dummy_sample_deter.half() scheduler.set_timesteps(__a ) for i, t in enumerate(scheduler.timesteps ): _UpperCamelCase : int = model(__a , __a ) _UpperCamelCase : Dict = scheduler.step(__a , __a , __a ).prev_sample assert sample.dtype == torch.floataa
718
"""simple docstring""" import math class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Any , __a : list[list[float]] , __a : list[int] ) -> int: _UpperCamelCase : List[Any] = 0.0 _UpperCamelCase : Union[str, Any] = 0.0 for i in range(len(__a ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : list[list[int | float]] , __a : list[int] , __a : int , __a : float ) -> list[list[int | float]]: for i in range(len(__a ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def lowercase__ ( ) -> None: """simple docstring""" _UpperCamelCase : Optional[int] = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) _UpperCamelCase : List[str] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training _UpperCamelCase : List[Any] = SelfOrganizingMap() _UpperCamelCase : int = 3 _UpperCamelCase : List[Any] = 0.5 for _ in range(lowercase_ ): for j in range(len(lowercase_ ) ): # training sample _UpperCamelCase : int = training_samples[j] # Compute the winning vector _UpperCamelCase : Tuple = self_organizing_map.get_winner(lowercase_ ,lowercase_ ) # Update the winning vector _UpperCamelCase : int = self_organizing_map.update(lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) # classify test sample _UpperCamelCase : Optional[int] = [0, 0, 0, 1] _UpperCamelCase : Dict = self_organizing_map.get_winner(lowercase_ ,lowercase_ ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
51
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class __SCREAMING_SNAKE_CASE : '''simple docstring''' SCREAMING_SNAKE_CASE__ :str = LEDConfig SCREAMING_SNAKE_CASE__ :Union[str, Any] = {} SCREAMING_SNAKE_CASE__ :Optional[Any] = '''gelu''' def __init__( self : Tuple , __a : Dict , __a : Union[str, Any]=13 , __a : List[Any]=7 , __a : List[Any]=True , __a : Optional[Any]=False , __a : List[Any]=99 , __a : List[Any]=32 , __a : List[Any]=2 , __a : Optional[Any]=4 , __a : int=37 , __a : Any=0.1 , __a : List[str]=0.1 , __a : int=20 , __a : Any=2 , __a : Union[str, Any]=1 , __a : str=0 , __a : List[str]=4 , ) -> List[Any]: _UpperCamelCase : List[Any] = parent _UpperCamelCase : List[str] = batch_size _UpperCamelCase : List[Any] = seq_length _UpperCamelCase : Dict = is_training _UpperCamelCase : Union[str, Any] = use_labels _UpperCamelCase : Union[str, Any] = vocab_size _UpperCamelCase : List[str] = hidden_size _UpperCamelCase : Tuple = num_hidden_layers _UpperCamelCase : Any = num_attention_heads _UpperCamelCase : Optional[Any] = intermediate_size _UpperCamelCase : Any = hidden_dropout_prob _UpperCamelCase : List[str] = attention_probs_dropout_prob _UpperCamelCase : int = max_position_embeddings _UpperCamelCase : Optional[Any] = eos_token_id _UpperCamelCase : Union[str, Any] = pad_token_id _UpperCamelCase : Optional[Any] = bos_token_id _UpperCamelCase : Tuple = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after _UpperCamelCase : int = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests _UpperCamelCase : Optional[Any] = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: _UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _UpperCamelCase : Optional[int] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _UpperCamelCase : List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) _UpperCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase : Optional[int] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) _UpperCamelCase : List[Any] = prepare_led_inputs_dict(__a , __a , __a ) _UpperCamelCase : str = tf.concat( [tf.zeros_like(__a )[:, :-1], tf.ones_like(__a )[:, -1:]] , axis=-1 , ) _UpperCamelCase : Optional[Any] = global_attention_mask return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self : Any , __a : Dict , __a : Optional[int] ) -> Optional[Any]: _UpperCamelCase : str = TFLEDModel(config=__a ).get_decoder() _UpperCamelCase : Tuple = inputs_dict["input_ids"] _UpperCamelCase : List[str] = input_ids[:1, :] _UpperCamelCase : Tuple = inputs_dict["attention_mask"][:1, :] _UpperCamelCase : int = 1 # first forward pass _UpperCamelCase : Any = model(__a , attention_mask=__a , use_cache=__a ) _UpperCamelCase, _UpperCamelCase : Union[str, Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _UpperCamelCase : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _UpperCamelCase : Tuple = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _UpperCamelCase : Dict = tf.concat([input_ids, next_tokens] , axis=-1 ) _UpperCamelCase : List[Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _UpperCamelCase : Dict = model(__a , attention_mask=__a )[0] _UpperCamelCase : int = model(__a , attention_mask=__a , past_key_values=__a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _UpperCamelCase : Union[str, Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _UpperCamelCase : Optional[Any] = output_from_no_past[:, -3:, random_slice_idx] _UpperCamelCase : int = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__a , __a , rtol=1e-3 ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_=None ,lowercase_=None ,) -> int: """simple docstring""" if attention_mask is None: _UpperCamelCase : Any = tf.cast(tf.math.not_equal(UpperCamelCase__ ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: _UpperCamelCase : Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: _UpperCamelCase : List[Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _UpperCamelCase : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[int] = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :int = (TFLEDForConditionalGeneration,) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :List[Any] = ( { '''conversational''': TFLEDForConditionalGeneration, '''feature-extraction''': TFLEDModel, '''summarization''': TFLEDForConditionalGeneration, '''text2text-generation''': TFLEDForConditionalGeneration, '''translation''': TFLEDForConditionalGeneration, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ :Tuple = True SCREAMING_SNAKE_CASE__ :Optional[int] = False SCREAMING_SNAKE_CASE__ :Dict = False SCREAMING_SNAKE_CASE__ :List[Any] = False def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: _UpperCamelCase : List[Any] = TFLEDModelTester(self ) _UpperCamelCase : List[str] = ConfigTester(self , config_class=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: _UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> str: _UpperCamelCase, _UpperCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase : List[str] = tf.zeros_like(inputs_dict["attention_mask"] ) _UpperCamelCase : Dict = 2 _UpperCamelCase : Optional[int] = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) _UpperCamelCase : List[str] = True _UpperCamelCase : Tuple = self.model_tester.seq_length _UpperCamelCase : Dict = self.model_tester.encoder_seq_length def check_decoder_attentions_output(__a : Optional[Any] ): _UpperCamelCase : Optional[int] = outputs.decoder_attentions self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(__a : Union[str, Any] ): _UpperCamelCase : List[str] = [t.numpy() for t in outputs.encoder_attentions] _UpperCamelCase : Optional[Any] = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: _UpperCamelCase : Union[str, Any] = True _UpperCamelCase : Dict = False _UpperCamelCase : Union[str, Any] = False _UpperCamelCase : int = model_class(__a ) _UpperCamelCase : Tuple = model(self._prepare_for_class(__a , __a ) ) _UpperCamelCase : Any = len(__a ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) if self.is_encoder_decoder: _UpperCamelCase : int = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_decoder_attentions_output(__a ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _UpperCamelCase : Optional[Any] = True _UpperCamelCase : int = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) # Check attention is always last and order is fine _UpperCamelCase : List[str] = True _UpperCamelCase : Union[str, Any] = True _UpperCamelCase : Optional[Any] = model_class(__a ) _UpperCamelCase : Dict = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__a ) ) self.assertEqual(model.config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[Any]: pass def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: # TODO: Head-masking not yet implement pass def lowercase__ ( lowercase_ ) -> str: """simple docstring""" return tf.constant(UpperCamelCase__ ,dtype=tf.intaa ) lowerCamelCase__ = 1E-4 @slow @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[Any]: _UpperCamelCase : List[Any] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here _UpperCamelCase : List[str] = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : int = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : int = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Tuple = model(**__a )[0] _UpperCamelCase : List[str] = (1, 1024, 768) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : int = tf.convert_to_tensor( [[2.30_50, 2.82_79, 0.65_31], [-1.84_57, -0.14_55, -3.56_61], [-1.01_86, 0.45_86, -2.20_43]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: _UpperCamelCase : Optional[Any] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here _UpperCamelCase : int = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Union[str, Any] = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Optional[Any] = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Optional[Any] = model(**__a )[0] _UpperCamelCase : Any = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : Union[str, Any] = tf.convert_to_tensor( [[33.65_07, 6.45_72, 16.80_89], [5.87_39, -2.42_38, 11.29_02], [-3.21_39, -4.31_49, 4.27_83]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 , rtol=1e-3 )
719
"""simple docstring""" import argparse import collections import os import re 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/check_table.py lowerCamelCase__ = "src/transformers" lowerCamelCase__ = "docs/source/en" lowerCamelCase__ = "." def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> List[str]: """simple docstring""" with open(lowercase_ ,"r" ,encoding="utf-8" ,newline="\n" ) as f: _UpperCamelCase : Union[str, Any] = f.readlines() # Find the start prompt. _UpperCamelCase : Dict = 0 while not lines[start_index].startswith(lowercase_ ): start_index += 1 start_index += 1 _UpperCamelCase : Optional[int] = start_index while not lines[end_index].startswith(lowercase_ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | lowerCamelCase__ = "Model|Encoder|Decoder|ForConditionalGeneration" # 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)") # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase__ = direct_transformers_import(TRANSFORMERS_PATH) def lowercase__ ( lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Tuple = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)" ,lowercase_ ) return [m.group(0 ) for m in matches] def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : str = 2 if text == "✅" or text == "❌" else len(lowercase_ ) _UpperCamelCase : Union[str, Any] = (width - text_length) // 2 _UpperCamelCase : Dict = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def lowercase__ ( ) -> str: """simple docstring""" _UpperCamelCase : Optional[Any] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _UpperCamelCase : str = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } _UpperCamelCase : Dict = {name: config.replace("Config" ,"" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. _UpperCamelCase : int = collections.defaultdict(lowercase_ ) _UpperCamelCase : Dict = collections.defaultdict(lowercase_ ) _UpperCamelCase : Dict = collections.defaultdict(lowercase_ ) _UpperCamelCase : int = collections.defaultdict(lowercase_ ) _UpperCamelCase : str = collections.defaultdict(lowercase_ ) # Let's lookup through all transformers object (once). for attr_name in dir(lowercase_ ): _UpperCamelCase : List[str] = None if attr_name.endswith("Tokenizer" ): _UpperCamelCase : Tuple = slow_tokenizers _UpperCamelCase : Any = attr_name[:-9] elif attr_name.endswith("TokenizerFast" ): _UpperCamelCase : Optional[Any] = fast_tokenizers _UpperCamelCase : List[str] = attr_name[:-13] elif _re_tf_models.match(lowercase_ ) is not None: _UpperCamelCase : List[Any] = tf_models _UpperCamelCase : Dict = _re_tf_models.match(lowercase_ ).groups()[0] elif _re_flax_models.match(lowercase_ ) is not None: _UpperCamelCase : Dict = flax_models _UpperCamelCase : Union[str, Any] = _re_flax_models.match(lowercase_ ).groups()[0] elif _re_pt_models.match(lowercase_ ) is not None: _UpperCamelCase : Optional[int] = pt_models _UpperCamelCase : Any = _re_pt_models.match(lowercase_ ).groups()[0] if lookup_dict is not None: while len(lowercase_ ) > 0: if attr_name in model_name_to_prefix.values(): _UpperCamelCase : Dict = True break # Try again after removing the last word in the name _UpperCamelCase : List[str] = "".join(camel_case_split(lowercase_ )[:-1] ) # Let's build that table! _UpperCamelCase : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) _UpperCamelCase : List[str] = ["Model", "Tokenizer slow", "Tokenizer fast", "PyTorch support", "TensorFlow support", "Flax Support"] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). _UpperCamelCase : Union[str, Any] = [len(lowercase_ ) + 2 for c in columns] _UpperCamelCase : Any = max([len(lowercase_ ) for name in model_names] ) + 2 # Build the table per se _UpperCamelCase : Tuple = "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for c, w in zip(lowercase_ ,lowercase_ )] ) + "|\n" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths] ) + "|\n" _UpperCamelCase : Union[str, Any] = {True: "✅", False: "❌"} for name in model_names: _UpperCamelCase : Optional[int] = model_name_to_prefix[name] _UpperCamelCase : Tuple = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for l, w in zip(lowercase_ ,lowercase_ )] ) + "|\n" return table def lowercase__ ( lowercase_=False ) -> List[Any]: """simple docstring""" _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : str = _find_text_in_file( filename=os.path.join(lowercase_ ,"index.md" ) ,start_prompt="<!--This table is updated automatically from the auto modules" ,end_prompt="<!-- End table-->" ,) _UpperCamelCase : Any = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(lowercase_ ,"index.md" ) ,"w" ,encoding="utf-8" ,newline="\n" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( "The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this." ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") lowerCamelCase__ = parser.parse_args() check_model_table(args.fix_and_overwrite)
51
0
"""simple docstring""" 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 lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {"vocab_file": "vocab.txt", "emoji_file": "emoji.json"} lowerCamelCase__ = { "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", }, } lowerCamelCase__ = { "abeja/gpt-neox-japanese-2.7b": 2048, } def lowercase__ ( lowercase_ ,lowercase_ ) -> str: """simple docstring""" with open(lowerCamelCase__ ,"r" ,encoding="utf-8" ) as f: _UpperCamelCase : List[str] = json.loads(f.read() ) _UpperCamelCase : List[Any] = collections.OrderedDict() _UpperCamelCase : Union[str, Any] = collections.OrderedDict() _UpperCamelCase : Optional[Any] = collections.OrderedDict() with open(lowerCamelCase__ ,"r" ,encoding="utf-8" ) as f: _UpperCamelCase : Optional[Any] = f.readlines() _UpperCamelCase : List[Any] = [[t.rstrip("\n" )] if (t == "," or "," not in t) else t.rstrip("\n" ).split("," ) for t in token] for idx, b in enumerate(lowerCamelCase__ ): _UpperCamelCase : Optional[int] = b _UpperCamelCase : Union[str, Any] = idx for wd in b: _UpperCamelCase : int = idx return vocab, raw_vocab, ids_to_tokens, emoji class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[int] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ :Any = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ :Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ :str = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[Any] , __a : Tuple , __a : Optional[Any] , __a : Optional[Any]="<|endoftext|>" , __a : List[str]="<|endoftext|>" , __a : Any="<|startoftext|>" , __a : Any="<|endoftext|>" , __a : Tuple=False , **__a : List[str] , ) -> Optional[Any]: super().__init__( unk_token=__a , pad_token=__a , bos_token=__a , eos_token=__a , do_clean_text=__a , **__a , ) if not os.path.isfile(__a ): 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(__a ): 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)`" ) _UpperCamelCase : Optional[Any] = do_clean_text _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : int = load_vocab_and_emoji(__a , __a ) _UpperCamelCase : str = SubWordJapaneseTokenizer( vocab=self.vocab , ids_to_tokens=self.ids_to_tokens , emoji=self.emoji ) @property def __SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: return len(self.raw_vocab ) def __SCREAMING_SNAKE_CASE ( self : str ) -> str: return dict(self.raw_vocab , **self.added_tokens_encoder ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Tuple ) -> Optional[Any]: return self.subword_tokenizer.tokenize(__a , clean=self.do_clean_text ) def __SCREAMING_SNAKE_CASE ( self : int , __a : Optional[int] ) -> Dict: return self.vocab.get(__a , self.vocab.get(self.unk_token ) ) def __SCREAMING_SNAKE_CASE ( self : int , __a : List[Any] ) -> Tuple: return self.subword_tokenizer.convert_id_to_token(__a ) def __SCREAMING_SNAKE_CASE ( self : str , __a : int ) -> Optional[Any]: _UpperCamelCase : Tuple = "".join(__a ).strip() return out_string def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : "Conversation" ) -> List[int]: _UpperCamelCase : int = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__a , add_special_tokens=__a ) + [self.eos_token_id] ) if len(__a ) > self.model_max_length: _UpperCamelCase : Optional[Any] = input_ids[-self.model_max_length :] return input_ids def __SCREAMING_SNAKE_CASE ( self : int , __a : str , __a : Optional[str] = None ) -> Tuple[str]: _UpperCamelCase : List[Any] = 0 if os.path.isdir(__a ): _UpperCamelCase : int = os.path.join( __a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) _UpperCamelCase : str = os.path.join( __a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["emoji_file"] ) else: _UpperCamelCase : Union[str, Any] = ( (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["vocab_file"] ) _UpperCamelCase : List[Any] = ( (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["emoji_file"] ) with open(__a , "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!" ) _UpperCamelCase : Dict = token_index writer.write(",".join(__a ) + "\n" ) index += 1 with open(__a , "w" , encoding="utf-8" ) as writer: json.dump(self.emoji , __a ) return vocab_file, emoji_file class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __init__( self : str , __a : Dict , __a : Optional[Any] , __a : List[Any] ) -> int: _UpperCamelCase : Optional[int] = vocab # same as swe _UpperCamelCase : int = ids_to_tokens # same as bpe _UpperCamelCase : List[Any] = emoji _UpperCamelCase : List[Any] = np.max([len(__a ) for w in self.vocab.keys()] ) _UpperCamelCase : int = re.compile(R"(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)" ) _UpperCamelCase : Optional[Any] = re.compile(R"[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*" ) _UpperCamelCase : List[Any] = re.compile(R"[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}" ) _UpperCamelCase : int = 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}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*" ) _UpperCamelCase : Tuple = 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}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*" ) _UpperCamelCase : int = 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)*" ) _UpperCamelCase : Union[str, Any] = "─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿" _UpperCamelCase : List[Any] = "▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟" _UpperCamelCase : Union[str, Any] = str.maketrans({k: "<BLOCK>" for k in keisen + blocks} ) def __len__( self : List[str] ) -> List[str]: return len(self.ids_to_tokens ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : Any ) -> Optional[int]: _UpperCamelCase : Tuple = self.content_repattera.sub("<URL>" , __a ) _UpperCamelCase : Tuple = self.content_repattera.sub("<EMAIL>" , __a ) _UpperCamelCase : int = self.content_repattera.sub("<TEL>" , __a ) _UpperCamelCase : int = self.content_repattera.sub("<DATE>" , __a ) _UpperCamelCase : Dict = self.content_repattera.sub("<DATE>" , __a ) _UpperCamelCase : List[Any] = self.content_repattera.sub("<PRICE>" , __a ) _UpperCamelCase : str = content.translate(self.content_transa ) while "<BLOCK><BLOCK>" in content: _UpperCamelCase : Optional[Any] = content.replace("<BLOCK><BLOCK>" , "<BLOCK>" ) return content def __SCREAMING_SNAKE_CASE ( self : Any , __a : int , __a : Any=False ) -> Any: _UpperCamelCase : Optional[Any] = text.replace(" " , "<SP>" ) _UpperCamelCase : Optional[int] = text.replace(" " , "<SP>" ) _UpperCamelCase : Optional[Any] = text.replace("\r\n" , "<BR>" ) _UpperCamelCase : List[Any] = text.replace("\n" , "<BR>" ) _UpperCamelCase : Optional[int] = text.replace("\r" , "<BR>" ) _UpperCamelCase : Dict = text.replace("\t" , "<TAB>" ) _UpperCamelCase : Union[str, Any] = text.replace("—" , "ー" ) _UpperCamelCase : Union[str, Any] = text.replace("−" , "ー" ) for k, v in self.emoji["emoji"].items(): if k in text: _UpperCamelCase : List[str] = text.replace(__a , __a ) if clean: _UpperCamelCase : int = self.clean_text(__a ) def check_simbol(__a : Union[str, Any] ): _UpperCamelCase : Tuple = x.encode() if len(__a ) == 1 and len(__a ) == 2: _UpperCamelCase : Union[str, 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(__a : List[Any] ): _UpperCamelCase : List[Any] = x.encode() if len(__a ) == 1 and len(__a ) == 3: _UpperCamelCase : List[Any] = (int(e[0] ) << 16) + (int(e[1] ) << 8) + int(e[2] ) if c >= 0Xe2_8080 and c <= 0Xe2_b07f: return True return False _UpperCamelCase : Any = 0 _UpperCamelCase : Any = [] while pos < len(__a ): _UpperCamelCase : Any = min(len(__a ) , pos + self.maxlen + 1 ) if text[pos] == "<" else pos + 3 _UpperCamelCase : List[str] = [] # (token_id, token, pos) for e in range(__a , __a , -1 ): _UpperCamelCase : Optional[Any] = text[pos:e] if wd in self.vocab: if wd[0] == "<" and len(__a ) > 2: _UpperCamelCase : Any = [(self.vocab[wd], wd, e)] break else: candidates.append((self.vocab[wd], wd, e) ) if len(__a ) > 0: # the smallest token_id is adopted _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : Union[str, Any] = sorted(__a , key=lambda __a : x[0] )[0] result.append(__a ) _UpperCamelCase : Optional[Any] = e else: _UpperCamelCase : Optional[Any] = pos + 1 _UpperCamelCase : List[Any] = text[pos:end] if check_simbol(__a ): result.append("<KIGOU>" ) elif checkuae(__a ): result.append("<U2000U2BFF>" ) else: for i in wd.encode("utf-8" ): result.append("<|byte%d|>" % i ) _UpperCamelCase : Optional[int] = end return result def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Optional[Any] , __a : Optional[Any]="\n" ) -> List[Any]: _UpperCamelCase : str = [] _UpperCamelCase : int = [] _UpperCamelCase : int = self.ids_to_tokens[index][0] if word[:6] == "<|byte" and word[-2:] == "|>": byte_tokens.append(int(word[6:-2] ) ) else: if len(__a ) > 0: words.append(bytearray(__a ).decode("utf-8" , errors="replace" ) ) _UpperCamelCase : List[str] = [] if word[:7] == "<|emoji" and word[-2:] == "|>": words.append(self.emoji["emoji_inv"][word] ) elif word == "<SP>": words.append(" " ) elif word == "<BR>": words.append(__a ) elif word == "<TAB>": words.append("\t" ) elif word == "<BLOCK>": words.append("▀" ) elif word == "<KIGOU>": words.append("ǀ" ) elif word == "<U2000U2BFF>": words.append("‖" ) else: words.append(__a ) if len(__a ) > 0: words.append(bytearray(__a ).decode("utf-8" , errors="replace" ) ) _UpperCamelCase : List[Any] = "".join(__a ) return text
720
"""simple docstring""" from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. lowerCamelCase__ = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. lowerCamelCase__ = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. lowerCamelCase__ = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def lowercase__ ( lowercase_ ,lowercase_ ) -> tuple[str, float]: """simple docstring""" _UpperCamelCase : str = len([g for position, g in enumerate(lowercase_ ) if g == main_target[position]] ) return (item, float(lowercase_ )) def lowercase__ ( lowercase_ ,lowercase_ ) -> tuple[str, str]: """simple docstring""" _UpperCamelCase : Tuple = random.randint(0 ,len(lowercase_ ) - 1 ) _UpperCamelCase : Dict = parent_a[:random_slice] + parent_a[random_slice:] _UpperCamelCase : Tuple = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def lowercase__ ( lowercase_ ,lowercase_ ) -> str: """simple docstring""" _UpperCamelCase : int = list(lowercase_ ) if random.uniform(0 ,1 ) < MUTATION_PROBABILITY: _UpperCamelCase : int = random.choice(lowercase_ ) return "".join(lowercase_ ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,) -> list[str]: """simple docstring""" _UpperCamelCase : Optional[Any] = [] # Generate more children proportionally to the fitness score. _UpperCamelCase : List[str] = int(parent_a[1] * 100 ) + 1 _UpperCamelCase : Union[str, Any] = 10 if child_n >= 10 else child_n for _ in range(lowercase_ ): _UpperCamelCase : Dict = population_score[random.randint(0 ,lowercase_ )][0] _UpperCamelCase, _UpperCamelCase : Dict = crossover(parent_a[0] ,lowercase_ ) # Append new string to the population list. pop.append(mutate(lowercase_ ,lowercase_ ) ) pop.append(mutate(lowercase_ ,lowercase_ ) ) return pop def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ = True ) -> tuple[int, int, str]: """simple docstring""" if N_POPULATION < N_SELECTED: _UpperCamelCase : List[str] = F'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(lowercase_ ) # Verify that the target contains no genes besides the ones inside genes variable. _UpperCamelCase : int = sorted({c for c in target if c not in genes} ) if not_in_genes_list: _UpperCamelCase : int = F'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(lowercase_ ) # Generate random starting population. _UpperCamelCase : Union[str, Any] = [] for _ in range(lowercase_ ): population.append("".join([random.choice(lowercase_ ) for i in range(len(lowercase_ ) )] ) ) # Just some logs to know what the algorithms is doing. _UpperCamelCase, _UpperCamelCase : str = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowercase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. _UpperCamelCase : int = [evaluate(lowercase_ ,lowercase_ ) for item in population] # Check if there is a matching evolution. _UpperCamelCase : Optional[Any] = sorted(lowercase_ ,key=lambda lowercase_ : x[1] ,reverse=lowercase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'''\nGeneration: {generation}''' F'''\nTotal Population:{total_population}''' F'''\nBest score: {population_score[0][1]}''' F'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. _UpperCamelCase : str = population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowercase_ ) # Normalize population score to be between 0 and 1. _UpperCamelCase : str = [ (item, score / len(lowercase_ )) for item, score in population_score ] # This is selection for i in range(lowercase_ ): population.extend(select(population_score[int(lowercase_ )] ,lowercase_ ,lowercase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowercase_ ) > N_POPULATION: break if __name__ == "__main__": lowerCamelCase__ = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) lowerCamelCase__ = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = basic(target_str, genes_list) print( f"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}""" )
51
0
"""simple docstring""" import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration lowerCamelCase__ = pytest.mark.integration lowerCamelCase__ = {"comet"} lowerCamelCase__ = importlib.util.find_spec("fairseq") is not None lowerCamelCase__ = {"code_eval"} lowerCamelCase__ = os.name == "nt" lowerCamelCase__ = {"bertscore", "frugalscore", "perplexity"} lowerCamelCase__ = importlib.util.find_spec("transformers") is not None def lowercase__ ( lowercase_ ) -> Tuple: """simple docstring""" @wraps(lowercase_ ) def wrapper(self ,lowercase_ ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("\"test requires Fairseq\"" ) else: test_case(self ,lowercase_ ) return wrapper def lowercase__ ( lowercase_ ) -> Dict: """simple docstring""" @wraps(lowercase_ ) def wrapper(self ,lowercase_ ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("\"test requires transformers\"" ) else: test_case(self ,lowercase_ ) return wrapper def lowercase__ ( lowercase_ ) -> int: """simple docstring""" @wraps(lowercase_ ) def wrapper(self ,lowercase_ ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("\"test not supported on Windows\"" ) else: test_case(self ,lowercase_ ) return wrapper def lowercase__ ( ) -> List[Any]: """simple docstring""" _UpperCamelCase : str = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( snake_case__ , snake_case__ , snake_case__ ) @local class __SCREAMING_SNAKE_CASE ( parameterized.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[int] = {} SCREAMING_SNAKE_CASE__ :Union[str, Any] = None @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning" ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : List[str] ) -> Dict: _UpperCamelCase : List[Any] = "[...]" _UpperCamelCase : List[Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , _SCREAMING_SNAKE_CASE ) ).module_path ) _UpperCamelCase : Optional[int] = datasets.load.import_main_class(metric_module.__name__ , dataset=_SCREAMING_SNAKE_CASE ) # check parameters _UpperCamelCase : Tuple = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(_SCREAMING_SNAKE_CASE , metric_module.__name__ ): with self.use_local_metrics(): try: _UpperCamelCase : Tuple = doctest.testmod(_SCREAMING_SNAKE_CASE , verbose=_SCREAMING_SNAKE_CASE , raise_on_error=_SCREAMING_SNAKE_CASE ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __SCREAMING_SNAKE_CASE ( self : int , __a : Tuple ) -> Tuple: _UpperCamelCase : Dict = "[...]" _UpperCamelCase : str = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , _SCREAMING_SNAKE_CASE ) ).module_path ) # run doctest with self.use_local_metrics(): _UpperCamelCase : Tuple = doctest.testmod(_SCREAMING_SNAKE_CASE , verbose=_SCREAMING_SNAKE_CASE , raise_on_error=_SCREAMING_SNAKE_CASE ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : Optional[int] , __a : int ) -> Optional[int]: if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](_SCREAMING_SNAKE_CASE ): yield else: yield @contextmanager def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: def load_local_metric(__a : List[str] , *__a : List[str] , **__a : Dict ): return load_metric(os.path.join("metrics" , _SCREAMING_SNAKE_CASE ) , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) with patch("datasets.load_metric" ) as mock_load_metric: _UpperCamelCase : List[Any] = load_local_metric yield @classmethod def __SCREAMING_SNAKE_CASE ( cls : List[str] , __a : Union[str, Any] ) -> Any: def wrapper(__a : str ): _UpperCamelCase : int = contextmanager(_SCREAMING_SNAKE_CASE ) _UpperCamelCase : List[str] = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("bleurt" ) def lowercase__ ( lowercase_ ) -> List[Any]: """simple docstring""" import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("sv" ,"" ,"" ) # handle pytest cli flags class __SCREAMING_SNAKE_CASE ( snake_case__ ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : Optional[int] ) -> List[str]: assert len(input_dict["input_ids"] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("bleurt.score._create_predictor" ) as mock_create_predictor: _UpperCamelCase : Optional[Any] = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("bertscore" ) def lowercase__ ( lowercase_ ) -> List[Any]: """simple docstring""" import torch def bert_cos_score_idf(lowercase_ ,lowercase_ ,*lowercase_ ,**lowercase_ ): return torch.tensor([[1.0, 1.0, 1.0]] * len(lowercase_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("bert_score.scorer.get_model" ), patch( "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf: _UpperCamelCase : Optional[int] = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("comet" ) def lowercase__ ( lowercase_ ) -> str: """simple docstring""" def load_from_checkpoint(lowercase_ ): class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Dict , __a : List[str] , *__a : Tuple , **__a : List[Any] ) -> Dict: assert len(_SCREAMING_SNAKE_CASE ) == 2 _UpperCamelCase : Any = [0.19, 0.92] return scores, sum(_SCREAMING_SNAKE_CASE ) / len(_SCREAMING_SNAKE_CASE ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("comet.download_model" ) as mock_download_model: _UpperCamelCase : str = None with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint: _UpperCamelCase : Any = load_from_checkpoint yield def lowercase__ ( ) -> str: """simple docstring""" _UpperCamelCase : Dict = load_metric(os.path.join("metrics" ,"seqeval" ) ) _UpperCamelCase : List[str] = "ERROR" _UpperCamelCase : str = F'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}''' with pytest.raises(lowercase_ ,match=re.escape(lowercase_ ) ): metric.compute(predictions=[] ,references=[] ,scheme=lowercase_ )
721
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = ["model.decoder.embed_positions.weights"] def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" if "emb" in name: _UpperCamelCase : List[str] = name.replace("emb" ,"model.decoder.embed_tokens" ) if "transformer" in name: _UpperCamelCase : Optional[int] = name.replace("transformer" ,"model.decoder" ) if "cross_attention" in name: _UpperCamelCase : Optional[int] = name.replace("cross_attention" ,"encoder_attn" ) if "linear1" in name: _UpperCamelCase : Optional[Any] = name.replace("linear1" ,"fc1" ) if "linear2" in name: _UpperCamelCase : Union[str, Any] = name.replace("linear2" ,"fc2" ) if "norm1" in name: _UpperCamelCase : Optional[Any] = name.replace("norm1" ,"self_attn_layer_norm" ) if "norm_cross" in name: _UpperCamelCase : Dict = name.replace("norm_cross" ,"encoder_attn_layer_norm" ) if "norm2" in name: _UpperCamelCase : Union[str, Any] = name.replace("norm2" ,"final_layer_norm" ) if "out_norm" in name: _UpperCamelCase : Union[str, Any] = name.replace("out_norm" ,"model.decoder.layer_norm" ) if "linears" in name: _UpperCamelCase : List[str] = name.replace("linears" ,"lm_heads" ) if "condition_provider.conditioners.description.output_proj" in name: _UpperCamelCase : Any = name.replace("condition_provider.conditioners.description.output_proj" ,"enc_to_dec_proj" ) return name def lowercase__ ( lowercase_ ,lowercase_ ) -> Tuple[Dict, Dict]: """simple docstring""" _UpperCamelCase : str = list(state_dict.keys() ) _UpperCamelCase : Optional[Any] = {} for key in keys: _UpperCamelCase : Optional[int] = state_dict.pop(lowercase_ ) _UpperCamelCase : List[Any] = rename_keys(lowercase_ ) if "in_proj_weight" in key: # split fused qkv proj _UpperCamelCase : Tuple = val[:hidden_size, :] _UpperCamelCase : Optional[Any] = val[hidden_size : 2 * hidden_size, :] _UpperCamelCase : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _UpperCamelCase : Optional[Any] = val else: _UpperCamelCase : List[str] = val return state_dict, enc_dec_proj_state_dict def lowercase__ ( lowercase_ ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values _UpperCamelCase : List[Any] = 1_024 _UpperCamelCase : List[str] = 24 _UpperCamelCase : Any = 16 elif checkpoint == "medium": _UpperCamelCase : Tuple = 1_536 _UpperCamelCase : Dict = 48 _UpperCamelCase : Tuple = 24 elif checkpoint == "large": _UpperCamelCase : int = 2_048 _UpperCamelCase : Optional[int] = 48 _UpperCamelCase : Dict = 32 else: raise ValueError(F'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' ) _UpperCamelCase : str = MusicgenDecoderConfig( hidden_size=lowercase_ ,ffn_dim=hidden_size * 4 ,num_hidden_layers=lowercase_ ,num_attention_heads=lowercase_ ,) return config @torch.no_grad() def lowercase__ ( lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_="cpu" ) -> List[str]: """simple docstring""" _UpperCamelCase : str = MusicGen.get_pretrained(lowercase_ ,device=lowercase_ ) _UpperCamelCase : Union[str, Any] = decoder_config_from_checkpoint(lowercase_ ) _UpperCamelCase : Optional[int] = fairseq_model.lm.state_dict() _UpperCamelCase, _UpperCamelCase : Optional[Any] = rename_state_dict( lowercase_ ,hidden_size=decoder_config.hidden_size ) _UpperCamelCase : Tuple = TaEncoderModel.from_pretrained("t5-base" ) _UpperCamelCase : Union[str, Any] = EncodecModel.from_pretrained("facebook/encodec_32khz" ) _UpperCamelCase : str = MusicgenForCausalLM(lowercase_ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _UpperCamelCase, _UpperCamelCase : str = decoder.load_state_dict(lowercase_ ,strict=lowercase_ ) for key in missing_keys.copy(): if key.startswith(("text_encoder", "audio_encoder") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(lowercase_ ) if len(lowercase_ ) > 0: raise ValueError(F'''Missing key(s) in state_dict: {missing_keys}''' ) if len(lowercase_ ) > 0: raise ValueError(F'''Unexpected key(s) in state_dict: {unexpected_keys}''' ) # init the composite model _UpperCamelCase : str = MusicgenForConditionalGeneration(text_encoder=lowercase_ ,audio_encoder=lowercase_ ,decoder=lowercase_ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(lowercase_ ) # check we can do a forward pass _UpperCamelCase : List[str] = torch.arange(0 ,8 ,dtype=torch.long ).reshape(2 ,-1 ) _UpperCamelCase : Dict = input_ids.reshape(2 * 4 ,-1 ) with torch.no_grad(): _UpperCamelCase : Tuple = model(input_ids=lowercase_ ,decoder_input_ids=lowercase_ ).logits if logits.shape != (8, 1, 2_048): raise ValueError("Incorrect shape for logits" ) # now construct the processor _UpperCamelCase : int = AutoTokenizer.from_pretrained("t5-base" ) _UpperCamelCase : str = AutoFeatureExtractor.from_pretrained("facebook/encodec_32khz" ,padding_side="left" ) _UpperCamelCase : Optional[int] = MusicgenProcessor(feature_extractor=lowercase_ ,tokenizer=lowercase_ ) # set the appropriate bos/pad token ids _UpperCamelCase : str = 2_048 _UpperCamelCase : str = 2_048 # set other default generation config params _UpperCamelCase : Optional[Any] = int(30 * audio_encoder.config.frame_rate ) _UpperCamelCase : List[str] = True _UpperCamelCase : int = 3.0 if pytorch_dump_folder is not None: Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) logger.info(F'''Saving model {checkpoint} to {pytorch_dump_folder}''' ) model.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) if repo_id: logger.info(F'''Pushing model {checkpoint} to {repo_id}''' ) model.push_to_hub(lowercase_ ) processor.push_to_hub(lowercase_ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) lowerCamelCase__ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
51
0
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : int ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Tuple: torch.manual_seed(0 ) _UpperCamelCase : Dict = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return model @property def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: torch.manual_seed(0 ) _UpperCamelCase : int = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , cross_attention_dim=10 , ) return model @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: torch.manual_seed(0 ) _UpperCamelCase : Any = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("DownEncoderBlock2D", "DownEncoderBlock2D") , up_block_types=("UpDecoderBlock2D", "UpDecoderBlock2D") , ) _UpperCamelCase : List[Any] = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=("AttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "AttnUpBlock2D") , ) return vqvae, unet @slow def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: _UpperCamelCase : List[str] = "cpu" # ensure determinism for the device-dependent torch.Generator _UpperCamelCase : Union[str, Any] = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) _UpperCamelCase : Union[str, Any] = DDPMScheduler() _UpperCamelCase : int = AudioDiffusionPipeline(vqvae=__a , unet=self.dummy_unet , mel=__a , scheduler=__a ) _UpperCamelCase : Optional[int] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase : List[str] = torch.Generator(device=__a ).manual_seed(42 ) _UpperCamelCase : List[str] = pipe(generator=__a , steps=4 ) _UpperCamelCase : int = output.audios[0] _UpperCamelCase : Tuple = output.images[0] _UpperCamelCase : str = torch.Generator(device=__a ).manual_seed(42 ) _UpperCamelCase : str = pipe(generator=__a , steps=4 , return_dict=__a ) _UpperCamelCase : Optional[int] = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) _UpperCamelCase : Tuple = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] _UpperCamelCase : Union[str, Any] = np.frombuffer(image_from_tuple.tobytes() , dtype="uint8" )[:10] _UpperCamelCase : List[Any] = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 _UpperCamelCase : Optional[Any] = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) _UpperCamelCase : Tuple = DDIMScheduler() _UpperCamelCase : Any = self.dummy_vqvae_and_unet _UpperCamelCase : str = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=__a , scheduler=__a ) _UpperCamelCase : Union[str, Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) np.random.seed(0 ) _UpperCamelCase : Optional[Any] = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) _UpperCamelCase : Dict = torch.Generator(device=__a ).manual_seed(42 ) _UpperCamelCase : Dict = pipe(raw_audio=__a , generator=__a , start_step=5 , steps=10 ) _UpperCamelCase : Optional[int] = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) _UpperCamelCase : int = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] _UpperCamelCase : int = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 _UpperCamelCase : int = self.dummy_unet_condition _UpperCamelCase : Optional[Any] = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=__a , mel=__a , scheduler=__a ) _UpperCamelCase : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) np.random.seed(0 ) _UpperCamelCase : Optional[int] = torch.rand((1, 1, 10) ) _UpperCamelCase : Any = pipe(generator=__a , encoding=__a ) _UpperCamelCase : int = output.images[0] _UpperCamelCase : str = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] _UpperCamelCase : Dict = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE ( self : int ) -> str: _UpperCamelCase : Any = torch_device _UpperCamelCase : Optional[Any] = DiffusionPipeline.from_pretrained("teticio/audio-diffusion-ddim-256" ) _UpperCamelCase : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase : Any = torch.Generator(device=__a ).manual_seed(42 ) _UpperCamelCase : List[str] = pipe(generator=__a ) _UpperCamelCase : Any = output.audios[0] _UpperCamelCase : Optional[int] = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] _UpperCamelCase : List[Any] = np.frombuffer(image.tobytes() , dtype="uint8" )[:10] _UpperCamelCase : int = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
700
"""simple docstring""" from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowerCamelCase__ = input("Enter image url: ").strip() print(f"""Downloading image from {url} ...""") lowerCamelCase__ = BeautifulSoup(requests.get(url).content, "html.parser") # The image URL is in the content field of the first meta tag with property og:image lowerCamelCase__ = soup.find("meta", {"property": "og:image"})["content"] lowerCamelCase__ = requests.get(image_url).content lowerCamelCase__ = f"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, "wb") as fp: fp.write(image_data) print(f"""Done. Image saved to disk as {file_name}.""")
51
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "google/canine-s": "https://huggingface.co/google/canine-s/resolve/main/config.json", # See all CANINE models at https://huggingface.co/models?filter=canine } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Union[str, Any] = "canine" def __init__( self : Tuple , __a : Dict=768 , __a : Dict=12 , __a : int=12 , __a : str=3072 , __a : str="gelu" , __a : List[str]=0.1 , __a : Optional[Any]=0.1 , __a : int=1_6384 , __a : Dict=16 , __a : Optional[Any]=0.02 , __a : Any=1e-1_2 , __a : Union[str, Any]=0 , __a : Optional[int]=0Xe000 , __a : Union[str, Any]=0Xe001 , __a : str=4 , __a : str=4 , __a : Union[str, Any]=8 , __a : int=1_6384 , __a : Optional[Any]=128 , **__a : Dict , ) -> Optional[int]: super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) _UpperCamelCase : List[str] = max_position_embeddings _UpperCamelCase : int = hidden_size _UpperCamelCase : List[str] = num_hidden_layers _UpperCamelCase : int = num_attention_heads _UpperCamelCase : Tuple = intermediate_size _UpperCamelCase : Union[str, Any] = hidden_act _UpperCamelCase : Union[str, Any] = hidden_dropout_prob _UpperCamelCase : Tuple = attention_probs_dropout_prob _UpperCamelCase : Any = initializer_range _UpperCamelCase : Optional[int] = type_vocab_size _UpperCamelCase : str = layer_norm_eps # Character config: _UpperCamelCase : Optional[int] = downsampling_rate _UpperCamelCase : Optional[int] = upsampling_kernel_size _UpperCamelCase : List[Any] = num_hash_functions _UpperCamelCase : List[Any] = num_hash_buckets _UpperCamelCase : Tuple = local_transformer_stride
701
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append(".") def lowercase__ ( lowercase_ ) -> int: """simple docstring""" _UpperCamelCase : Any = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " F'''{test_file} instead.''' ) _UpperCamelCase : str = components[-1] if not test_fn.endswith("py" ): raise ValueError(F'''`test_file` should be a python file. Got {test_fn} instead.''' ) if not test_fn.startswith("test_modeling_" ): raise ValueError( F'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.''' ) _UpperCamelCase : Dict = components[:-1] + [test_fn.replace(".py" ,"" )] _UpperCamelCase : List[str] = ".".join(lowercase_ ) return test_module_path def lowercase__ ( lowercase_ ) -> List[Any]: """simple docstring""" _UpperCamelCase : Optional[Any] = get_module_path(lowercase_ ) _UpperCamelCase : str = importlib.import_module(lowercase_ ) return test_module def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : Union[str, Any] = [] _UpperCamelCase : List[Any] = get_test_module(lowercase_ ) for attr in dir(lowercase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowercase_ ,lowercase_ ) ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Tuple: """simple docstring""" _UpperCamelCase : Optional[Any] = [] _UpperCamelCase : Any = get_test_module(lowercase_ ) for attr in dir(lowercase_ ): _UpperCamelCase : int = getattr(lowercase_ ,lowercase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). _UpperCamelCase : Optional[Any] = getattr(lowercase_ ,"all_model_classes" ,[] ) if len(lowercase_ ) > 0: test_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Dict = get_test_classes(lowercase_ ) _UpperCamelCase : int = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : List[str] = test_class() if hasattr(lowercase_ ,"setUp" ): test.setUp() _UpperCamelCase : Tuple = None if hasattr(lowercase_ ,"model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: _UpperCamelCase : Tuple = test.model_tester.__class__ return model_tester def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : str = get_test_classes(lowercase_ ) _UpperCamelCase : Dict = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ,lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : Any = get_test_classes_for_model(lowercase_ ,lowercase_ ) _UpperCamelCase : List[Any] = [] for test_class in test_classes: _UpperCamelCase : List[Any] = get_model_tester_from_test_class(lowercase_ ) if tester_class is not None: tester_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Any = get_test_classes(lowercase_ ) _UpperCamelCase : Tuple = {test_class: get_model_tester_from_test_class(lowercase_ ) for test_class in test_classes} return test_tester_mapping def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : List[Any] = get_model_classes(lowercase_ ) _UpperCamelCase : Optional[int] = { model_class: get_test_classes_for_model(lowercase_ ,lowercase_ ) for model_class in model_classes } return model_test_mapping def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Optional[Any] = get_model_classes(lowercase_ ) _UpperCamelCase : Tuple = { model_class: get_tester_classes_for_model(lowercase_ ,lowercase_ ) for model_class in model_classes } return model_to_tester_mapping def lowercase__ ( lowercase_ ) -> Optional[int]: """simple docstring""" if isinstance(lowercase_ ,lowercase_ ): return o elif isinstance(lowercase_ ,lowercase_ ): return o.__name__ elif isinstance(lowercase_ ,(list, tuple) ): return [to_json(lowercase_ ) for x in o] elif isinstance(lowercase_ ,lowercase_ ): return {to_json(lowercase_ ): to_json(lowercase_ ) for k, v in o.items()} else: return o
51
0
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Union[str, Any] = RoCBertTokenizer SCREAMING_SNAKE_CASE__ :Dict = None SCREAMING_SNAKE_CASE__ :List[Any] = False SCREAMING_SNAKE_CASE__ :Union[str, Any] = True SCREAMING_SNAKE_CASE__ :Union[str, Any] = filter_non_english def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: super().setUp() _UpperCamelCase : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] _UpperCamelCase : List[str] = {} _UpperCamelCase : Tuple = {} for i, value in enumerate(__a ): _UpperCamelCase : List[str] = i _UpperCamelCase : Optional[Any] = i _UpperCamelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) _UpperCamelCase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(__a , __a , ensure_ascii=__a ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(__a , __a , ensure_ascii=__a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: _UpperCamelCase : Tuple = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : int = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(__a , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__a ) , [5, 6, 2, 5, 7, 8] ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: _UpperCamelCase : Dict = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: _UpperCamelCase : List[Any] = RoCBertBasicTokenizer(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 : Optional[Any] ) -> Tuple: _UpperCamelCase : Optional[Any] = RoCBertBasicTokenizer(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 : Dict ) -> str: _UpperCamelCase : Dict = RoCBertBasicTokenizer(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 : Union[str, Any] ) -> Union[str, Any]: _UpperCamelCase : List[str] = RoCBertBasicTokenizer(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[int]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase : Union[str, Any] = RoCBertBasicTokenizer(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 : Tuple ) -> List[Any]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(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 : Optional[Any] ) -> int: _UpperCamelCase : int = RoCBertBasicTokenizer(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 : List[str] ) -> Optional[Any]: _UpperCamelCase : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] _UpperCamelCase : Any = {} for i, token in enumerate(__a ): _UpperCamelCase : str = i _UpperCamelCase : Optional[int] = RoCBertWordpieceTokenizer(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 : Dict ) -> Optional[Any]: 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: 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 : Optional[int] ) -> Optional[int]: 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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = self.get_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]"]] ) if self.test_rust_tokenizer: _UpperCamelCase : Tuple = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__a ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Union[str, Any] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' _UpperCamelCase : Optional[Any] = tokenizer_r.encode_plus( __a , return_attention_mask=__a , return_token_type_ids=__a , return_offsets_mapping=__a , add_special_tokens=__a , ) _UpperCamelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(__a , "do_lower_case" ) else False _UpperCamelCase : Dict = ( [ ((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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = ["的", "人", "有"] _UpperCamelCase : int = "".join(__a ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = True _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : int = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : int = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : List[Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Union[str, Any] = 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 ) _UpperCamelCase : Any = False _UpperCamelCase : Dict = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Any = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Dict = tokenizer_p.convert_ids_to_tokens(__a ) # it is expected that only the first Chinese character is not preceded by "##". _UpperCamelCase : Any = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(__a ) ] self.assertListEqual(__a , __a ) self.assertListEqual(__a , __a ) @slow def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: _UpperCamelCase : Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : Optional[int] = tokenizer.encode("你好" , add_special_tokens=__a ) _UpperCamelCase : Dict = tokenizer.encode("你是谁" , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__a ) _UpperCamelCase : Tuple = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: _UpperCamelCase : Optional[Any] = self.get_tokenizers(do_lower_case=__a ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): _UpperCamelCase : int = "你好,你是谁" _UpperCamelCase : Any = tokenizer.tokenize(__a ) _UpperCamelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(__a ) _UpperCamelCase : List[str] = tokenizer.convert_tokens_to_shape_ids(__a ) _UpperCamelCase : Any = tokenizer.convert_tokens_to_pronunciation_ids(__a ) _UpperCamelCase : Optional[int] = tokenizer.prepare_for_model( __a , __a , __a , add_special_tokens=__a ) _UpperCamelCase : Tuple = tokenizer.encode_plus(__a , add_special_tokens=__a ) self.assertEqual(__a , __a )
702
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure)
51
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) def lowercase__ ( lowercase_ ) -> YolosConfig: """simple docstring""" _UpperCamelCase : str = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: _UpperCamelCase : Union[str, Any] = 192 _UpperCamelCase : Dict = 768 _UpperCamelCase : str = 12 _UpperCamelCase : List[Any] = 3 _UpperCamelCase : List[Any] = [800, 1_333] _UpperCamelCase : Union[str, Any] = False elif yolos_name == "yolos_s_dWr": _UpperCamelCase : Optional[int] = 330 _UpperCamelCase : int = 14 _UpperCamelCase : int = 6 _UpperCamelCase : Dict = 1_320 elif "yolos_s" in yolos_name: _UpperCamelCase : Tuple = 384 _UpperCamelCase : List[Any] = 1_536 _UpperCamelCase : Dict = 12 _UpperCamelCase : str = 6 elif "yolos_b" in yolos_name: _UpperCamelCase : int = [800, 1_344] _UpperCamelCase : Union[str, Any] = 91 _UpperCamelCase : Dict = "huggingface/label-files" _UpperCamelCase : int = "coco-detection-id2label.json" _UpperCamelCase : Optional[int] = json.load(open(hf_hub_download(lowercase_ ,lowercase_ ,repo_type="dataset" ) ,"r" ) ) _UpperCamelCase : Tuple = {int(lowercase_ ): v for k, v in idalabel.items()} _UpperCamelCase : Optional[Any] = idalabel _UpperCamelCase : Any = {v: k for k, v in idalabel.items()} return config def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ = False ) -> Optional[Any]: """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _UpperCamelCase : List[str] = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) _UpperCamelCase : Optional[int] = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict _UpperCamelCase : Union[str, Any] = in_proj_weight[: config.hidden_size, :] _UpperCamelCase : List[Any] = in_proj_bias[: config.hidden_size] _UpperCamelCase : Optional[int] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _UpperCamelCase : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _UpperCamelCase : Dict = in_proj_weight[-config.hidden_size :, :] _UpperCamelCase : List[str] = in_proj_bias[-config.hidden_size :] def lowercase__ ( lowercase_ ) -> str: """simple docstring""" if "backbone" in name: _UpperCamelCase : List[str] = name.replace("backbone" ,"vit" ) if "cls_token" in name: _UpperCamelCase : Tuple = name.replace("cls_token" ,"embeddings.cls_token" ) if "det_token" in name: _UpperCamelCase : str = name.replace("det_token" ,"embeddings.detection_tokens" ) if "mid_pos_embed" in name: _UpperCamelCase : Dict = name.replace("mid_pos_embed" ,"encoder.mid_position_embeddings" ) if "pos_embed" in name: _UpperCamelCase : str = name.replace("pos_embed" ,"embeddings.position_embeddings" ) if "patch_embed.proj" in name: _UpperCamelCase : List[Any] = name.replace("patch_embed.proj" ,"embeddings.patch_embeddings.projection" ) if "blocks" in name: _UpperCamelCase : Dict = name.replace("blocks" ,"encoder.layer" ) if "attn.proj" in name: _UpperCamelCase : Dict = name.replace("attn.proj" ,"attention.output.dense" ) if "attn" in name: _UpperCamelCase : List[Any] = name.replace("attn" ,"attention.self" ) if "norm1" in name: _UpperCamelCase : Optional[int] = name.replace("norm1" ,"layernorm_before" ) if "norm2" in name: _UpperCamelCase : Optional[Any] = name.replace("norm2" ,"layernorm_after" ) if "mlp.fc1" in name: _UpperCamelCase : Dict = name.replace("mlp.fc1" ,"intermediate.dense" ) if "mlp.fc2" in name: _UpperCamelCase : str = name.replace("mlp.fc2" ,"output.dense" ) if "class_embed" in name: _UpperCamelCase : Union[str, Any] = name.replace("class_embed" ,"class_labels_classifier" ) if "bbox_embed" in name: _UpperCamelCase : str = name.replace("bbox_embed" ,"bbox_predictor" ) if "vit.norm" in name: _UpperCamelCase : List[str] = name.replace("vit.norm" ,"vit.layernorm" ) return name def lowercase__ ( lowercase_ ,lowercase_ ) -> dict: """simple docstring""" for key in orig_state_dict.copy().keys(): _UpperCamelCase : Any = orig_state_dict.pop(lowercase_ ) if "qkv" in key: _UpperCamelCase : Dict = key.split("." ) _UpperCamelCase : Optional[int] = int(key_split[2] ) _UpperCamelCase : List[Any] = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: _UpperCamelCase : Any = val[:dim, :] _UpperCamelCase : Tuple = val[ dim : dim * 2, : ] _UpperCamelCase : str = val[-dim:, :] else: _UpperCamelCase : str = val[:dim] _UpperCamelCase : Optional[Any] = val[dim : dim * 2] _UpperCamelCase : List[Any] = val[-dim:] else: _UpperCamelCase : List[str] = val return orig_state_dict def lowercase__ ( ) -> torch.Tensor: """simple docstring""" _UpperCamelCase : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" _UpperCamelCase : Optional[int] = Image.open(requests.get(lowercase_ ,stream=lowercase_ ).raw ) return im @torch.no_grad() def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ = False ) -> List[str]: """simple docstring""" _UpperCamelCase : Dict = get_yolos_config(lowercase_ ) # load original state_dict _UpperCamelCase : Tuple = torch.load(lowercase_ ,map_location="cpu" )["model"] # load 🤗 model _UpperCamelCase : Dict = YolosForObjectDetection(lowercase_ ) model.eval() _UpperCamelCase : List[str] = convert_state_dict(lowercase_ ,lowercase_ ) model.load_state_dict(lowercase_ ) # Check outputs on an image, prepared by YolosImageProcessor _UpperCamelCase : List[str] = 800 if yolos_name != "yolos_ti" else 512 _UpperCamelCase : Any = YolosImageProcessor(format="coco_detection" ,size=lowercase_ ) _UpperCamelCase : Union[str, Any] = image_processor(images=prepare_img() ,return_tensors="pt" ) _UpperCamelCase : Dict = model(**lowercase_ ) _UpperCamelCase : Dict = outputs.logits, outputs.pred_boxes _UpperCamelCase : int = None, None if yolos_name == "yolos_ti": _UpperCamelCase : List[Any] = torch.tensor( [[-39.5022, -11.9820, -17.6888], [-29.9574, -9.9769, -17.7691], [-42.3281, -20.7200, -30.6294]] ) _UpperCamelCase : str = torch.tensor( [[0.4021, 0.0836, 0.7979], [0.0184, 0.2609, 0.0364], [0.1781, 0.2004, 0.2095]] ) elif yolos_name == "yolos_s_200_pre": _UpperCamelCase : Union[str, Any] = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] ) _UpperCamelCase : Optional[Any] = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] ) elif yolos_name == "yolos_s_300_pre": _UpperCamelCase : Any = torch.tensor( [[-36.2220, -14.4385, -23.5457], [-35.6970, -14.7583, -21.3935], [-31.5939, -13.6042, -16.8049]] ) _UpperCamelCase : int = torch.tensor( [[0.7614, 0.2316, 0.4728], [0.7168, 0.4495, 0.3855], [0.4996, 0.1466, 0.9996]] ) elif yolos_name == "yolos_s_dWr": _UpperCamelCase : int = torch.tensor( [[-42.8668, -24.1049, -41.1690], [-34.7456, -14.1274, -24.9194], [-33.7898, -12.1946, -25.6495]] ) _UpperCamelCase : Optional[Any] = torch.tensor( [[0.5587, 0.2773, 0.0605], [0.5004, 0.3014, 0.9994], [0.4999, 0.1548, 0.9994]] ) elif yolos_name == "yolos_base": _UpperCamelCase : Dict = torch.tensor( [[-40.6064, -24.3084, -32.6447], [-55.1990, -30.7719, -35.5877], [-51.4311, -33.3507, -35.6462]] ) _UpperCamelCase : Optional[Any] = torch.tensor( [[0.5555, 0.2794, 0.0655], [0.9049, 0.2664, 0.1894], [0.9183, 0.1984, 0.1635]] ) else: raise ValueError(F'''Unknown yolos_name: {yolos_name}''' ) assert torch.allclose(logits[0, :3, :3] ,lowercase_ ,atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] ,lowercase_ ,atol=1e-4 ) Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) print(F'''Saving model {yolos_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase_ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase_ ) if push_to_hub: _UpperCamelCase : str = { "yolos_ti": "yolos-tiny", "yolos_s_200_pre": "yolos-small", "yolos_s_300_pre": "yolos-small-300", "yolos_s_dWr": "yolos-small-dwr", "yolos_base": "yolos-base", } print("Pushing to the hub..." ) _UpperCamelCase : List[str] = model_mapping[yolos_name] image_processor.push_to_hub(lowercase_ ,organization="hustvl" ) model.push_to_hub(lowercase_ ,organization="hustvl" ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--yolos_name", default="yolos_s_200_pre", type=str, help=( "Name of the YOLOS model you'd like to convert. Should be one of 'yolos_ti', 'yolos_s_200_pre'," " 'yolos_s_300_pre', 'yolos_s_dWr', 'yolos_base'." ), ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original state dict (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) lowerCamelCase__ = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
703
"""simple docstring""" lowerCamelCase__ = "\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCamelCase__ = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase__ = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
51
0
"""simple docstring""" from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Optional[Any] , __a : int , __a : int , __a : int , __a : Dict=0.0 , __a : Optional[int] = None , __a : str = "geglu" , __a : Optional[int] = None , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = True , __a : str = "layer_norm" , __a : bool = False , ) -> List[str]: super().__init__() _UpperCamelCase : Tuple = only_cross_attention _UpperCamelCase : List[Any] = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero" _UpperCamelCase : List[Any] = (num_embeds_ada_norm is not None) and norm_type == "ada_norm" if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F'''`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to''' F''' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.''' ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: _UpperCamelCase : Union[str, Any] = AdaLayerNorm(__a , __a ) elif self.use_ada_layer_norm_zero: _UpperCamelCase : Any = AdaLayerNormZero(__a , __a ) else: _UpperCamelCase : Optional[Any] = nn.LayerNorm(__a , elementwise_affine=__a ) _UpperCamelCase : Union[str, Any] = Attention( query_dim=__a , heads=__a , dim_head=__a , dropout=__a , bias=__a , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=__a , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. _UpperCamelCase : int = ( AdaLayerNorm(__a , __a ) if self.use_ada_layer_norm else nn.LayerNorm(__a , elementwise_affine=__a ) ) _UpperCamelCase : Optional[Any] = Attention( query_dim=__a , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=__a , dim_head=__a , dropout=__a , bias=__a , upcast_attention=__a , ) # is self-attn if encoder_hidden_states is none else: _UpperCamelCase : Optional[Any] = None _UpperCamelCase : Optional[int] = None # 3. Feed-forward _UpperCamelCase : List[Any] = nn.LayerNorm(__a , elementwise_affine=__a ) _UpperCamelCase : Any = FeedForward(__a , dropout=__a , activation_fn=__a , final_dropout=__a ) # let chunk size default to None _UpperCamelCase : List[str] = None _UpperCamelCase : Optional[Any] = 0 def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Optional[int] , __a : int ) -> Tuple: # Sets chunk feed-forward _UpperCamelCase : List[str] = chunk_size _UpperCamelCase : Tuple = dim def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : torch.FloatTensor , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.LongTensor] = None , __a : Dict[str, Any] = None , __a : Optional[torch.LongTensor] = None , ) -> Optional[Any]: # Notice that normalization is always applied before the real computation in the following blocks. # 1. Self-Attention if self.use_ada_layer_norm: _UpperCamelCase : int = self.norma(__a , __a ) elif self.use_ada_layer_norm_zero: _UpperCamelCase : Dict = self.norma( __a , __a , __a , hidden_dtype=hidden_states.dtype ) else: _UpperCamelCase : str = self.norma(__a ) _UpperCamelCase : Optional[int] = cross_attention_kwargs if cross_attention_kwargs is not None else {} _UpperCamelCase : Optional[int] = self.attna( __a , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=__a , **__a , ) if self.use_ada_layer_norm_zero: _UpperCamelCase : Optional[int] = gate_msa.unsqueeze(1 ) * attn_output _UpperCamelCase : Tuple = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: _UpperCamelCase : str = ( self.norma(__a , __a ) if self.use_ada_layer_norm else self.norma(__a ) ) _UpperCamelCase : Any = self.attna( __a , encoder_hidden_states=__a , attention_mask=__a , **__a , ) _UpperCamelCase : List[Any] = attn_output + hidden_states # 3. Feed-forward _UpperCamelCase : Optional[int] = self.norma(__a ) if self.use_ada_layer_norm_zero: _UpperCamelCase : str = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F'''`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.''' ) _UpperCamelCase : str = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size _UpperCamelCase : Dict = torch.cat( [self.ff(__a ) for hid_slice in norm_hidden_states.chunk(__a , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: _UpperCamelCase : Optional[int] = self.ff(__a ) if self.use_ada_layer_norm_zero: _UpperCamelCase : Any = gate_mlp.unsqueeze(1 ) * ff_output _UpperCamelCase : Tuple = ff_output + hidden_states return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] , __a : int , __a : Optional[int] = None , __a : int = 4 , __a : float = 0.0 , __a : str = "geglu" , __a : bool = False , ) -> str: super().__init__() _UpperCamelCase : List[Any] = int(dim * mult ) _UpperCamelCase : List[Any] = dim_out if dim_out is not None else dim if activation_fn == "gelu": _UpperCamelCase : Optional[Any] = GELU(__a , __a ) if activation_fn == "gelu-approximate": _UpperCamelCase : Dict = GELU(__a , __a , approximate="tanh" ) elif activation_fn == "geglu": _UpperCamelCase : Dict = GEGLU(__a , __a ) elif activation_fn == "geglu-approximate": _UpperCamelCase : List[str] = ApproximateGELU(__a , __a ) _UpperCamelCase : Union[str, Any] = nn.ModuleList([] ) # project in self.net.append(__a ) # project dropout self.net.append(nn.Dropout(__a ) ) # project out self.net.append(nn.Linear(__a , __a ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(__a ) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : Tuple ) -> List[str]: for module in self.net: _UpperCamelCase : int = module(__a ) return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : int , __a : int , __a : int , __a : str = "none" ) -> List[str]: super().__init__() _UpperCamelCase : Optional[Any] = nn.Linear(__a , __a ) _UpperCamelCase : List[str] = approximate def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : int ) -> Dict: if gate.device.type != "mps": return F.gelu(__a , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : int ) -> Tuple: _UpperCamelCase : int = self.proj(__a ) _UpperCamelCase : List[Any] = self.gelu(__a ) return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : List[str] , __a : int , __a : int ) -> str: super().__init__() _UpperCamelCase : Optional[Any] = nn.Linear(__a , dim_out * 2 ) def __SCREAMING_SNAKE_CASE ( self : Any , __a : Optional[Any] ) -> List[str]: if gate.device.type != "mps": return F.gelu(__a ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : Tuple ) -> Optional[int]: _UpperCamelCase : Optional[Any] = self.proj(__a ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(__a ) class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : int , __a : int , __a : int ) -> Any: super().__init__() _UpperCamelCase : str = nn.Linear(__a , __a ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : Any ) -> str: _UpperCamelCase : Dict = self.proj(__a ) return x * torch.sigmoid(1.7_02 * x ) class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : List[str] , __a : Tuple ) -> Union[str, Any]: super().__init__() _UpperCamelCase : Dict = nn.Embedding(__a , __a ) _UpperCamelCase : Optional[int] = nn.SiLU() _UpperCamelCase : Tuple = nn.Linear(__a , embedding_dim * 2 ) _UpperCamelCase : str = nn.LayerNorm(__a , elementwise_affine=__a ) def __SCREAMING_SNAKE_CASE ( self : Any , __a : str , __a : List[Any] ) -> List[Any]: _UpperCamelCase : Optional[int] = self.linear(self.silu(self.emb(__a ) ) ) _UpperCamelCase : Optional[Any] = torch.chunk(__a , 2 ) _UpperCamelCase : List[Any] = self.norm(__a ) * (1 + scale) + shift return x class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Tuple , __a : List[Any] , __a : Tuple ) -> List[Any]: super().__init__() _UpperCamelCase : Any = CombinedTimestepLabelEmbeddings(__a , __a ) _UpperCamelCase : List[str] = nn.SiLU() _UpperCamelCase : Optional[int] = nn.Linear(__a , 6 * embedding_dim , bias=__a ) _UpperCamelCase : List[str] = nn.LayerNorm(__a , elementwise_affine=__a , eps=1e-6 ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : str , __a : Optional[Any] , __a : Dict , __a : Tuple=None ) -> int: _UpperCamelCase : Tuple = self.linear(self.silu(self.emb(__a , __a , hidden_dtype=__a ) ) ) _UpperCamelCase : str = emb.chunk(6 , dim=1 ) _UpperCamelCase : Tuple = self.norm(__a ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : str , __a : int , __a : int , __a : int , __a : Optional[str] = None , __a : float = 1e-5 ) -> Dict: super().__init__() _UpperCamelCase : Optional[int] = num_groups _UpperCamelCase : List[str] = eps if act_fn is None: _UpperCamelCase : int = None else: _UpperCamelCase : List[str] = get_activation(__a ) _UpperCamelCase : List[Any] = nn.Linear(__a , out_dim * 2 ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Union[str, Any] , __a : Any ) -> Tuple: if self.act: _UpperCamelCase : Any = self.act(__a ) _UpperCamelCase : Optional[Any] = self.linear(__a ) _UpperCamelCase : Tuple = emb[:, :, None, None] _UpperCamelCase : Optional[int] = emb.chunk(2 , dim=1 ) _UpperCamelCase : Optional[int] = F.group_norm(__a , self.num_groups , eps=self.eps ) _UpperCamelCase : Optional[Any] = x * (1 + scale) + shift return x
704
"""simple docstring""" import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: _UpperCamelCase : Tuple = tempfile.mkdtemp() _UpperCamelCase : str = 5 # Realm tok _UpperCamelCase : Tuple = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "test", "question", "this", "is", "the", "first", "second", "third", "fourth", "fifth", "record", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _UpperCamelCase : Optional[int] = os.path.join(self.tmpdirname , "realm_tokenizer" ) os.makedirs(__a , exist_ok=__a ) _UpperCamelCase : Optional[Any] = os.path.join(__a , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) _UpperCamelCase : Optional[int] = os.path.join(self.tmpdirname , "realm_block_records" ) os.makedirs(__a , exist_ok=__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , "realm_tokenizer" ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: shutil.rmtree(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: _UpperCamelCase : Optional[Any] = RealmConfig(num_block_records=self.num_block_records ) return config def __SCREAMING_SNAKE_CASE ( self : int ) -> int: _UpperCamelCase : Any = Dataset.from_dict( { "id": ["0", "1"], "question": ["foo", "bar"], "answers": [["Foo", "Bar"], ["Bar"]], } ) return dataset def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: _UpperCamelCase : int = np.array( [ b"This is the first record", b"This is the second record", b"This is the third record", b"This is the fourth record", b"This is the fifth record", b"This is a longer longer longer record", ] , dtype=__a , ) return block_records def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: _UpperCamelCase : List[str] = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: _UpperCamelCase : Tuple = self.get_config() _UpperCamelCase : int = self.get_dummy_retriever() _UpperCamelCase : Tuple = retriever.tokenizer _UpperCamelCase : List[str] = np.array([0, 3] , dtype="long" ) _UpperCamelCase : Union[str, Any] = tokenizer(["Test question"] ).input_ids _UpperCamelCase : List[str] = tokenizer( ["the fourth"] , add_special_tokens=__a , return_token_type_ids=__a , return_attention_mask=__a , ).input_ids _UpperCamelCase : str = config.reader_seq_len _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : List[Any] = retriever( __a , __a , answer_ids=__a , max_length=__a , return_tensors="np" ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "first", "record", "[SEP]"] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "fourth", "record", "[SEP]"] , ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: _UpperCamelCase : Any = self.get_config() _UpperCamelCase : Dict = self.get_dummy_retriever() _UpperCamelCase : Dict = retriever.tokenizer _UpperCamelCase : List[Any] = np.array([0, 3, 5] , dtype="long" ) _UpperCamelCase : Optional[int] = tokenizer(["Test question"] ).input_ids _UpperCamelCase : str = tokenizer( ["the fourth", "longer longer"] , add_special_tokens=__a , return_token_type_ids=__a , return_attention_mask=__a , ).input_ids _UpperCamelCase : Union[str, Any] = config.reader_seq_len _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : Optional[Any] = retriever( __a , __a , answer_ids=__a , max_length=__a , return_tensors="np" ) self.assertEqual([False, True, True] , __a ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , __a ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , __a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: _UpperCamelCase : List[Any] = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) # Test local path _UpperCamelCase : int = retriever.from_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) self.assertEqual(retriever.block_records[0] , b"This is the first record" ) # Test mocked remote path with patch("transformers.models.realm.retrieval_realm.hf_hub_download" ) as mock_hf_hub_download: _UpperCamelCase : List[Any] = os.path.join( os.path.join(self.tmpdirname , "realm_block_records" ) , _REALM_BLOCK_RECORDS_FILENAME ) _UpperCamelCase : int = RealmRetriever.from_pretrained("google/realm-cc-news-pretrained-openqa" ) self.assertEqual(retriever.block_records[0] , b"This is the first record" )
51
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCamelCase__ = { "configuration_convnext": ["CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvNextConfig", "ConvNextOnnxConfig"] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["ConvNextFeatureExtractor"] lowerCamelCase__ = ["ConvNextImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "ConvNextForImageClassification", "ConvNextModel", "ConvNextPreTrainedModel", "ConvNextBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "TFConvNextForImageClassification", "TFConvNextModel", "TFConvNextPreTrainedModel", ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure)
705
"""simple docstring""" from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class __SCREAMING_SNAKE_CASE : '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = LEDConfig SCREAMING_SNAKE_CASE__ :str = {} SCREAMING_SNAKE_CASE__ :List[str] = "gelu" def __init__( self : List[Any] , __a : Union[str, Any] , __a : List[Any]=13 , __a : int=7 , __a : str=True , __a : Any=False , __a : str=99 , __a : str=32 , __a : Union[str, Any]=2 , __a : Optional[Any]=4 , __a : List[Any]=37 , __a : List[Any]=0.1 , __a : Tuple=0.1 , __a : Dict=20 , __a : str=2 , __a : Dict=1 , __a : Any=0 , __a : List[Any]=4 , ) -> List[Any]: _UpperCamelCase : Optional[Any] = parent _UpperCamelCase : List[str] = batch_size _UpperCamelCase : str = seq_length _UpperCamelCase : str = is_training _UpperCamelCase : Any = use_labels _UpperCamelCase : Any = vocab_size _UpperCamelCase : List[str] = hidden_size _UpperCamelCase : Optional[Any] = num_hidden_layers _UpperCamelCase : Dict = num_attention_heads _UpperCamelCase : Optional[Any] = intermediate_size _UpperCamelCase : int = hidden_dropout_prob _UpperCamelCase : Dict = attention_probs_dropout_prob _UpperCamelCase : str = max_position_embeddings _UpperCamelCase : int = eos_token_id _UpperCamelCase : Dict = pad_token_id _UpperCamelCase : Optional[Any] = bos_token_id _UpperCamelCase : str = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after _UpperCamelCase : List[str] = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests _UpperCamelCase : int = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __SCREAMING_SNAKE_CASE ( self : int ) -> str: _UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _UpperCamelCase : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _UpperCamelCase : Tuple = tf.concat([input_ids, eos_tensor] , axis=1 ) _UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase : List[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) _UpperCamelCase : Dict = prepare_led_inputs_dict(__a , __a , __a ) _UpperCamelCase : Union[str, Any] = tf.concat( [tf.zeros_like(__a )[:, :-1], tf.ones_like(__a )[:, -1:]] , axis=-1 , ) _UpperCamelCase : Union[str, Any] = global_attention_mask return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : List[Any] , __a : int ) -> Tuple: _UpperCamelCase : Tuple = TFLEDModel(config=__a ).get_decoder() _UpperCamelCase : Tuple = inputs_dict["input_ids"] _UpperCamelCase : int = input_ids[:1, :] _UpperCamelCase : List[str] = inputs_dict["attention_mask"][:1, :] _UpperCamelCase : List[Any] = 1 # first forward pass _UpperCamelCase : Any = model(__a , attention_mask=__a , use_cache=__a ) _UpperCamelCase, _UpperCamelCase : Union[str, Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _UpperCamelCase : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) _UpperCamelCase : Any = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _UpperCamelCase : List[str] = tf.concat([input_ids, next_tokens] , axis=-1 ) _UpperCamelCase : Union[str, Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _UpperCamelCase : Tuple = model(__a , attention_mask=__a )[0] _UpperCamelCase : int = model(__a , attention_mask=__a , past_key_values=__a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _UpperCamelCase : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _UpperCamelCase : List[str] = output_from_no_past[:, -3:, random_slice_idx] _UpperCamelCase : Optional[int] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__a , __a , rtol=1e-3 ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_=None ,lowercase_=None ,) -> Dict: """simple docstring""" if attention_mask is None: _UpperCamelCase : str = tf.cast(tf.math.not_equal(lowercase_ ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: _UpperCamelCase : str = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: _UpperCamelCase : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _UpperCamelCase : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :List[str] = (TFLEDForConditionalGeneration,) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :List[str] = ( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ :Tuple = True SCREAMING_SNAKE_CASE__ :str = False SCREAMING_SNAKE_CASE__ :Optional[Any] = False SCREAMING_SNAKE_CASE__ :int = False def __SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: _UpperCamelCase : int = TFLEDModelTester(self ) _UpperCamelCase : Any = ConfigTester(self , config_class=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: _UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__a ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase, _UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase : Optional[int] = tf.zeros_like(inputs_dict["attention_mask"] ) _UpperCamelCase : Union[str, Any] = 2 _UpperCamelCase : str = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) _UpperCamelCase : Dict = True _UpperCamelCase : str = self.model_tester.seq_length _UpperCamelCase : Union[str, Any] = self.model_tester.encoder_seq_length def check_decoder_attentions_output(__a : Optional[int] ): _UpperCamelCase : Optional[int] = outputs.decoder_attentions self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(__a : Optional[Any] ): _UpperCamelCase : Union[str, Any] = [t.numpy() for t in outputs.encoder_attentions] _UpperCamelCase : List[Any] = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: _UpperCamelCase : Dict = True _UpperCamelCase : Optional[Any] = False _UpperCamelCase : int = False _UpperCamelCase : Optional[int] = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) _UpperCamelCase : Any = len(__a ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) if self.is_encoder_decoder: _UpperCamelCase : Optional[Any] = model_class(__a ) _UpperCamelCase : List[Any] = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_decoder_attentions_output(__a ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _UpperCamelCase : int = True _UpperCamelCase : Tuple = model_class(__a ) _UpperCamelCase : str = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) # Check attention is always last and order is fine _UpperCamelCase : Any = True _UpperCamelCase : List[str] = True _UpperCamelCase : Tuple = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__a ) ) self.assertEqual(model.config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: pass def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: # TODO: Head-masking not yet implement pass def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" return tf.constant(lowercase_ ,dtype=tf.intaa ) lowerCamelCase__ = 1E-4 @slow @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: _UpperCamelCase : Any = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here _UpperCamelCase : int = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Tuple = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Optional[Any] = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Optional[int] = model(**__a )[0] _UpperCamelCase : Optional[int] = (1, 1024, 768) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : Tuple = tf.convert_to_tensor( [[2.30_50, 2.82_79, 0.65_31], [-1.84_57, -0.14_55, -3.56_61], [-1.01_86, 0.45_86, -2.20_43]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> str: _UpperCamelCase : Optional[int] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here _UpperCamelCase : Optional[int] = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : List[str] = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Optional[Any] = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Union[str, Any] = model(**__a )[0] _UpperCamelCase : int = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : Optional[int] = tf.convert_to_tensor( [[33.65_07, 6.45_72, 16.80_89], [5.87_39, -2.42_38, 11.29_02], [-3.21_39, -4.31_49, 4.27_83]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 , rtol=1e-3 )
51
0
"""simple docstring""" import argparse import math import os import torch from neural_compressor.utils.pytorch import load from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel def lowercase__ ( ) -> Dict: """simple docstring""" _UpperCamelCase : Tuple = argparse.ArgumentParser() parser.add_argument( "-m" ,"--pretrained_model_name_or_path" ,type=lowercase_ ,default=lowercase_ ,required=lowercase_ ,help="Path to pretrained model or model identifier from huggingface.co/models." ,) parser.add_argument( "-c" ,"--caption" ,type=lowercase_ ,default="robotic cat with wings" ,help="Text used to generate images." ,) parser.add_argument( "-n" ,"--images_num" ,type=lowercase_ ,default=4 ,help="How much images to generate." ,) parser.add_argument( "-s" ,"--seed" ,type=lowercase_ ,default=42 ,help="Seed for random process." ,) parser.add_argument( "-ci" ,"--cuda_id" ,type=lowercase_ ,default=0 ,help="cuda_id." ,) _UpperCamelCase : Union[str, Any] = parser.parse_args() return args def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" if not len(lowercase_ ) == rows * cols: raise ValueError("The specified number of rows and columns are not correct." ) _UpperCamelCase : int = imgs[0].size _UpperCamelCase : Optional[int] = Image.new("RGB" ,size=(cols * w, rows * h) ) _UpperCamelCase : List[str] = grid.size for i, img in enumerate(lowercase_ ): grid.paste(lowercase_ ,box=(i % cols * w, i // cols * h) ) return grid def lowercase__ ( lowercase_ ,lowercase_="robotic cat with wings" ,lowercase_=7.5 ,lowercase_=50 ,lowercase_=1 ,lowercase_=42 ,) -> Any: """simple docstring""" _UpperCamelCase : List[Any] = torch.Generator(pipeline.device ).manual_seed(lowercase_ ) _UpperCamelCase : Optional[Any] = pipeline( lowercase_ ,guidance_scale=lowercase_ ,num_inference_steps=lowercase_ ,generator=lowercase_ ,num_images_per_prompt=lowercase_ ,).images _UpperCamelCase : List[Any] = int(math.sqrt(lowercase_ ) ) _UpperCamelCase : Any = image_grid(lowercase_ ,rows=_rows ,cols=num_images_per_prompt // _rows ) return grid, images lowerCamelCase__ = parse_args() # Load models and create wrapper for stable diffusion lowerCamelCase__ = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer") lowerCamelCase__ = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder") lowerCamelCase__ = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae") lowerCamelCase__ = UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet") lowerCamelCase__ = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer ) lowerCamelCase__ = lambda images, clip_input: (images, False) if os.path.exists(os.path.join(args.pretrained_model_name_or_path, "best_model.pt")): lowerCamelCase__ = load(args.pretrained_model_name_or_path, model=unet) unet.eval() setattr(pipeline, "unet", unet) else: lowerCamelCase__ = unet.to(torch.device("cuda", args.cuda_id)) lowerCamelCase__ = pipeline.to(unet.device) lowerCamelCase__ , lowerCamelCase__ = generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed) grid.save(os.path.join(args.pretrained_model_name_or_path, "{}.png".format("_".join(args.caption.split())))) lowerCamelCase__ = os.path.join(args.pretrained_model_name_or_path, "_".join(args.caption.split())) os.makedirs(dirname, exist_ok=True) for idx, image in enumerate(images): image.save(os.path.join(dirname, "{}.png".format(idx + 1)))
706
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Union[str, Any] = RoCBertTokenizer SCREAMING_SNAKE_CASE__ :Dict = None SCREAMING_SNAKE_CASE__ :List[Any] = False SCREAMING_SNAKE_CASE__ :Union[str, Any] = True SCREAMING_SNAKE_CASE__ :Union[str, Any] = filter_non_english def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: super().setUp() _UpperCamelCase : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] _UpperCamelCase : List[str] = {} _UpperCamelCase : Tuple = {} for i, value in enumerate(__a ): _UpperCamelCase : List[str] = i _UpperCamelCase : Optional[Any] = i _UpperCamelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) _UpperCamelCase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(__a , __a , ensure_ascii=__a ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(__a , __a , ensure_ascii=__a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: _UpperCamelCase : Tuple = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : int = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(__a , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__a ) , [5, 6, 2, 5, 7, 8] ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: _UpperCamelCase : Dict = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: _UpperCamelCase : List[Any] = RoCBertBasicTokenizer(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 : Optional[Any] ) -> Tuple: _UpperCamelCase : Optional[Any] = RoCBertBasicTokenizer(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 : Dict ) -> str: _UpperCamelCase : Dict = RoCBertBasicTokenizer(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 : Union[str, Any] ) -> Union[str, Any]: _UpperCamelCase : List[str] = RoCBertBasicTokenizer(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[int]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase : Union[str, Any] = RoCBertBasicTokenizer(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 : Tuple ) -> List[Any]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(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 : Optional[Any] ) -> int: _UpperCamelCase : int = RoCBertBasicTokenizer(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 : List[str] ) -> Optional[Any]: _UpperCamelCase : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] _UpperCamelCase : Any = {} for i, token in enumerate(__a ): _UpperCamelCase : str = i _UpperCamelCase : Optional[int] = RoCBertWordpieceTokenizer(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 : Dict ) -> Optional[Any]: 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: 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 : Optional[int] ) -> Optional[int]: 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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = self.get_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]"]] ) if self.test_rust_tokenizer: _UpperCamelCase : Tuple = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__a ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Union[str, Any] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' _UpperCamelCase : Optional[Any] = tokenizer_r.encode_plus( __a , return_attention_mask=__a , return_token_type_ids=__a , return_offsets_mapping=__a , add_special_tokens=__a , ) _UpperCamelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(__a , "do_lower_case" ) else False _UpperCamelCase : Dict = ( [ ((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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = ["的", "人", "有"] _UpperCamelCase : int = "".join(__a ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = True _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : int = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : int = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : List[Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Union[str, Any] = 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 ) _UpperCamelCase : Any = False _UpperCamelCase : Dict = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Any = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Dict = tokenizer_p.convert_ids_to_tokens(__a ) # it is expected that only the first Chinese character is not preceded by "##". _UpperCamelCase : Any = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(__a ) ] self.assertListEqual(__a , __a ) self.assertListEqual(__a , __a ) @slow def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: _UpperCamelCase : Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : Optional[int] = tokenizer.encode("你好" , add_special_tokens=__a ) _UpperCamelCase : Dict = tokenizer.encode("你是谁" , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__a ) _UpperCamelCase : Tuple = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: _UpperCamelCase : Optional[Any] = self.get_tokenizers(do_lower_case=__a ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): _UpperCamelCase : int = "你好,你是谁" _UpperCamelCase : Any = tokenizer.tokenize(__a ) _UpperCamelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(__a ) _UpperCamelCase : List[str] = tokenizer.convert_tokens_to_shape_ids(__a ) _UpperCamelCase : Any = tokenizer.convert_tokens_to_pronunciation_ids(__a ) _UpperCamelCase : Optional[int] = tokenizer.prepare_for_model( __a , __a , __a , add_special_tokens=__a ) _UpperCamelCase : Tuple = tokenizer.encode_plus(__a , add_special_tokens=__a ) self.assertEqual(__a , __a )
51
0
"""simple docstring""" from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class __SCREAMING_SNAKE_CASE : '''simple docstring''' SCREAMING_SNAKE_CASE__ :int SCREAMING_SNAKE_CASE__ :TreeNode | None = None SCREAMING_SNAKE_CASE__ :TreeNode | None = None lowerCamelCase__ = namedtuple("CoinsDistribResult", "moves excess") def lowercase__ ( lowercase_ ) -> int: """simple docstring""" if root is None: return 0 # Validation def count_nodes(lowercase_ ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(lowercase_ ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(lowercase_ ) != count_coins(lowercase_ ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(lowercase_ ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 ,1 ) _UpperCamelCase : int = get_distrib(node.left ) _UpperCamelCase : List[str] = get_distrib(node.right ) _UpperCamelCase : Tuple = 1 - left_distrib_excess _UpperCamelCase : Union[str, Any] = 1 - right_distrib_excess _UpperCamelCase : List[Any] = ( left_distrib_moves + right_distrib_moves + abs(lowercase_ ) + abs(lowercase_ ) ) _UpperCamelCase : Optional[int] = node.data - coins_to_left - coins_to_right return CoinsDistribResult(lowercase_ ,lowercase_ ) return get_distrib(lowercase_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
707
"""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 lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "hustvl/yolos-small": "https://huggingface.co/hustvl/yolos-small/resolve/main/config.json", # See all YOLOS models at https://huggingface.co/models?filter=yolos } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = "yolos" def __init__( self : Dict , __a : Optional[Any]=768 , __a : List[Any]=12 , __a : Any=12 , __a : List[Any]=3072 , __a : Optional[int]="gelu" , __a : Dict=0.0 , __a : Optional[Any]=0.0 , __a : Any=0.02 , __a : Optional[int]=1e-1_2 , __a : List[Any]=[512, 864] , __a : List[str]=16 , __a : str=3 , __a : Optional[Any]=True , __a : Optional[Any]=100 , __a : List[str]=True , __a : Any=False , __a : List[str]=1 , __a : str=5 , __a : Optional[Any]=2 , __a : Tuple=5 , __a : Any=2 , __a : Union[str, Any]=0.1 , **__a : List[str] , ) -> List[str]: super().__init__(**__a ) _UpperCamelCase : Dict = hidden_size _UpperCamelCase : Any = num_hidden_layers _UpperCamelCase : str = num_attention_heads _UpperCamelCase : Dict = intermediate_size _UpperCamelCase : List[str] = hidden_act _UpperCamelCase : List[str] = hidden_dropout_prob _UpperCamelCase : str = attention_probs_dropout_prob _UpperCamelCase : Tuple = initializer_range _UpperCamelCase : List[str] = layer_norm_eps _UpperCamelCase : Tuple = image_size _UpperCamelCase : Tuple = patch_size _UpperCamelCase : Dict = num_channels _UpperCamelCase : Any = qkv_bias _UpperCamelCase : str = num_detection_tokens _UpperCamelCase : str = use_mid_position_embeddings _UpperCamelCase : List[str] = auxiliary_loss # Hungarian matcher _UpperCamelCase : List[Any] = class_cost _UpperCamelCase : int = bbox_cost _UpperCamelCase : Optional[int] = giou_cost # Loss coefficients _UpperCamelCase : List[Any] = bbox_loss_coefficient _UpperCamelCase : str = giou_loss_coefficient _UpperCamelCase : Dict = eos_coefficient class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[str] = version.parse("1.11" ) @property def __SCREAMING_SNAKE_CASE ( self : str ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> float: return 1e-4 @property def __SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return 12
51
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Dict = "megatron-bert" def __init__( self : int , __a : List[str]=2_9056 , __a : Dict=1024 , __a : Optional[Any]=24 , __a : str=16 , __a : List[Any]=4096 , __a : str="gelu" , __a : Optional[Any]=0.1 , __a : Any=0.1 , __a : Optional[int]=512 , __a : int=2 , __a : Tuple=0.02 , __a : str=1e-1_2 , __a : Optional[int]=0 , __a : Optional[Any]="absolute" , __a : Any=True , **__a : List[Any] , ) -> Tuple: super().__init__(pad_token_id=__a , **__a ) _UpperCamelCase : Any = vocab_size _UpperCamelCase : int = hidden_size _UpperCamelCase : int = num_hidden_layers _UpperCamelCase : List[Any] = num_attention_heads _UpperCamelCase : List[str] = hidden_act _UpperCamelCase : Union[str, Any] = intermediate_size _UpperCamelCase : List[Any] = hidden_dropout_prob _UpperCamelCase : Tuple = attention_probs_dropout_prob _UpperCamelCase : Tuple = max_position_embeddings _UpperCamelCase : Optional[Any] = type_vocab_size _UpperCamelCase : Dict = initializer_range _UpperCamelCase : Union[str, Any] = layer_norm_eps _UpperCamelCase : Any = position_embedding_type _UpperCamelCase : Optional[int] = use_cache
708
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path lowerCamelCase__ = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) lowerCamelCase__ = [ord(letter) for letter in string.ascii_lowercase] lowerCamelCase__ = {ord(char) for char in VALID_CHARS} lowerCamelCase__ = ["the", "be", "to", "of", "and", "in", "that", "have"] def lowercase__ ( lowercase_ ,lowercase_ ) -> str | None: """simple docstring""" _UpperCamelCase : str = "" _UpperCamelCase : int _UpperCamelCase : int _UpperCamelCase : int for keychar, cipherchar in zip(cycle(lowercase_ ) ,lowercase_ ): _UpperCamelCase : Dict = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(lowercase_ ) return decoded def lowercase__ ( lowercase_ ) -> list[str]: """simple docstring""" _UpperCamelCase : list[str] = [] for key in product(lowercase_ ,repeat=3 ): _UpperCamelCase : int = try_key(lowercase_ ,lowercase_ ) if encoded is not None: possibles.append(lowercase_ ) return possibles def lowercase__ ( lowercase_ ,lowercase_ ) -> list[str]: """simple docstring""" return [possible for possible in possibles if common_word in possible.lower()] def lowercase__ ( lowercase_ = "p059_cipher.txt" ) -> int: """simple docstring""" _UpperCamelCase : list[int] _UpperCamelCase : list[str] _UpperCamelCase : str _UpperCamelCase : str _UpperCamelCase : str = Path(lowercase_ ).parent.joinpath(lowercase_ ).read_text(encoding="utf-8" ) _UpperCamelCase : Optional[Any] = [int(lowercase_ ) for number in data.strip().split("," )] _UpperCamelCase : List[str] = filter_valid_chars(lowercase_ ) for common_word in COMMON_WORDS: _UpperCamelCase : Union[str, Any] = filter_common_word(lowercase_ ,lowercase_ ) if len(lowercase_ ) == 1: break _UpperCamelCase : Union[str, Any] = possibles[0] return sum(ord(lowercase_ ) for char in decoded_text ) if __name__ == "__main__": print(f"""{solution() = }""")
51
0
def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_=None ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Tuple = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: _UpperCamelCase : Any = True, True _UpperCamelCase : Optional[int] = dfs(lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) return path def lowercase__ ( lowercase_ ,lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Tuple = 0 _UpperCamelCase : Tuple = -1 for i in range(lowercase_ ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 _UpperCamelCase : str = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def lowercase__ ( lowercase_ ,lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : List[str] = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] _UpperCamelCase : Any = check_circuit_or_path(lowercase_ ,lowercase_ ) if check == 3: print("graph is not Eulerian" ) print("no path" ) return _UpperCamelCase : int = 1 if check == 2: _UpperCamelCase : Optional[Any] = odd_node print("graph has a Euler path" ) if check == 1: print("graph has a Euler cycle" ) _UpperCamelCase : Any = dfs(lowercase_ ,lowercase_ ,lowercase_ ) print(lowercase_ ) def lowercase__ ( ) -> Dict: """simple docstring""" _UpperCamelCase : Union[str, Any] = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} _UpperCamelCase : Any = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} _UpperCamelCase : List[Any] = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} _UpperCamelCase : Optional[int] = {1: [2, 3], 2: [1, 3], 3: [1, 2]} _UpperCamelCase : Tuple = { 1: [], 2: [] # all degree is zero } _UpperCamelCase : Optional[int] = 10 check_euler(lowercase_ ,lowercase_ ) check_euler(lowercase_ ,lowercase_ ) check_euler(lowercase_ ,lowercase_ ) check_euler(lowercase_ ,lowercase_ ) check_euler(lowercase_ ,lowercase_ ) if __name__ == "__main__": main()
709
"""simple docstring""" def lowercase__ ( lowercase_ ,lowercase_ ) -> None: """simple docstring""" _UpperCamelCase : List[Any] = len(lowercase_ ) print("The following activities are selected:" ) # The first activity is always selected _UpperCamelCase : List[Any] = 0 print(lowercase_ ,end="," ) # Consider rest of the activities for j in range(lowercase_ ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(lowercase_ ,end="," ) _UpperCamelCase : Optional[Any] = j if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase__ = [1, 3, 0, 5, 8, 5] lowerCamelCase__ = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
51
0
"""simple docstring""" import random from .binary_exp_mod import bin_exp_mod def lowercase__ ( lowercase_ ,lowercase_=1_000 ) -> Union[str, Any]: """simple docstring""" if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd _UpperCamelCase : str = n - 1 _UpperCamelCase : Optional[int] = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) _UpperCamelCase : List[str] = 0 while count < prec: _UpperCamelCase : Union[str, Any] = random.randint(2 ,n - 1 ) _UpperCamelCase : Optional[int] = bin_exp_mod(lowercase_ ,lowercase_ ,lowercase_ ) if b != 1: _UpperCamelCase : Optional[int] = True for _ in range(lowercase_ ): if b == n - 1: _UpperCamelCase : Tuple = False break _UpperCamelCase : List[Any] = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": lowerCamelCase__ = abs(int(input("Enter bound : ").strip())) print("Here's the list of primes:") print(", ".join(str(i) for i in range(n + 1) if is_prime_big(i)))
710
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :torch.FloatTensor class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : Dict=3 , __a : Any=3 , __a : Union[str, Any]=("DownEncoderBlock2D",) , __a : Optional[int]=(64,) , __a : int=2 , __a : Tuple=32 , __a : int="silu" , __a : str=True , ) -> Dict: super().__init__() _UpperCamelCase : List[str] = layers_per_block _UpperCamelCase : Dict = torch.nn.Convad( __a , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) _UpperCamelCase : int = None _UpperCamelCase : Any = nn.ModuleList([] ) # down _UpperCamelCase : List[str] = block_out_channels[0] for i, down_block_type in enumerate(__a ): _UpperCamelCase : Tuple = output_channel _UpperCamelCase : int = block_out_channels[i] _UpperCamelCase : int = i == len(__a ) - 1 _UpperCamelCase : Dict = get_down_block( __a , num_layers=self.layers_per_block , in_channels=__a , out_channels=__a , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=__a , resnet_groups=__a , attention_head_dim=__a , temb_channels=__a , ) self.down_blocks.append(__a ) # mid _UpperCamelCase : Union[str, Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__a , output_scale_factor=1 , resnet_time_scale_shift="default" , attention_head_dim=block_out_channels[-1] , resnet_groups=__a , temb_channels=__a , ) # out _UpperCamelCase : Any = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__a , eps=1e-6 ) _UpperCamelCase : Any = nn.SiLU() _UpperCamelCase : Union[str, Any] = 2 * out_channels if double_z else out_channels _UpperCamelCase : Tuple = nn.Convad(block_out_channels[-1] , __a , 3 , padding=1 ) _UpperCamelCase : Optional[int] = False def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Dict ) -> List[str]: _UpperCamelCase : int = x _UpperCamelCase : Optional[int] = self.conv_in(__a ) if self.training and self.gradient_checkpointing: def create_custom_forward(__a : Tuple ): def custom_forward(*__a : Any ): return module(*__a ) return custom_forward # down if is_torch_version(">=" , "1.11.0" ): for down_block in self.down_blocks: _UpperCamelCase : Optional[int] = torch.utils.checkpoint.checkpoint( create_custom_forward(__a ) , __a , use_reentrant=__a ) # middle _UpperCamelCase : Tuple = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , use_reentrant=__a ) else: for down_block in self.down_blocks: _UpperCamelCase : Any = torch.utils.checkpoint.checkpoint(create_custom_forward(__a ) , __a ) # middle _UpperCamelCase : int = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __a ) else: # down for down_block in self.down_blocks: _UpperCamelCase : int = down_block(__a ) # middle _UpperCamelCase : int = self.mid_block(__a ) # post-process _UpperCamelCase : Any = self.conv_norm_out(__a ) _UpperCamelCase : Any = self.conv_act(__a ) _UpperCamelCase : Optional[Any] = self.conv_out(__a ) return sample class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : int=3 , __a : Any=3 , __a : str=("UpDecoderBlock2D",) , __a : Optional[int]=(64,) , __a : int=2 , __a : Optional[int]=32 , __a : Tuple="silu" , __a : Union[str, Any]="group" , ) -> str: super().__init__() _UpperCamelCase : List[Any] = layers_per_block _UpperCamelCase : Tuple = nn.Convad( __a , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) _UpperCamelCase : List[str] = None _UpperCamelCase : Dict = nn.ModuleList([] ) _UpperCamelCase : List[Any] = in_channels if norm_type == "spatial" else None # mid _UpperCamelCase : Optional[Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__a , output_scale_factor=1 , resnet_time_scale_shift="default" if norm_type == "group" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__a , temb_channels=__a , ) # up _UpperCamelCase : List[str] = list(reversed(__a ) ) _UpperCamelCase : int = reversed_block_out_channels[0] for i, up_block_type in enumerate(__a ): _UpperCamelCase : int = output_channel _UpperCamelCase : Union[str, Any] = reversed_block_out_channels[i] _UpperCamelCase : Optional[Any] = i == len(__a ) - 1 _UpperCamelCase : Union[str, Any] = get_up_block( __a , num_layers=self.layers_per_block + 1 , in_channels=__a , out_channels=__a , prev_output_channel=__a , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=__a , resnet_groups=__a , attention_head_dim=__a , temb_channels=__a , resnet_time_scale_shift=__a , ) self.up_blocks.append(__a ) _UpperCamelCase : Optional[Any] = output_channel # out if norm_type == "spatial": _UpperCamelCase : Optional[int] = SpatialNorm(block_out_channels[0] , __a ) else: _UpperCamelCase : Optional[int] = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__a , eps=1e-6 ) _UpperCamelCase : str = nn.SiLU() _UpperCamelCase : str = nn.Convad(block_out_channels[0] , __a , 3 , padding=1 ) _UpperCamelCase : Dict = False def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : List[Any] , __a : Union[str, Any]=None ) -> Tuple: _UpperCamelCase : List[str] = z _UpperCamelCase : Dict = self.conv_in(__a ) _UpperCamelCase : Any = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__a : Any ): def custom_forward(*__a : Tuple ): return module(*__a ) return custom_forward if is_torch_version(">=" , "1.11.0" ): # middle _UpperCamelCase : str = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , __a , use_reentrant=__a ) _UpperCamelCase : Optional[int] = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(__a ) , __a , __a , use_reentrant=__a ) else: # middle _UpperCamelCase : Optional[int] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __a , __a ) _UpperCamelCase : Union[str, Any] = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : str = torch.utils.checkpoint.checkpoint(create_custom_forward(__a ) , __a , __a ) else: # middle _UpperCamelCase : str = self.mid_block(__a , __a ) _UpperCamelCase : int = sample.to(__a ) # up for up_block in self.up_blocks: _UpperCamelCase : Any = up_block(__a , __a ) # post-process if latent_embeds is None: _UpperCamelCase : List[str] = self.conv_norm_out(__a ) else: _UpperCamelCase : Optional[int] = self.conv_norm_out(__a , __a ) _UpperCamelCase : Tuple = self.conv_act(__a ) _UpperCamelCase : List[Any] = self.conv_out(__a ) return sample class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict , __a : Tuple , __a : List[str] , __a : List[str] , __a : str=None , __a : Optional[int]="random" , __a : Any=False , __a : Optional[Any]=True ) -> List[Any]: super().__init__() _UpperCamelCase : Tuple = n_e _UpperCamelCase : Tuple = vq_embed_dim _UpperCamelCase : Union[str, Any] = beta _UpperCamelCase : str = legacy _UpperCamelCase : Dict = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) _UpperCamelCase : Any = remap if self.remap is not None: self.register_buffer("used" , torch.tensor(np.load(self.remap ) ) ) _UpperCamelCase : Dict = self.used.shape[0] _UpperCamelCase : Optional[int] = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": _UpperCamelCase : Optional[int] = self.re_embed _UpperCamelCase : Any = self.re_embed + 1 print( F'''Remapping {self.n_e} indices to {self.re_embed} indices. ''' F'''Using {self.unknown_index} for unknown indices.''' ) else: _UpperCamelCase : Union[str, Any] = n_e _UpperCamelCase : List[str] = sane_index_shape def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : Optional[Any] ) -> Optional[int]: _UpperCamelCase : str = inds.shape assert len(__a ) > 1 _UpperCamelCase : Union[str, Any] = inds.reshape(ishape[0] , -1 ) _UpperCamelCase : Optional[Any] = self.used.to(__a ) _UpperCamelCase : List[str] = (inds[:, :, None] == used[None, None, ...]).long() _UpperCamelCase : Optional[Any] = match.argmax(-1 ) _UpperCamelCase : Any = match.sum(2 ) < 1 if self.unknown_index == "random": _UpperCamelCase : Optional[int] = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: _UpperCamelCase : Dict = self.unknown_index return new.reshape(__a ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : Optional[int] ) -> Optional[int]: _UpperCamelCase : int = inds.shape assert len(__a ) > 1 _UpperCamelCase : List[Any] = inds.reshape(ishape[0] , -1 ) _UpperCamelCase : Optional[int] = self.used.to(__a ) if self.re_embed > self.used.shape[0]: # extra token _UpperCamelCase : int = 0 # simply set to zero _UpperCamelCase : Union[str, Any] = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __a ) return back.reshape(__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : str ) -> Optional[int]: # reshape z -> (batch, height, width, channel) and flatten _UpperCamelCase : List[str] = z.permute(0 , 2 , 3 , 1 ).contiguous() _UpperCamelCase : int = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z _UpperCamelCase : Optional[int] = torch.argmin(torch.cdist(__a , self.embedding.weight ) , dim=1 ) _UpperCamelCase : int = self.embedding(__a ).view(z.shape ) _UpperCamelCase : str = None _UpperCamelCase : Any = None # compute loss for embedding if not self.legacy: _UpperCamelCase : List[str] = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: _UpperCamelCase : str = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients _UpperCamelCase : List[str] = z + (z_q - z).detach() # reshape back to match original input shape _UpperCamelCase : Optional[Any] = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: _UpperCamelCase : Tuple = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis _UpperCamelCase : Dict = self.remap_to_used(__a ) _UpperCamelCase : List[str] = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: _UpperCamelCase : str = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : List[str] , __a : str ) -> Any: # shape specifying (batch, height, width, channel) if self.remap is not None: _UpperCamelCase : str = indices.reshape(shape[0] , -1 ) # add batch axis _UpperCamelCase : str = self.unmap_to_all(__a ) _UpperCamelCase : int = indices.reshape(-1 ) # flatten again # get quantized latent vectors _UpperCamelCase : Optional[int] = self.embedding(__a ) if shape is not None: _UpperCamelCase : Tuple = z_q.view(__a ) # reshape back to match original input shape _UpperCamelCase : Tuple = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __init__( self : Optional[int] , __a : List[str] , __a : Optional[Any]=False ) -> int: _UpperCamelCase : Dict = parameters _UpperCamelCase, _UpperCamelCase : str = torch.chunk(__a , 2 , dim=1 ) _UpperCamelCase : Tuple = torch.clamp(self.logvar , -30.0 , 20.0 ) _UpperCamelCase : Union[str, Any] = deterministic _UpperCamelCase : Dict = torch.exp(0.5 * self.logvar ) _UpperCamelCase : Any = torch.exp(self.logvar ) if self.deterministic: _UpperCamelCase : List[Any] = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : Optional[torch.Generator] = None ) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype _UpperCamelCase : List[Any] = randn_tensor( self.mean.shape , generator=__a , device=self.parameters.device , dtype=self.parameters.dtype ) _UpperCamelCase : List[Any] = self.mean + self.std * sample return x def __SCREAMING_SNAKE_CASE ( self : Any , __a : List[str]=None ) -> List[Any]: if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def __SCREAMING_SNAKE_CASE ( self : str , __a : Tuple , __a : List[str]=[1, 2, 3] ) -> int: if self.deterministic: return torch.Tensor([0.0] ) _UpperCamelCase : List[str] = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: return self.mean
51
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL lowerCamelCase__ = logging.get_logger(__name__) def lowercase__ ( lowercase_ ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(lowercase_ ,(list, tuple) ) and isinstance(videos[0] ,(list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(lowercase_ ,(list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(lowercase_ ): return [[videos]] raise ValueError(F'''Could not make batched video from {videos}''' ) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): SCREAMING_SNAKE_CASE__ :str = ["pixel_values"] def __init__( self : List[str] , __a : bool = True , __a : Dict[str, int] = None , __a : PILImageResampling = PILImageResampling.BILINEAR , __a : bool = True , __a : Dict[str, int] = None , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : bool = True , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[float, List[float]]] = None , **__a : Tuple , ) -> None: super().__init__(**__a ) _UpperCamelCase : List[Any] = size if size is not None else {"shortest_edge": 256} _UpperCamelCase : Any = get_size_dict(__a , default_to_square=__a ) _UpperCamelCase : List[Any] = crop_size if crop_size is not None else {"height": 224, "width": 224} _UpperCamelCase : List[str] = get_size_dict(__a , param_name="crop_size" ) _UpperCamelCase : Optional[int] = do_resize _UpperCamelCase : Any = size _UpperCamelCase : Tuple = do_center_crop _UpperCamelCase : str = crop_size _UpperCamelCase : List[Any] = resample _UpperCamelCase : Any = do_rescale _UpperCamelCase : int = rescale_factor _UpperCamelCase : str = offset _UpperCamelCase : Union[str, Any] = do_normalize _UpperCamelCase : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _UpperCamelCase : Any = image_std if image_std is not None else IMAGENET_STANDARD_STD def __SCREAMING_SNAKE_CASE ( self : int , __a : np.ndarray , __a : Dict[str, int] , __a : PILImageResampling = PILImageResampling.BILINEAR , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Any , ) -> np.ndarray: _UpperCamelCase : Tuple = get_size_dict(__a , default_to_square=__a ) if "shortest_edge" in size: _UpperCamelCase : Any = get_resize_output_image_size(__a , size["shortest_edge"] , default_to_square=__a ) elif "height" in size and "width" in size: _UpperCamelCase : Union[str, Any] = (size["height"], size["width"]) else: raise ValueError(F'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' ) return resize(__a , size=__a , resample=__a , data_format=__a , **__a ) def __SCREAMING_SNAKE_CASE ( self : int , __a : np.ndarray , __a : Dict[str, int] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : List[str] , ) -> np.ndarray: _UpperCamelCase : List[Any] = get_size_dict(__a ) if "height" not in size or "width" not in size: raise ValueError(F'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}''' ) return center_crop(__a , size=(size["height"], size["width"]) , data_format=__a , **__a ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : np.ndarray , __a : Union[int, float] , __a : bool = True , __a : Optional[Union[str, ChannelDimension]] = None , **__a : int , ) -> Optional[Any]: _UpperCamelCase : Any = image.astype(np.floataa ) if offset: _UpperCamelCase : Any = image - (scale / 2) return rescale(__a , scale=__a , data_format=__a , **__a ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : np.ndarray , __a : Union[float, List[float]] , __a : Union[float, List[float]] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : int , ) -> np.ndarray: return normalize(__a , mean=__a , std=__a , data_format=__a , **__a ) def __SCREAMING_SNAKE_CASE ( self : Dict , __a : ImageInput , __a : bool = None , __a : Dict[str, int] = None , __a : PILImageResampling = None , __a : bool = None , __a : Dict[str, int] = None , __a : bool = None , __a : float = None , __a : bool = None , __a : bool = None , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[float, List[float]]] = None , __a : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray: if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) if offset and not do_rescale: raise ValueError("For offset, do_rescale must also be set to True." ) # All transformations expect numpy arrays. _UpperCamelCase : List[str] = to_numpy_array(__a ) if do_resize: _UpperCamelCase : Tuple = self.resize(image=__a , size=__a , resample=__a ) if do_center_crop: _UpperCamelCase : Tuple = self.center_crop(__a , size=__a ) if do_rescale: _UpperCamelCase : Dict = self.rescale(image=__a , scale=__a , offset=__a ) if do_normalize: _UpperCamelCase : Optional[Any] = self.normalize(image=__a , mean=__a , std=__a ) _UpperCamelCase : Tuple = to_channel_dimension_format(__a , __a ) return image def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : ImageInput , __a : bool = None , __a : Dict[str, int] = None , __a : PILImageResampling = None , __a : bool = None , __a : Dict[str, int] = None , __a : bool = None , __a : float = None , __a : bool = None , __a : bool = None , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[str, TensorType]] = None , __a : ChannelDimension = ChannelDimension.FIRST , **__a : Optional[Any] , ) -> PIL.Image.Image: _UpperCamelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize _UpperCamelCase : Optional[int] = resample if resample is not None else self.resample _UpperCamelCase : int = do_center_crop if do_center_crop is not None else self.do_center_crop _UpperCamelCase : List[str] = do_rescale if do_rescale is not None else self.do_rescale _UpperCamelCase : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCamelCase : Dict = offset if offset is not None else self.offset _UpperCamelCase : Optional[Any] = do_normalize if do_normalize is not None else self.do_normalize _UpperCamelCase : int = image_mean if image_mean is not None else self.image_mean _UpperCamelCase : Union[str, Any] = image_std if image_std is not None else self.image_std _UpperCamelCase : int = size if size is not None else self.size _UpperCamelCase : int = get_size_dict(__a , default_to_square=__a ) _UpperCamelCase : Any = crop_size if crop_size is not None else self.crop_size _UpperCamelCase : List[Any] = get_size_dict(__a , param_name="crop_size" ) if not valid_images(__a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) _UpperCamelCase : List[str] = make_batched(__a ) _UpperCamelCase : int = [ [ self._preprocess_image( image=__a , do_resize=__a , size=__a , resample=__a , do_center_crop=__a , crop_size=__a , do_rescale=__a , rescale_factor=__a , offset=__a , do_normalize=__a , image_mean=__a , image_std=__a , data_format=__a , ) for img in video ] for video in videos ] _UpperCamelCase : Any = {"pixel_values": videos} return BatchFeature(data=__a , tensor_type=__a )
711
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''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 __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict[str, str]: return {self.text_column: "text", self.summary_column: "summary"}
51
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase__ = {"configuration_xlnet": ["XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["XLNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["XLNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "XLNET_PRETRAINED_MODEL_ARCHIVE_LIST", "XLNetForMultipleChoice", "XLNetForQuestionAnswering", "XLNetForQuestionAnsweringSimple", "XLNetForSequenceClassification", "XLNetForTokenClassification", "XLNetLMHeadModel", "XLNetModel", "XLNetPreTrainedModel", "load_tf_weights_in_xlnet", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLNetForMultipleChoice", "TFXLNetForQuestionAnsweringSimple", "TFXLNetForSequenceClassification", "TFXLNetForTokenClassification", "TFXLNetLMHeadModel", "TFXLNetMainLayer", "TFXLNetModel", "TFXLNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
712
"""simple docstring""" def lowercase__ ( lowercase_ ) -> set: """simple docstring""" _UpperCamelCase : Union[str, Any] = set() # edges = list of graph's edges _UpperCamelCase : Union[str, Any] = get_edges(lowercase_ ) # 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: _UpperCamelCase, _UpperCamelCase : str = edges.pop() chosen_vertices.add(lowercase_ ) chosen_vertices.add(lowercase_ ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(lowercase_ ) return chosen_vertices def lowercase__ ( lowercase_ ) -> set: """simple docstring""" _UpperCamelCase : List[str] = 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)}")
51
0
"""simple docstring""" from __future__ import annotations def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> float: """simple docstring""" if days_between_payments <= 0: raise ValueError("days_between_payments must be > 0" ) if daily_interest_rate < 0: raise ValueError("daily_interest_rate must be >= 0" ) if principal <= 0: raise ValueError("principal must be > 0" ) return principal * daily_interest_rate * days_between_payments def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,) -> float: """simple docstring""" if number_of_compounding_periods <= 0: raise ValueError("number_of_compounding_periods must be > 0" ) if nominal_annual_interest_rate_percentage < 0: raise ValueError("nominal_annual_interest_rate_percentage must be >= 0" ) if principal <= 0: raise ValueError("principal must be > 0" ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,) -> float: """simple docstring""" if number_of_years <= 0: raise ValueError("number_of_years must be > 0" ) if nominal_annual_percentage_rate < 0: raise ValueError("nominal_annual_percentage_rate must be >= 0" ) if principal <= 0: raise ValueError("principal must be > 0" ) return compound_interest( lowercase_ ,nominal_annual_percentage_rate / 365 ,number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
713
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCamelCase__ = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["OwlViTFeatureExtractor"] lowerCamelCase__ = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
51
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "microsoft/table-transformer-detection": ( "https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json" ), } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :str = "table-transformer" SCREAMING_SNAKE_CASE__ :Optional[int] = ["past_key_values"] SCREAMING_SNAKE_CASE__ :Union[str, Any] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : Optional[int] , __a : Dict=True , __a : int=None , __a : Optional[Any]=3 , __a : Any=100 , __a : List[str]=6 , __a : Optional[int]=2048 , __a : List[Any]=8 , __a : str=6 , __a : Union[str, Any]=2048 , __a : Tuple=8 , __a : Dict=0.0 , __a : Any=0.0 , __a : int=True , __a : int="relu" , __a : Tuple=256 , __a : List[Any]=0.1 , __a : Optional[int]=0.0 , __a : Union[str, Any]=0.0 , __a : List[str]=0.02 , __a : Dict=1.0 , __a : Union[str, Any]=False , __a : Optional[Any]="sine" , __a : List[Any]="resnet50" , __a : List[Any]=True , __a : List[str]=False , __a : Union[str, Any]=1 , __a : str=5 , __a : str=2 , __a : Optional[Any]=1 , __a : Tuple=1 , __a : Dict=5 , __a : Tuple=2 , __a : Any=0.1 , **__a : str , ) -> List[str]: 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 : Dict = CONFIG_MAPPING["resnet"](out_features=["stage4"] ) elif isinstance(__a , __a ): _UpperCamelCase : List[Any] = backbone_config.get("model_type" ) _UpperCamelCase : int = CONFIG_MAPPING[backbone_model_type] _UpperCamelCase : str = config_class.from_dict(__a ) # set timm attributes to None _UpperCamelCase : Union[str, Any] = None, None, None _UpperCamelCase : List[str] = use_timm_backbone _UpperCamelCase : Optional[int] = backbone_config _UpperCamelCase : Union[str, Any] = num_channels _UpperCamelCase : List[str] = num_queries _UpperCamelCase : Union[str, Any] = d_model _UpperCamelCase : Union[str, Any] = encoder_ffn_dim _UpperCamelCase : Tuple = encoder_layers _UpperCamelCase : str = encoder_attention_heads _UpperCamelCase : Dict = decoder_ffn_dim _UpperCamelCase : str = decoder_layers _UpperCamelCase : Optional[Any] = decoder_attention_heads _UpperCamelCase : Any = dropout _UpperCamelCase : Dict = attention_dropout _UpperCamelCase : Any = activation_dropout _UpperCamelCase : Dict = activation_function _UpperCamelCase : Optional[Any] = init_std _UpperCamelCase : int = init_xavier_std _UpperCamelCase : int = encoder_layerdrop _UpperCamelCase : Optional[int] = decoder_layerdrop _UpperCamelCase : Tuple = encoder_layers _UpperCamelCase : str = auxiliary_loss _UpperCamelCase : str = position_embedding_type _UpperCamelCase : Optional[Any] = backbone _UpperCamelCase : Dict = use_pretrained_backbone _UpperCamelCase : List[Any] = dilation # Hungarian matcher _UpperCamelCase : List[str] = class_cost _UpperCamelCase : Union[str, Any] = bbox_cost _UpperCamelCase : Any = giou_cost # Loss coefficients _UpperCamelCase : List[Any] = mask_loss_coefficient _UpperCamelCase : Dict = dice_loss_coefficient _UpperCamelCase : Dict = bbox_loss_coefficient _UpperCamelCase : Any = giou_loss_coefficient _UpperCamelCase : Optional[int] = eos_coefficient super().__init__(is_encoder_decoder=__a , **__a ) @property def __SCREAMING_SNAKE_CASE ( self : str ) -> int: return self.encoder_attention_heads @property def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: return self.d_model class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Dict = version.parse("1.11" ) @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ("pixel_mask", {0: "batch"}), ] ) @property def __SCREAMING_SNAKE_CASE ( self : str ) -> float: return 1e-5 @property def __SCREAMING_SNAKE_CASE ( self : str ) -> int: return 12
714
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowercase__ ( lowercase_ = 1_000_000 ,lowercase_ = 10 ) -> int: """simple docstring""" _UpperCamelCase : defaultdict = defaultdict(lowercase_ ) for outer_width in range(3 ,(t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: _UpperCamelCase : Any = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) ,1 ) else: _UpperCamelCase : str = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowercase_ ,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() = }""")
51
0
"""simple docstring""" import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = StableUnCLIPPipeline SCREAMING_SNAKE_CASE__ :Union[str, Any] = TEXT_TO_IMAGE_PARAMS SCREAMING_SNAKE_CASE__ :List[str] = TEXT_TO_IMAGE_BATCH_PARAMS SCREAMING_SNAKE_CASE__ :Any = TEXT_TO_IMAGE_IMAGE_PARAMS SCREAMING_SNAKE_CASE__ :str = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false SCREAMING_SNAKE_CASE__ :Union[str, Any] = False def __SCREAMING_SNAKE_CASE ( self : str ) -> Tuple: _UpperCamelCase : Tuple = 32 _UpperCamelCase : List[str] = embedder_hidden_size # prior components torch.manual_seed(0 ) _UpperCamelCase : Optional[int] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) _UpperCamelCase : int = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__a , projection_dim=__a , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) _UpperCamelCase : str = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=__a , num_layers=1 , ) torch.manual_seed(0 ) _UpperCamelCase : List[Any] = DDPMScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1000 , clip_sample=__a , clip_sample_range=5.0 , beta_schedule="squaredcos_cap_v2" , ) # regular denoising components torch.manual_seed(0 ) _UpperCamelCase : str = StableUnCLIPImageNormalizer(embedding_dim=__a ) _UpperCamelCase : Optional[Any] = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) _UpperCamelCase : int = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) _UpperCamelCase : int = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__a , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) _UpperCamelCase : Union[str, Any] = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__a , layers_per_block=1 , upcast_attention=__a , use_linear_projection=__a , ) torch.manual_seed(0 ) _UpperCamelCase : Optional[Any] = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type="v_prediction" , set_alpha_to_one=__a , steps_offset=1 , ) torch.manual_seed(0 ) _UpperCamelCase : Union[str, Any] = AutoencoderKL() _UpperCamelCase : List[str] = { # prior components "prior_tokenizer": prior_tokenizer, "prior_text_encoder": prior_text_encoder, "prior": prior, "prior_scheduler": prior_scheduler, # image noising components "image_normalizer": image_normalizer, "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder, "unet": unet, "scheduler": scheduler, "vae": vae, } return components def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : str , __a : List[str]=0 ) -> Tuple: if str(__a ).startswith("mps" ): _UpperCamelCase : Optional[Any] = torch.manual_seed(__a ) else: _UpperCamelCase : List[str] = torch.Generator(device=__a ).manual_seed(__a ) _UpperCamelCase : List[Any] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "prior_num_inference_steps": 2, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: _UpperCamelCase : Optional[int] = torch_device == "cpu" self._test_attention_slicing_forward_pass(test_max_difference=__a ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: _UpperCamelCase : Optional[Any] = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=__a ) @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE ( self : int ) -> Any: _UpperCamelCase : Any = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" ) _UpperCamelCase : Tuple = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _UpperCamelCase : List[str] = torch.Generator(device="cpu" ).manual_seed(0 ) _UpperCamelCase : Optional[Any] = pipe("anime turle" , generator=__a , output_type="np" ) _UpperCamelCase : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__a , __a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _UpperCamelCase : Optional[Any] = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) _UpperCamelCase : Optional[int] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _UpperCamelCase : str = pipe( "anime turtle" , prior_num_inference_steps=2 , num_inference_steps=2 , output_type="np" , ) _UpperCamelCase : Dict = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
715
"""simple docstring""" from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar lowerCamelCase__ = TypeVar("KEY") lowerCamelCase__ = TypeVar("VAL") @dataclass(frozen=_UpperCamelCase , slots=_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( Generic[KEY, VAL] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :KEY SCREAMING_SNAKE_CASE__ :VAL class __SCREAMING_SNAKE_CASE ( _Item ): '''simple docstring''' def __init__( self : List[str] ) -> None: super().__init__(__a , __a ) def __bool__( self : Dict ) -> bool: return False lowerCamelCase__ = _DeletedItem() class __SCREAMING_SNAKE_CASE ( MutableMapping[KEY, VAL] ): '''simple docstring''' def __init__( self : int , __a : int = 8 , __a : float = 0.75 ) -> None: _UpperCamelCase : str = initial_block_size _UpperCamelCase : list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 _UpperCamelCase : List[str] = capacity_factor _UpperCamelCase : Dict = 0 def __SCREAMING_SNAKE_CASE ( self : int , __a : KEY ) -> int: return hash(__a ) % len(self._buckets ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : int ) -> int: return (ind + 1) % len(self._buckets ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __a : int , __a : KEY , __a : VAL ) -> bool: _UpperCamelCase : List[Any] = self._buckets[ind] if not stored: _UpperCamelCase : Tuple = _Item(__a , __a ) self._len += 1 return True elif stored.key == key: _UpperCamelCase : Union[str, Any] = _Item(__a , __a ) return True else: return False def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> bool: _UpperCamelCase : Any = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False _UpperCamelCase : List[str] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __a : int ) -> None: _UpperCamelCase : Any = self._buckets _UpperCamelCase : List[Any] = [None] * new_size _UpperCamelCase : List[str] = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def __SCREAMING_SNAKE_CASE ( self : int ) -> None: self._resize(len(self._buckets ) * 2 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> None: self._resize(len(self._buckets ) // 2 ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : KEY ) -> Iterator[int]: _UpperCamelCase : str = self._get_bucket_index(__a ) for _ in range(len(self._buckets ) ): yield ind _UpperCamelCase : Tuple = self._get_next_ind(__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : KEY , __a : VAL ) -> None: for ind in self._iterate_buckets(__a ): if self._try_set(__a , __a , __a ): break def __setitem__( self : int , __a : KEY , __a : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(__a , __a ) def __delitem__( self : str , __a : KEY ) -> None: for ind in self._iterate_buckets(__a ): _UpperCamelCase : Tuple = self._buckets[ind] if item is None: raise KeyError(__a ) if item is _deleted: continue if item.key == key: _UpperCamelCase : List[Any] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : str , __a : KEY ) -> VAL: for ind in self._iterate_buckets(__a ): _UpperCamelCase : Tuple = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__a ) def __len__( self : List[Any] ) -> int: return self._len def __iter__( self : List[str] ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : List[str] ) -> str: _UpperCamelCase : Optional[int] = " ,".join( F'''{item.key}: {item.val}''' for item in self._buckets if item ) return F'''HashMap({val_string})'''
51
0
"""simple docstring""" import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def lowercase__ ( lowercase_ ) -> List[str]: """simple docstring""" _UpperCamelCase : int = model.config _UpperCamelCase : Optional[int] = DonutSwinConfig( image_size=original_config.input_size ,patch_size=4 ,depths=original_config.encoder_layer ,num_heads=[4, 8, 16, 32] ,window_size=original_config.window_size ,embed_dim=128 ,) _UpperCamelCase : Any = MBartConfig( is_decoder=lowercase_ ,is_encoder_decoder=lowercase_ ,add_cross_attention=lowercase_ ,decoder_layers=original_config.decoder_layer ,max_position_embeddings=original_config.max_position_embeddings ,vocab_size=len( model.decoder.tokenizer ) ,scale_embedding=lowercase_ ,add_final_layer_norm=lowercase_ ,) return encoder_config, decoder_config def lowercase__ ( lowercase_ ) -> Optional[int]: """simple docstring""" if "encoder.model" in name: _UpperCamelCase : str = name.replace("encoder.model" ,"encoder" ) if "decoder.model" in name: _UpperCamelCase : Dict = name.replace("decoder.model" ,"decoder" ) if "patch_embed.proj" in name: _UpperCamelCase : List[Any] = name.replace("patch_embed.proj" ,"embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: _UpperCamelCase : str = name.replace("patch_embed.norm" ,"embeddings.norm" ) if name.startswith("encoder" ): if "layers" in name: _UpperCamelCase : Union[str, Any] = "encoder." + name if "attn.proj" in name: _UpperCamelCase : Any = name.replace("attn.proj" ,"attention.output.dense" ) if "attn" in name and "mask" not in name: _UpperCamelCase : int = name.replace("attn" ,"attention.self" ) if "norm1" in name: _UpperCamelCase : int = name.replace("norm1" ,"layernorm_before" ) if "norm2" in name: _UpperCamelCase : int = name.replace("norm2" ,"layernorm_after" ) if "mlp.fc1" in name: _UpperCamelCase : List[str] = name.replace("mlp.fc1" ,"intermediate.dense" ) if "mlp.fc2" in name: _UpperCamelCase : Optional[Any] = name.replace("mlp.fc2" ,"output.dense" ) if name == "encoder.norm.weight": _UpperCamelCase : Union[str, Any] = "encoder.layernorm.weight" if name == "encoder.norm.bias": _UpperCamelCase : Tuple = "encoder.layernorm.bias" return name def lowercase__ ( lowercase_ ,lowercase_ ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): _UpperCamelCase : Optional[Any] = orig_state_dict.pop(lowercase_ ) if "qkv" in key: _UpperCamelCase : Tuple = key.split("." ) _UpperCamelCase : Dict = int(key_split[3] ) _UpperCamelCase : Optional[Any] = int(key_split[5] ) _UpperCamelCase : int = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _UpperCamelCase : int = val[:dim, :] _UpperCamelCase : Tuple = val[dim : dim * 2, :] _UpperCamelCase : Optional[Any] = val[-dim:, :] else: _UpperCamelCase : Union[str, Any] = val[:dim] _UpperCamelCase : Tuple = val[dim : dim * 2] _UpperCamelCase : Any = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: _UpperCamelCase : Dict = val return orig_state_dict def lowercase__ ( lowercase_ ,lowercase_=None ,lowercase_=False ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : List[str] = DonutModel.from_pretrained(lowercase_ ).eval() # load HuggingFace model _UpperCamelCase : Dict = get_configs(lowercase_ ) _UpperCamelCase : Dict = DonutSwinModel(lowercase_ ) _UpperCamelCase : int = MBartForCausalLM(lowercase_ ) _UpperCamelCase : str = VisionEncoderDecoderModel(encoder=lowercase_ ,decoder=lowercase_ ) model.eval() _UpperCamelCase : str = original_model.state_dict() _UpperCamelCase : Union[str, Any] = convert_state_dict(lowercase_ ,lowercase_ ) model.load_state_dict(lowercase_ ) # verify results on scanned document _UpperCamelCase : Any = load_dataset("hf-internal-testing/example-documents" ) _UpperCamelCase : Any = dataset["test"][0]["image"].convert("RGB" ) _UpperCamelCase : Dict = XLMRobertaTokenizerFast.from_pretrained(lowercase_ ,from_slow=lowercase_ ) _UpperCamelCase : Any = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis ,size=original_model.config.input_size[::-1] ) _UpperCamelCase : int = DonutProcessor(lowercase_ ,lowercase_ ) _UpperCamelCase : List[str] = processor(lowercase_ ,return_tensors="pt" ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": _UpperCamelCase : Optional[Any] = "<s_docvqa><s_question>{user_input}</s_question><s_answer>" _UpperCamelCase : str = "When is the coffee break?" _UpperCamelCase : str = task_prompt.replace("{user_input}" ,lowercase_ ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": _UpperCamelCase : int = "<s_rvlcdip>" elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: _UpperCamelCase : Any = "<s_cord>" elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": _UpperCamelCase : Tuple = "s_cord-v2>" elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": _UpperCamelCase : Tuple = "<s_zhtrainticket>" elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt _UpperCamelCase : List[Any] = "hello world" else: raise ValueError("Model name not supported" ) _UpperCamelCase : str = original_model.decoder.tokenizer(lowercase_ ,add_special_tokens=lowercase_ ,return_tensors="pt" )[ "input_ids" ] _UpperCamelCase : List[Any] = original_model.encoder.model.patch_embed(lowercase_ ) _UpperCamelCase : List[Any] = model.encoder.embeddings(lowercase_ ) assert torch.allclose(lowercase_ ,lowercase_ ,atol=1e-3 ) # verify encoder hidden states _UpperCamelCase : Any = original_model.encoder(lowercase_ ) _UpperCamelCase : Any = model.encoder(lowercase_ ).last_hidden_state assert torch.allclose(lowercase_ ,lowercase_ ,atol=1e-2 ) # verify decoder hidden states _UpperCamelCase : Any = original_model(lowercase_ ,lowercase_ ,lowercase_ ).logits _UpperCamelCase : List[str] = model(lowercase_ ,decoder_input_ids=lowercase_ ).logits assert torch.allclose(lowercase_ ,lowercase_ ,atol=1e-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(F'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) if push_to_hub: model.push_to_hub("nielsr/" + model_name.split("/" )[-1] ,commit_message="Update model" ) processor.push_to_hub("nielsr/" + model_name.split("/" )[-1] ,commit_message="Update model" ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub.", ) lowerCamelCase__ = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
716
"""simple docstring""" class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , __a : list[int] ) -> None: _UpperCamelCase : Tuple = len(__a ) _UpperCamelCase : Dict = [0] * len_array if len_array > 0: _UpperCamelCase : Optional[Any] = array[0] for i in range(1 , __a ): _UpperCamelCase : Tuple = self.prefix_sum[i - 1] + array[i] def __SCREAMING_SNAKE_CASE ( self : Dict , __a : int , __a : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : int ) -> bool: _UpperCamelCase : int = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(__a ) return False if __name__ == "__main__": import doctest doctest.testmod()
51
0
"""simple docstring""" def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> float: """simple docstring""" _UpperCamelCase : int = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def lowercase__ ( ) -> Any: """simple docstring""" print(sum_of_series(1 ,1 ,10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
717
"""simple docstring""" import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def lowercase__ ( lowercase_ ,lowercase_=7 ) -> Tuple: """simple docstring""" _UpperCamelCase : Optional[int] = None if token is not None: _UpperCamelCase : Optional[Any] = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} # The id of a workflow (not of a workflow run) _UpperCamelCase : Any = "636036" _UpperCamelCase : Tuple = F'''https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs''' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'''?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}''' _UpperCamelCase : Dict = requests.get(lowercase_ ,headers=lowercase_ ).json() return result["workflow_runs"] def lowercase__ ( lowercase_ ) -> List[str]: """simple docstring""" _UpperCamelCase : List[Any] = get_daily_ci_runs(lowercase_ ) _UpperCamelCase : Tuple = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": _UpperCamelCase : Union[str, Any] = workflow_run["id"] break return workflow_run_id def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> Optional[int]: """simple docstring""" _UpperCamelCase : str = get_last_daily_ci_runs(lowercase_ ) if workflow_run_id is not None: _UpperCamelCase : int = get_artifacts_links(worflow_run_id=lowercase_ ,token=lowercase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: _UpperCamelCase : Dict = artifacts_links[artifact_name] download_artifact( artifact_name=lowercase_ ,artifact_url=lowercase_ ,output_dir=lowercase_ ,token=lowercase_ ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> int: """simple docstring""" get_last_daily_ci_artifacts(lowercase_ ,lowercase_ ,lowercase_ ) _UpperCamelCase : Dict = {} for artifact_name in artifact_names: _UpperCamelCase : Union[str, Any] = os.path.join(lowercase_ ,F'''{artifact_name}.zip''' ) if os.path.isfile(lowercase_ ): _UpperCamelCase : int = {} with zipfile.ZipFile(lowercase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowercase_ ): # read the file with z.open(lowercase_ ) as f: _UpperCamelCase : int = f.read().decode("UTF-8" ) return results
51
0
"""simple docstring""" import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> List[str]: """simple docstring""" return params[F'''{prefix}/{prefix}/relpos_bias/rel_embedding'''][:, i, :] def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_="attention" ) -> str: """simple docstring""" _UpperCamelCase : List[Any] = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/key/kernel'''][:, i, :, :] ) _UpperCamelCase : Tuple = k_tmp.reshape(k_tmp.shape[0] ,k_tmp.shape[1] * k_tmp.shape[2] ) _UpperCamelCase : Optional[Any] = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/out/kernel'''][:, i, :, :] ) _UpperCamelCase : Dict = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] ,o_tmp.shape[2] ) _UpperCamelCase : str = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/query/kernel'''][:, i, :, :] ) _UpperCamelCase : int = q_tmp.reshape(q_tmp.shape[0] ,q_tmp.shape[1] * q_tmp.shape[2] ) _UpperCamelCase : Dict = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/value/kernel'''][:, i, :, :] ) _UpperCamelCase : Optional[Any] = v_tmp.reshape(v_tmp.shape[0] ,v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_=False ) -> Dict: """simple docstring""" if split_mlp_wi: _UpperCamelCase : Dict = params[F'''{prefix}/{prefix}/mlp/wi_0/kernel'''][:, i, :] _UpperCamelCase : Optional[Any] = params[F'''{prefix}/{prefix}/mlp/wi_1/kernel'''][:, i, :] _UpperCamelCase : Union[str, Any] = (wi_a, wi_a) else: _UpperCamelCase : Optional[Any] = params[F'''{prefix}/{prefix}/mlp/wi/kernel'''][:, i, :] _UpperCamelCase : int = params[F'''{prefix}/{prefix}/mlp/wo/kernel'''][:, i, :] return wi, wo def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" return params[F'''{prefix}/{prefix}/{layer_name}/scale'''][:, i] def lowercase__ ( lowercase_ ,*, lowercase_ ,lowercase_ ,lowercase_ = False ) -> List[Any]: """simple docstring""" _UpperCamelCase : int = traverse_util.flatten_dict(variables["target"] ) _UpperCamelCase : str = {"/".join(lowercase_ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi _UpperCamelCase : Union[str, Any] = "encoder/encoder/mlp/wi_0/kernel" in old print("Split MLP:" ,lowercase_ ) _UpperCamelCase : List[Any] = collections.OrderedDict() # Shared embeddings. _UpperCamelCase : str = old["token_embedder/embedding"] # Encoder. for i in range(lowercase_ ): # Block i, layer 0 (Self Attention). _UpperCamelCase : int = tax_layer_norm_lookup(lowercase_ ,lowercase_ ,"encoder" ,"pre_attention_layer_norm" ) _UpperCamelCase : str = tax_attention_lookup(lowercase_ ,lowercase_ ,"encoder" ,"attention" ) _UpperCamelCase : List[Any] = layer_norm _UpperCamelCase : str = k.T _UpperCamelCase : Optional[Any] = o.T _UpperCamelCase : List[str] = q.T _UpperCamelCase : int = v.T # Block i, layer 1 (MLP). _UpperCamelCase : Dict = tax_layer_norm_lookup(lowercase_ ,lowercase_ ,"encoder" ,"pre_mlp_layer_norm" ) _UpperCamelCase : int = tax_mlp_lookup(lowercase_ ,lowercase_ ,"encoder" ,lowercase_ ) _UpperCamelCase : int = layer_norm if split_mlp_wi: _UpperCamelCase : Optional[int] = wi[0].T _UpperCamelCase : Optional[Any] = wi[1].T else: _UpperCamelCase : Any = wi.T _UpperCamelCase : Optional[Any] = wo.T if scalable_attention: # convert the rel_embedding of each layer _UpperCamelCase : Optional[int] = tax_relpos_bias_lookup( lowercase_ ,lowercase_ ,"encoder" ).T _UpperCamelCase : str = old["encoder/encoder_norm/scale"] if not scalable_attention: _UpperCamelCase : Any = tax_relpos_bias_lookup( lowercase_ ,0 ,"encoder" ).T _UpperCamelCase : str = tax_relpos_bias_lookup( lowercase_ ,0 ,"decoder" ).T if not is_encoder_only: # Decoder. for i in range(lowercase_ ): # Block i, layer 0 (Self Attention). _UpperCamelCase : List[Any] = tax_layer_norm_lookup(lowercase_ ,lowercase_ ,"decoder" ,"pre_self_attention_layer_norm" ) _UpperCamelCase : Any = tax_attention_lookup(lowercase_ ,lowercase_ ,"decoder" ,"self_attention" ) _UpperCamelCase : List[str] = layer_norm _UpperCamelCase : Union[str, Any] = k.T _UpperCamelCase : str = o.T _UpperCamelCase : List[str] = q.T _UpperCamelCase : Union[str, Any] = v.T # Block i, layer 1 (Cross Attention). _UpperCamelCase : Dict = tax_layer_norm_lookup(lowercase_ ,lowercase_ ,"decoder" ,"pre_cross_attention_layer_norm" ) _UpperCamelCase : int = tax_attention_lookup(lowercase_ ,lowercase_ ,"decoder" ,"encoder_decoder_attention" ) _UpperCamelCase : List[str] = layer_norm _UpperCamelCase : str = k.T _UpperCamelCase : List[Any] = o.T _UpperCamelCase : int = q.T _UpperCamelCase : List[Any] = v.T # Block i, layer 2 (MLP). _UpperCamelCase : Tuple = tax_layer_norm_lookup(lowercase_ ,lowercase_ ,"decoder" ,"pre_mlp_layer_norm" ) _UpperCamelCase : Tuple = tax_mlp_lookup(lowercase_ ,lowercase_ ,"decoder" ,lowercase_ ) _UpperCamelCase : Optional[int] = layer_norm if split_mlp_wi: _UpperCamelCase : List[Any] = wi[0].T _UpperCamelCase : Optional[int] = wi[1].T else: _UpperCamelCase : str = wi.T _UpperCamelCase : Union[str, Any] = wo.T if scalable_attention: # convert the rel_embedding of each layer _UpperCamelCase : Optional[int] = tax_relpos_bias_lookup(lowercase_ ,lowercase_ ,"decoder" ).T _UpperCamelCase : Tuple = old["decoder/decoder_norm/scale"] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: _UpperCamelCase : Any = old["decoder/logits_dense/kernel"].T return new def lowercase__ ( lowercase_ ,lowercase_ ) -> Tuple: """simple docstring""" _UpperCamelCase : Dict = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: _UpperCamelCase : str = state_dict["shared.weight"] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: _UpperCamelCase : Optional[int] = state_dict["shared.weight"] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("Using shared word embeddings as lm_head." ) _UpperCamelCase : int = state_dict["shared.weight"] return state_dict def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : int = checkpoints.load_tax_checkpoint(lowercase_ ) _UpperCamelCase : List[str] = convert_tax_to_pytorch( lowercase_ ,num_layers=config.num_layers ,is_encoder_only=lowercase_ ,scalable_attention=lowercase_ ) _UpperCamelCase : Union[str, Any] = make_state_dict(lowercase_ ,lowercase_ ) model.load_state_dict(lowercase_ ,strict=lowercase_ ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ = False ,lowercase_ = False ,) -> Tuple: """simple docstring""" _UpperCamelCase : int = MTaConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: _UpperCamelCase : Optional[int] = UMTaEncoderModel(lowercase_ ) else: _UpperCamelCase : Optional[int] = UMTaForConditionalGeneration(lowercase_ ) # Load weights from tf checkpoint load_tax_weights_in_ta(lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(lowercase_ ) # Verify that we can load the checkpoint. model.from_pretrained(lowercase_ ) print("Done" ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser(description="Converts a native T5X checkpoint into a PyTorch checkpoint.") # Required parameters parser.add_argument( "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path to the T5X checkpoint." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_encoder_only", action="store_true", help="Check if the model is encoder-decoder model", default=False ) parser.add_argument( "--scalable_attention", action="store_true", help="Whether the model uses scaled attention (umt5 model)", default=False, ) lowerCamelCase__ = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
718
"""simple docstring""" import math class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Any , __a : list[list[float]] , __a : list[int] ) -> int: _UpperCamelCase : List[Any] = 0.0 _UpperCamelCase : Union[str, Any] = 0.0 for i in range(len(__a ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __a : list[list[int | float]] , __a : list[int] , __a : int , __a : float ) -> list[list[int | float]]: for i in range(len(__a ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def lowercase__ ( ) -> None: """simple docstring""" _UpperCamelCase : Optional[int] = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) _UpperCamelCase : List[str] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training _UpperCamelCase : List[Any] = SelfOrganizingMap() _UpperCamelCase : int = 3 _UpperCamelCase : List[Any] = 0.5 for _ in range(lowercase_ ): for j in range(len(lowercase_ ) ): # training sample _UpperCamelCase : int = training_samples[j] # Compute the winning vector _UpperCamelCase : Tuple = self_organizing_map.get_winner(lowercase_ ,lowercase_ ) # Update the winning vector _UpperCamelCase : int = self_organizing_map.update(lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) # classify test sample _UpperCamelCase : Optional[int] = [0, 0, 0, 1] _UpperCamelCase : Dict = self_organizing_map.get_winner(lowercase_ ,lowercase_ ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
51
0
"""simple docstring""" import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: _UpperCamelCase : Any = "| <pad> <unk> <s> </s> a b c d e f g h i j k".split() _UpperCamelCase : Any = dict(zip(__a , range(len(__a ) ) ) ) _UpperCamelCase : Union[str, Any] = { "unk_token": "<unk>", "bos_token": "<s>", "eos_token": "</s>", } _UpperCamelCase : List[str] = { "feature_size": 1, "padding_value": 0.0, "sampling_rate": 1_6000, "return_attention_mask": False, "do_normalize": True, } _UpperCamelCase : Optional[Any] = tempfile.mkdtemp() _UpperCamelCase : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _UpperCamelCase : List[Any] = os.path.join(self.tmpdirname , __a ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(__a ) + "\n" ) with open(self.feature_extraction_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(__a ) + "\n" ) # load decoder from hub _UpperCamelCase : List[Any] = "hf-internal-testing/ngram-beam-search-decoder" def __SCREAMING_SNAKE_CASE ( self : Tuple , **__a : Union[str, Any] ) -> int: _UpperCamelCase : Tuple = self.add_kwargs_tokens_map.copy() kwargs.update(__a ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **__a ) def __SCREAMING_SNAKE_CASE ( self : Tuple , **__a : List[str] ) -> int: return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **__a ) def __SCREAMING_SNAKE_CASE ( self : str , **__a : Optional[int] ) -> Tuple: return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **__a ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: shutil.rmtree(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: _UpperCamelCase : List[Any] = self.get_tokenizer() _UpperCamelCase : Dict = self.get_feature_extractor() _UpperCamelCase : Dict = self.get_decoder() _UpperCamelCase : int = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase : Optional[Any] = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) # decoder self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , ) self.assertIsInstance(processor.decoder , __a ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[int]: _UpperCamelCase : List[Any] = WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match _UpperCamelCase : Union[str, Any] = WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha , 5.0 ) self.assertEqual(processor.language_model.beta , 3.0 ) self.assertEqual(processor.language_model.score_boundary , -7.0 ) self.assertEqual(processor.language_model.unk_score_offset , 3 ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: _UpperCamelCase : int = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(["xx"] ) with self.assertRaisesRegex(__a , "include" ): WavaVecaProcessorWithLM( tokenizer=__a , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: _UpperCamelCase : Any = self.get_feature_extractor() _UpperCamelCase : Dict = self.get_tokenizer() _UpperCamelCase : str = self.get_decoder() _UpperCamelCase : Tuple = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a ) _UpperCamelCase : Union[str, Any] = floats_list((3, 1000) ) _UpperCamelCase : List[Any] = feature_extractor(__a , return_tensors="np" ) _UpperCamelCase : Optional[Any] = processor(__a , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> int: _UpperCamelCase : str = self.get_feature_extractor() _UpperCamelCase : List[str] = self.get_tokenizer() _UpperCamelCase : Union[str, Any] = self.get_decoder() _UpperCamelCase : Dict = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a ) _UpperCamelCase : Optional[int] = "This is a test string" _UpperCamelCase : Optional[int] = processor(text=__a ) _UpperCamelCase : Any = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : Tuple=(2, 10, 16) , __a : int=77 ) -> List[Any]: np.random.seed(__a ) return np.random.rand(*__a ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: _UpperCamelCase : Optional[Any] = self.get_feature_extractor() _UpperCamelCase : List[Any] = self.get_tokenizer() _UpperCamelCase : Optional[Any] = self.get_decoder() _UpperCamelCase : Optional[int] = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a ) _UpperCamelCase : Union[str, Any] = self._get_dummy_logits(shape=(10, 16) , seed=13 ) _UpperCamelCase : List[Any] = processor.decode(__a ) _UpperCamelCase : str = decoder.decode_beams(__a )[0] self.assertEqual(decoded_decoder[0] , decoded_processor.text ) self.assertEqual("</s> <s> </s>" , decoded_processor.text ) self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score ) @parameterized.expand([[None], ["fork"], ["spawn"]] ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : Tuple ) -> Any: _UpperCamelCase : str = self.get_feature_extractor() _UpperCamelCase : int = self.get_tokenizer() _UpperCamelCase : str = self.get_decoder() _UpperCamelCase : Dict = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a ) _UpperCamelCase : Any = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: _UpperCamelCase : List[str] = processor.batch_decode(__a ) else: with get_context(__a ).Pool() as pool: _UpperCamelCase : List[str] = processor.batch_decode(__a , __a ) _UpperCamelCase : Any = list(__a ) with get_context("fork" ).Pool() as p: _UpperCamelCase : Optional[int] = decoder.decode_beams_batch(__a , __a ) _UpperCamelCase : Dict = [], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(__a , decoded_processor.text ) self.assertListEqual(["<s> <s> </s>", "<s> <s> <s>"] , decoded_processor.text ) self.assertListEqual(__a , decoded_processor.logit_score ) self.assertListEqual(__a , decoded_processor.lm_score ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: _UpperCamelCase : Dict = self.get_feature_extractor() _UpperCamelCase : Any = self.get_tokenizer() _UpperCamelCase : Optional[int] = self.get_decoder() _UpperCamelCase : Optional[int] = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a ) _UpperCamelCase : int = self._get_dummy_logits() _UpperCamelCase : Tuple = 15 _UpperCamelCase : List[Any] = -20.0 _UpperCamelCase : int = -4.0 _UpperCamelCase : Union[str, Any] = processor.batch_decode( __a , beam_width=__a , beam_prune_logp=__a , token_min_logp=__a , ) _UpperCamelCase : List[str] = decoded_processor_out.text _UpperCamelCase : Optional[int] = list(__a ) with get_context("fork" ).Pool() as pool: _UpperCamelCase : List[str] = decoder.decode_beams_batch( __a , __a , beam_width=__a , beam_prune_logp=__a , token_min_logp=__a , ) _UpperCamelCase : int = [d[0][0] for d in decoded_decoder_out] _UpperCamelCase : List[Any] = [d[0][2] for d in decoded_decoder_out] _UpperCamelCase : Optional[Any] = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(__a , __a ) self.assertListEqual(["</s> <s> <s>", "<s> <s> <s>"] , __a ) self.assertTrue(np.array_equal(__a , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.0_54, -18.4_47] , __a , atol=1e-3 ) ) self.assertTrue(np.array_equal(__a , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.5_54, -13.94_74] , __a , atol=1e-3 ) ) def __SCREAMING_SNAKE_CASE ( self : Any ) -> Any: _UpperCamelCase : Optional[int] = self.get_feature_extractor() _UpperCamelCase : Union[str, Any] = self.get_tokenizer() _UpperCamelCase : Any = self.get_decoder() _UpperCamelCase : Dict = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a ) _UpperCamelCase : Union[str, Any] = self._get_dummy_logits() _UpperCamelCase : Optional[Any] = 2.0 _UpperCamelCase : Union[str, Any] = 5.0 _UpperCamelCase : Tuple = -20.0 _UpperCamelCase : str = True _UpperCamelCase : Any = processor.batch_decode( __a , alpha=__a , beta=__a , unk_score_offset=__a , lm_score_boundary=__a , ) _UpperCamelCase : str = decoded_processor_out.text _UpperCamelCase : Union[str, Any] = list(__a ) decoder.reset_params( alpha=__a , beta=__a , unk_score_offset=__a , lm_score_boundary=__a , ) with get_context("fork" ).Pool() as pool: _UpperCamelCase : List[str] = decoder.decode_beams_batch( __a , __a , ) _UpperCamelCase : str = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(__a , __a ) self.assertListEqual(["<s> </s> <s> </s> </s>", "</s> </s> <s> </s> </s>"] , __a ) _UpperCamelCase : Tuple = processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha , 2.0 ) self.assertEqual(lm_model.beta , 5.0 ) self.assertEqual(lm_model.unk_score_offset , -20.0 ) self.assertEqual(lm_model.score_boundary , __a ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Dict: _UpperCamelCase : List[Any] = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) _UpperCamelCase : str = processor.decoder.model_container[processor.decoder._model_key] _UpperCamelCase : Optional[Any] = Path(language_model._kenlm_model.path.decode("utf-8" ) ).parent.parent.absolute() _UpperCamelCase : Dict = os.listdir(__a ) _UpperCamelCase : Dict = ["alphabet.json", "language_model"] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(__a , __a ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: _UpperCamelCase : List[str] = snapshot_download("hf-internal-testing/processor_with_lm" ) _UpperCamelCase : int = WavaVecaProcessorWithLM.from_pretrained(__a ) _UpperCamelCase : Optional[Any] = processor.decoder.model_container[processor.decoder._model_key] _UpperCamelCase : Dict = Path(language_model._kenlm_model.path.decode("utf-8" ) ).parent.parent.absolute() _UpperCamelCase : Dict = os.listdir(__a ) _UpperCamelCase : Optional[Any] = os.listdir(__a ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(__a , __a ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: _UpperCamelCase : List[Any] = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) _UpperCamelCase : Dict = AutoProcessor.from_pretrained("hf-internal-testing/processor_with_lm" ) _UpperCamelCase : Dict = floats_list((3, 1000) ) _UpperCamelCase : Optional[Any] = processor_wavaveca(__a , return_tensors="np" ) _UpperCamelCase : Dict = processor_auto(__a , return_tensors="np" ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1e-2 ) _UpperCamelCase : List[str] = self._get_dummy_logits() _UpperCamelCase : str = processor_wavaveca.batch_decode(__a ) _UpperCamelCase : str = processor_auto.batch_decode(__a ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: _UpperCamelCase : Any = self.get_feature_extractor() _UpperCamelCase : Optional[int] = self.get_tokenizer() _UpperCamelCase : Any = self.get_decoder() _UpperCamelCase : Tuple = WavaVecaProcessorWithLM(tokenizer=__a , feature_extractor=__a , decoder=__a ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg="`processor` and `feature_extractor` model input names do not match" , ) @staticmethod def __SCREAMING_SNAKE_CASE ( __a : Optional[Any] , __a : Optional[int] ) -> int: _UpperCamelCase : Dict = [d[key] for d in offsets] return retrieved_list def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: _UpperCamelCase : Any = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) _UpperCamelCase : int = self._get_dummy_logits()[0] _UpperCamelCase : List[str] = processor.decode(__a , output_word_offsets=__a ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("text" in outputs ) self.assertTrue("word_offsets" in outputs ) self.assertTrue(isinstance(__a , __a ) ) self.assertEqual(" ".join(self.get_from_offsets(outputs["word_offsets"] , "word" ) ) , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "word" ) , ["<s>", "<s>", "</s>"] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "start_offset" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "end_offset" ) , [1, 3, 5] ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: _UpperCamelCase : List[str] = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) _UpperCamelCase : List[Any] = self._get_dummy_logits() _UpperCamelCase : str = processor.batch_decode(__a , output_word_offsets=__a ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("text" in outputs ) self.assertTrue("word_offsets" in outputs ) self.assertTrue(isinstance(__a , __a ) ) self.assertListEqual( [" ".join(self.get_from_offsets(__a , "word" ) ) for o in outputs["word_offsets"]] , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "word" ) , ["<s>", "<s>", "</s>"] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "start_offset" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "end_offset" ) , [1, 3, 5] ) @slow @require_torch @require_torchaudio def __SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: import torch _UpperCamelCase : Optional[int] = load_dataset("common_voice" , "en" , split="train" , streaming=__a ) _UpperCamelCase : Optional[int] = ds.cast_column("audio" , datasets.Audio(sampling_rate=1_6000 ) ) _UpperCamelCase : Any = iter(__a ) _UpperCamelCase : Union[str, Any] = next(__a ) _UpperCamelCase : Optional[Any] = AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm" ) _UpperCamelCase : List[Any] = WavaVecaForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm" ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train _UpperCamelCase : int = processor(sample["audio"]["array"] , return_tensors="pt" ).input_values with torch.no_grad(): _UpperCamelCase : Optional[Any] = model(__a ).logits.cpu().numpy() _UpperCamelCase : Dict = processor.decode(logits[0] , output_word_offsets=__a ) _UpperCamelCase : Any = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate _UpperCamelCase : str = [ { "start_time": d["start_offset"] * time_offset, "end_time": d["end_offset"] * time_offset, "word": d["word"], } for d in output["word_offsets"] ] _UpperCamelCase : Dict = "WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL" # output words self.assertEqual(" ".join(self.get_from_offsets(__a , "word" ) ) , __a ) self.assertEqual(" ".join(self.get_from_offsets(__a , "word" ) ) , output.text ) # output times _UpperCamelCase : List[str] = torch.tensor(self.get_from_offsets(__a , "start_time" ) ) _UpperCamelCase : List[Any] = torch.tensor(self.get_from_offsets(__a , "end_time" ) ) # fmt: off _UpperCamelCase : List[Any] = torch.tensor([1.41_99, 1.65_99, 2.25_99, 3.0, 3.24, 3.59_99, 3.79_99, 4.09_99, 4.26, 4.94, 5.28, 5.65_99, 5.78, 5.94, 6.32, 6.53_99, 6.65_99] ) _UpperCamelCase : Tuple = torch.tensor([1.53_99, 1.89_99, 2.9, 3.16, 3.53_99, 3.72, 4.01_99, 4.17_99, 4.76, 5.15_99, 5.55_99, 5.69_99, 5.86, 6.19_99, 6.38, 6.61_99, 6.94] ) # fmt: on self.assertTrue(torch.allclose(__a , __a , atol=0.01 ) ) self.assertTrue(torch.allclose(__a , __a , atol=0.01 ) )
719
"""simple docstring""" import argparse import collections import os import re 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/check_table.py lowerCamelCase__ = "src/transformers" lowerCamelCase__ = "docs/source/en" lowerCamelCase__ = "." def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> List[str]: """simple docstring""" with open(lowercase_ ,"r" ,encoding="utf-8" ,newline="\n" ) as f: _UpperCamelCase : Union[str, Any] = f.readlines() # Find the start prompt. _UpperCamelCase : Dict = 0 while not lines[start_index].startswith(lowercase_ ): start_index += 1 start_index += 1 _UpperCamelCase : Optional[int] = start_index while not lines[end_index].startswith(lowercase_ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | lowerCamelCase__ = "Model|Encoder|Decoder|ForConditionalGeneration" # 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)") # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase__ = direct_transformers_import(TRANSFORMERS_PATH) def lowercase__ ( lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Tuple = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)" ,lowercase_ ) return [m.group(0 ) for m in matches] def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : str = 2 if text == "✅" or text == "❌" else len(lowercase_ ) _UpperCamelCase : Union[str, Any] = (width - text_length) // 2 _UpperCamelCase : Dict = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def lowercase__ ( ) -> str: """simple docstring""" _UpperCamelCase : Optional[Any] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _UpperCamelCase : str = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } _UpperCamelCase : Dict = {name: config.replace("Config" ,"" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. _UpperCamelCase : int = collections.defaultdict(lowercase_ ) _UpperCamelCase : Dict = collections.defaultdict(lowercase_ ) _UpperCamelCase : Dict = collections.defaultdict(lowercase_ ) _UpperCamelCase : int = collections.defaultdict(lowercase_ ) _UpperCamelCase : str = collections.defaultdict(lowercase_ ) # Let's lookup through all transformers object (once). for attr_name in dir(lowercase_ ): _UpperCamelCase : List[str] = None if attr_name.endswith("Tokenizer" ): _UpperCamelCase : Tuple = slow_tokenizers _UpperCamelCase : Any = attr_name[:-9] elif attr_name.endswith("TokenizerFast" ): _UpperCamelCase : Optional[Any] = fast_tokenizers _UpperCamelCase : List[str] = attr_name[:-13] elif _re_tf_models.match(lowercase_ ) is not None: _UpperCamelCase : List[Any] = tf_models _UpperCamelCase : Dict = _re_tf_models.match(lowercase_ ).groups()[0] elif _re_flax_models.match(lowercase_ ) is not None: _UpperCamelCase : Dict = flax_models _UpperCamelCase : Union[str, Any] = _re_flax_models.match(lowercase_ ).groups()[0] elif _re_pt_models.match(lowercase_ ) is not None: _UpperCamelCase : Optional[int] = pt_models _UpperCamelCase : Any = _re_pt_models.match(lowercase_ ).groups()[0] if lookup_dict is not None: while len(lowercase_ ) > 0: if attr_name in model_name_to_prefix.values(): _UpperCamelCase : Dict = True break # Try again after removing the last word in the name _UpperCamelCase : List[str] = "".join(camel_case_split(lowercase_ )[:-1] ) # Let's build that table! _UpperCamelCase : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) _UpperCamelCase : List[str] = ["Model", "Tokenizer slow", "Tokenizer fast", "PyTorch support", "TensorFlow support", "Flax Support"] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). _UpperCamelCase : Union[str, Any] = [len(lowercase_ ) + 2 for c in columns] _UpperCamelCase : Any = max([len(lowercase_ ) for name in model_names] ) + 2 # Build the table per se _UpperCamelCase : Tuple = "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for c, w in zip(lowercase_ ,lowercase_ )] ) + "|\n" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([":" + "-" * (w - 2) + ":" for w in widths] ) + "|\n" _UpperCamelCase : Union[str, Any] = {True: "✅", False: "❌"} for name in model_names: _UpperCamelCase : Optional[int] = model_name_to_prefix[name] _UpperCamelCase : Tuple = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(lowercase_ ,lowercase_ ) for l, w in zip(lowercase_ ,lowercase_ )] ) + "|\n" return table def lowercase__ ( lowercase_=False ) -> List[Any]: """simple docstring""" _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : str = _find_text_in_file( filename=os.path.join(lowercase_ ,"index.md" ) ,start_prompt="<!--This table is updated automatically from the auto modules" ,end_prompt="<!-- End table-->" ,) _UpperCamelCase : Any = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(lowercase_ ,"index.md" ) ,"w" ,encoding="utf-8" ,newline="\n" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( "The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this." ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") lowerCamelCase__ = parser.parse_args() check_model_table(args.fix_and_overwrite)
51
0
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase__ = get_tests_dir("fixtures/test_sentencepiece.model") lowerCamelCase__ = get_tests_dir("fixtures/test_sentencepiece_bpe.model") lowerCamelCase__ = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[int] = CamembertTokenizer SCREAMING_SNAKE_CASE__ :List[Any] = CamembertTokenizerFast SCREAMING_SNAKE_CASE__ :Optional[Any] = True SCREAMING_SNAKE_CASE__ :int = True def __SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing _UpperCamelCase : Optional[int] = CamembertTokenizer(__a ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: _UpperCamelCase : Any = "<pad>" _UpperCamelCase : Optional[int] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: _UpperCamelCase : List[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>NOTUSED" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "<mask>" ) self.assertEqual(len(__a ) , 1004 ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: _UpperCamelCase : Tuple = CamembertTokenizer(__a ) tokenizer.save_pretrained(self.tmpdirname ) _UpperCamelCase : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) _UpperCamelCase : str = "I was born in 92000, and this is falsé." _UpperCamelCase : Tuple = tokenizer.encode(__a ) _UpperCamelCase : Any = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) _UpperCamelCase : Union[str, Any] = tokenizer.encode(__a , add_special_tokens=__a ) _UpperCamelCase : List[str] = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) _UpperCamelCase : Tuple = tokenizer.convert_ids_to_tokens(__a ) _UpperCamelCase : Tuple = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: if not self.test_rust_tokenizer: return _UpperCamelCase : Union[str, Any] = self.get_tokenizer() _UpperCamelCase : int = self.get_rust_tokenizer() _UpperCamelCase : Optional[int] = "I was born in 92000, and this is falsé." _UpperCamelCase : Dict = tokenizer.tokenize(__a ) _UpperCamelCase : Optional[Any] = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) _UpperCamelCase : Optional[Any] = tokenizer.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Any = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) _UpperCamelCase : Optional[Any] = self.get_rust_tokenizer() _UpperCamelCase : Any = tokenizer.encode(__a ) _UpperCamelCase : str = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) @slow def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]: # fmt: off _UpperCamelCase : Union[str, Any] = {"input_ids": [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. _UpperCamelCase : List[Any] = [ "Le transformeur est un modèle d'apprentissage profond introduit en 2017, " "utilisé principalement dans le domaine du traitement automatique des langues (TAL).", "À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus " "pour gérer des données séquentielles, telles que le langage naturel, pour des tâches " "telles que la traduction et la synthèse de texte.", ] self.tokenizer_integration_test_util( expected_encoding=__a , model_name="camembert-base" , revision="3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf" , sequences=__a , )
720
"""simple docstring""" from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. lowerCamelCase__ = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. lowerCamelCase__ = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. lowerCamelCase__ = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def lowercase__ ( lowercase_ ,lowercase_ ) -> tuple[str, float]: """simple docstring""" _UpperCamelCase : str = len([g for position, g in enumerate(lowercase_ ) if g == main_target[position]] ) return (item, float(lowercase_ )) def lowercase__ ( lowercase_ ,lowercase_ ) -> tuple[str, str]: """simple docstring""" _UpperCamelCase : Tuple = random.randint(0 ,len(lowercase_ ) - 1 ) _UpperCamelCase : Dict = parent_a[:random_slice] + parent_a[random_slice:] _UpperCamelCase : Tuple = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def lowercase__ ( lowercase_ ,lowercase_ ) -> str: """simple docstring""" _UpperCamelCase : int = list(lowercase_ ) if random.uniform(0 ,1 ) < MUTATION_PROBABILITY: _UpperCamelCase : int = random.choice(lowercase_ ) return "".join(lowercase_ ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,) -> list[str]: """simple docstring""" _UpperCamelCase : Optional[Any] = [] # Generate more children proportionally to the fitness score. _UpperCamelCase : List[str] = int(parent_a[1] * 100 ) + 1 _UpperCamelCase : Union[str, Any] = 10 if child_n >= 10 else child_n for _ in range(lowercase_ ): _UpperCamelCase : Dict = population_score[random.randint(0 ,lowercase_ )][0] _UpperCamelCase, _UpperCamelCase : Dict = crossover(parent_a[0] ,lowercase_ ) # Append new string to the population list. pop.append(mutate(lowercase_ ,lowercase_ ) ) pop.append(mutate(lowercase_ ,lowercase_ ) ) return pop def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ = True ) -> tuple[int, int, str]: """simple docstring""" if N_POPULATION < N_SELECTED: _UpperCamelCase : List[str] = F'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(lowercase_ ) # Verify that the target contains no genes besides the ones inside genes variable. _UpperCamelCase : int = sorted({c for c in target if c not in genes} ) if not_in_genes_list: _UpperCamelCase : int = F'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(lowercase_ ) # Generate random starting population. _UpperCamelCase : Union[str, Any] = [] for _ in range(lowercase_ ): population.append("".join([random.choice(lowercase_ ) for i in range(len(lowercase_ ) )] ) ) # Just some logs to know what the algorithms is doing. _UpperCamelCase, _UpperCamelCase : str = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowercase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. _UpperCamelCase : int = [evaluate(lowercase_ ,lowercase_ ) for item in population] # Check if there is a matching evolution. _UpperCamelCase : Optional[Any] = sorted(lowercase_ ,key=lambda lowercase_ : x[1] ,reverse=lowercase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'''\nGeneration: {generation}''' F'''\nTotal Population:{total_population}''' F'''\nBest score: {population_score[0][1]}''' F'''\nBest string: {population_score[0][0]}''' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. _UpperCamelCase : str = population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowercase_ ) # Normalize population score to be between 0 and 1. _UpperCamelCase : str = [ (item, score / len(lowercase_ )) for item, score in population_score ] # This is selection for i in range(lowercase_ ): population.extend(select(population_score[int(lowercase_ )] ,lowercase_ ,lowercase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowercase_ ) > N_POPULATION: break if __name__ == "__main__": lowerCamelCase__ = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) lowerCamelCase__ = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = basic(target_str, genes_list) print( f"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}""" )
51
0
"""simple docstring""" from __future__ import annotations def lowercase__ ( lowercase_ ) -> int: """simple docstring""" _UpperCamelCase : Dict = len(lowercase_ ) // 2 # choose the middle 3 elements _UpperCamelCase : Dict = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
721
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = ["model.decoder.embed_positions.weights"] def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" if "emb" in name: _UpperCamelCase : List[str] = name.replace("emb" ,"model.decoder.embed_tokens" ) if "transformer" in name: _UpperCamelCase : Optional[int] = name.replace("transformer" ,"model.decoder" ) if "cross_attention" in name: _UpperCamelCase : Optional[int] = name.replace("cross_attention" ,"encoder_attn" ) if "linear1" in name: _UpperCamelCase : Optional[Any] = name.replace("linear1" ,"fc1" ) if "linear2" in name: _UpperCamelCase : Union[str, Any] = name.replace("linear2" ,"fc2" ) if "norm1" in name: _UpperCamelCase : Optional[Any] = name.replace("norm1" ,"self_attn_layer_norm" ) if "norm_cross" in name: _UpperCamelCase : Dict = name.replace("norm_cross" ,"encoder_attn_layer_norm" ) if "norm2" in name: _UpperCamelCase : Union[str, Any] = name.replace("norm2" ,"final_layer_norm" ) if "out_norm" in name: _UpperCamelCase : Union[str, Any] = name.replace("out_norm" ,"model.decoder.layer_norm" ) if "linears" in name: _UpperCamelCase : List[str] = name.replace("linears" ,"lm_heads" ) if "condition_provider.conditioners.description.output_proj" in name: _UpperCamelCase : Any = name.replace("condition_provider.conditioners.description.output_proj" ,"enc_to_dec_proj" ) return name def lowercase__ ( lowercase_ ,lowercase_ ) -> Tuple[Dict, Dict]: """simple docstring""" _UpperCamelCase : str = list(state_dict.keys() ) _UpperCamelCase : Optional[Any] = {} for key in keys: _UpperCamelCase : Optional[int] = state_dict.pop(lowercase_ ) _UpperCamelCase : List[Any] = rename_keys(lowercase_ ) if "in_proj_weight" in key: # split fused qkv proj _UpperCamelCase : Tuple = val[:hidden_size, :] _UpperCamelCase : Optional[Any] = val[hidden_size : 2 * hidden_size, :] _UpperCamelCase : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _UpperCamelCase : Optional[Any] = val else: _UpperCamelCase : List[str] = val return state_dict, enc_dec_proj_state_dict def lowercase__ ( lowercase_ ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values _UpperCamelCase : List[Any] = 1_024 _UpperCamelCase : List[str] = 24 _UpperCamelCase : Any = 16 elif checkpoint == "medium": _UpperCamelCase : Tuple = 1_536 _UpperCamelCase : Dict = 48 _UpperCamelCase : Tuple = 24 elif checkpoint == "large": _UpperCamelCase : int = 2_048 _UpperCamelCase : Optional[int] = 48 _UpperCamelCase : Dict = 32 else: raise ValueError(F'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' ) _UpperCamelCase : str = MusicgenDecoderConfig( hidden_size=lowercase_ ,ffn_dim=hidden_size * 4 ,num_hidden_layers=lowercase_ ,num_attention_heads=lowercase_ ,) return config @torch.no_grad() def lowercase__ ( lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_="cpu" ) -> List[str]: """simple docstring""" _UpperCamelCase : str = MusicGen.get_pretrained(lowercase_ ,device=lowercase_ ) _UpperCamelCase : Union[str, Any] = decoder_config_from_checkpoint(lowercase_ ) _UpperCamelCase : Optional[int] = fairseq_model.lm.state_dict() _UpperCamelCase, _UpperCamelCase : Optional[Any] = rename_state_dict( lowercase_ ,hidden_size=decoder_config.hidden_size ) _UpperCamelCase : Tuple = TaEncoderModel.from_pretrained("t5-base" ) _UpperCamelCase : Union[str, Any] = EncodecModel.from_pretrained("facebook/encodec_32khz" ) _UpperCamelCase : str = MusicgenForCausalLM(lowercase_ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _UpperCamelCase, _UpperCamelCase : str = decoder.load_state_dict(lowercase_ ,strict=lowercase_ ) for key in missing_keys.copy(): if key.startswith(("text_encoder", "audio_encoder") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(lowercase_ ) if len(lowercase_ ) > 0: raise ValueError(F'''Missing key(s) in state_dict: {missing_keys}''' ) if len(lowercase_ ) > 0: raise ValueError(F'''Unexpected key(s) in state_dict: {unexpected_keys}''' ) # init the composite model _UpperCamelCase : str = MusicgenForConditionalGeneration(text_encoder=lowercase_ ,audio_encoder=lowercase_ ,decoder=lowercase_ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(lowercase_ ) # check we can do a forward pass _UpperCamelCase : List[str] = torch.arange(0 ,8 ,dtype=torch.long ).reshape(2 ,-1 ) _UpperCamelCase : Dict = input_ids.reshape(2 * 4 ,-1 ) with torch.no_grad(): _UpperCamelCase : Tuple = model(input_ids=lowercase_ ,decoder_input_ids=lowercase_ ).logits if logits.shape != (8, 1, 2_048): raise ValueError("Incorrect shape for logits" ) # now construct the processor _UpperCamelCase : int = AutoTokenizer.from_pretrained("t5-base" ) _UpperCamelCase : str = AutoFeatureExtractor.from_pretrained("facebook/encodec_32khz" ,padding_side="left" ) _UpperCamelCase : Optional[int] = MusicgenProcessor(feature_extractor=lowercase_ ,tokenizer=lowercase_ ) # set the appropriate bos/pad token ids _UpperCamelCase : str = 2_048 _UpperCamelCase : str = 2_048 # set other default generation config params _UpperCamelCase : Optional[Any] = int(30 * audio_encoder.config.frame_rate ) _UpperCamelCase : List[str] = True _UpperCamelCase : int = 3.0 if pytorch_dump_folder is not None: Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) logger.info(F'''Saving model {checkpoint} to {pytorch_dump_folder}''' ) model.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) if repo_id: logger.info(F'''Pushing model {checkpoint} to {repo_id}''' ) model.push_to_hub(lowercase_ ) processor.push_to_hub(lowercase_ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) lowerCamelCase__ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
51
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) def lowercase__ ( lowercase_ ,lowercase_=False ) -> Any: """simple docstring""" _UpperCamelCase : Union[str, Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ("cls_token", "vit.embeddings.cls_token"), ("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"), ("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"), ("pos_embed", "vit.embeddings.position_embeddings"), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _UpperCamelCase : List[str] = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) return rename_keys def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_=False ) -> Any: """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: _UpperCamelCase : Union[str, Any] = "" else: _UpperCamelCase : Union[str, Any] = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _UpperCamelCase : Any = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) _UpperCamelCase : List[str] = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict _UpperCamelCase : List[Any] = in_proj_weight[ : config.hidden_size, : ] _UpperCamelCase : Tuple = in_proj_bias[: config.hidden_size] _UpperCamelCase : Any = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _UpperCamelCase : Optional[int] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _UpperCamelCase : Dict = in_proj_weight[ -config.hidden_size :, : ] _UpperCamelCase : Any = in_proj_bias[-config.hidden_size :] def lowercase__ ( lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Optional[int] = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(lowercase_ ,lowercase_ ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ) -> List[str]: """simple docstring""" _UpperCamelCase : Dict = dct.pop(lowercase_ ) _UpperCamelCase : List[str] = val def lowercase__ ( ) -> List[Any]: """simple docstring""" _UpperCamelCase : Union[str, Any] = "http://images.cocodataset.org/val2017/000000039769.jpg" _UpperCamelCase : Any = Image.open(requests.get(lowercase_ ,stream=lowercase_ ).raw ) return im @torch.no_grad() def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_=True ) -> List[str]: """simple docstring""" _UpperCamelCase : Union[str, Any] = ViTConfig() # patch_size if model_name[-1] == "8": _UpperCamelCase : List[Any] = 8 # set labels if required if not base_model: _UpperCamelCase : Tuple = 1_000 _UpperCamelCase : Union[str, Any] = "huggingface/label-files" _UpperCamelCase : Optional[Any] = "imagenet-1k-id2label.json" _UpperCamelCase : int = json.load(open(hf_hub_download(lowercase_ ,lowercase_ ,repo_type="dataset" ) ,"r" ) ) _UpperCamelCase : int = {int(lowercase_ ): v for k, v in idalabel.items()} _UpperCamelCase : int = idalabel _UpperCamelCase : List[str] = {v: k for k, v in idalabel.items()} # size of the architecture if model_name in ["dino_vits8", "dino_vits16"]: _UpperCamelCase : Dict = 384 _UpperCamelCase : Any = 1_536 _UpperCamelCase : List[Any] = 12 _UpperCamelCase : Union[str, Any] = 6 # load original model from torch hub _UpperCamelCase : List[str] = torch.hub.load("facebookresearch/dino:main" ,lowercase_ ) original_model.eval() # load state_dict of original model, remove and rename some keys _UpperCamelCase : int = original_model.state_dict() if base_model: remove_classification_head_(lowercase_ ) _UpperCamelCase : Optional[Any] = create_rename_keys(lowercase_ ,base_model=lowercase_ ) for src, dest in rename_keys: rename_key(lowercase_ ,lowercase_ ,lowercase_ ) read_in_q_k_v(lowercase_ ,lowercase_ ,lowercase_ ) # load HuggingFace model if base_model: _UpperCamelCase : Dict = ViTModel(lowercase_ ,add_pooling_layer=lowercase_ ).eval() else: _UpperCamelCase : List[str] = ViTForImageClassification(lowercase_ ).eval() model.load_state_dict(lowercase_ ) # Check outputs on an image, prepared by ViTImageProcessor _UpperCamelCase : Tuple = ViTImageProcessor() _UpperCamelCase : str = image_processor(images=prepare_img() ,return_tensors="pt" ) _UpperCamelCase : str = encoding["pixel_values"] _UpperCamelCase : Union[str, Any] = model(lowercase_ ) if base_model: _UpperCamelCase : Union[str, Any] = original_model(lowercase_ ) assert torch.allclose(lowercase_ ,outputs.last_hidden_state[:, 0, :] ,atol=1e-1 ) else: _UpperCamelCase : str = original_model(lowercase_ ) assert logits.shape == outputs.logits.shape assert torch.allclose(lowercase_ ,outputs.logits ,atol=1e-3 ) Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase_ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase_ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="dino_vitb16", type=str, help="Name of the model trained with DINO you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--base_model", action="store_true", help="Whether to only convert the base model (no projection head weights).", ) parser.set_defaults(base_model=True) lowerCamelCase__ = parser.parse_args() convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
700
"""simple docstring""" from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowerCamelCase__ = input("Enter image url: ").strip() print(f"""Downloading image from {url} ...""") lowerCamelCase__ = BeautifulSoup(requests.get(url).content, "html.parser") # The image URL is in the content field of the first meta tag with property og:image lowerCamelCase__ = soup.find("meta", {"property": "og:image"})["content"] lowerCamelCase__ = requests.get(image_url).content lowerCamelCase__ = f"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, "wb") as fp: fp.write(image_data) print(f"""Done. Image saved to disk as {file_name}.""")
51
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "microsoft/biogpt": "https://huggingface.co/microsoft/biogpt/resolve/main/config.json", # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = "biogpt" def __init__( self : List[Any] , __a : List[Any]=4_2384 , __a : Optional[Any]=1024 , __a : Dict=24 , __a : List[str]=16 , __a : Any=4096 , __a : Tuple="gelu" , __a : List[str]=0.1 , __a : Optional[int]=0.1 , __a : Any=1024 , __a : Dict=0.02 , __a : str=1e-1_2 , __a : Optional[int]=True , __a : Union[str, Any]=True , __a : Optional[int]=0.0 , __a : Dict=0.0 , __a : List[str]=1 , __a : Dict=0 , __a : Any=2 , **__a : int , ) -> Dict: _UpperCamelCase : Union[str, Any] = vocab_size _UpperCamelCase : Optional[Any] = max_position_embeddings _UpperCamelCase : List[Any] = hidden_size _UpperCamelCase : int = num_hidden_layers _UpperCamelCase : Optional[Any] = num_attention_heads _UpperCamelCase : Optional[int] = intermediate_size _UpperCamelCase : Tuple = hidden_act _UpperCamelCase : Dict = hidden_dropout_prob _UpperCamelCase : Optional[int] = attention_probs_dropout_prob _UpperCamelCase : Tuple = initializer_range _UpperCamelCase : List[Any] = layer_norm_eps _UpperCamelCase : Tuple = scale_embedding _UpperCamelCase : List[str] = use_cache _UpperCamelCase : Any = layerdrop _UpperCamelCase : Optional[Any] = activation_dropout super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a )
701
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append(".") def lowercase__ ( lowercase_ ) -> int: """simple docstring""" _UpperCamelCase : Any = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " F'''{test_file} instead.''' ) _UpperCamelCase : str = components[-1] if not test_fn.endswith("py" ): raise ValueError(F'''`test_file` should be a python file. Got {test_fn} instead.''' ) if not test_fn.startswith("test_modeling_" ): raise ValueError( F'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.''' ) _UpperCamelCase : Dict = components[:-1] + [test_fn.replace(".py" ,"" )] _UpperCamelCase : List[str] = ".".join(lowercase_ ) return test_module_path def lowercase__ ( lowercase_ ) -> List[Any]: """simple docstring""" _UpperCamelCase : Optional[Any] = get_module_path(lowercase_ ) _UpperCamelCase : str = importlib.import_module(lowercase_ ) return test_module def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : Union[str, Any] = [] _UpperCamelCase : List[Any] = get_test_module(lowercase_ ) for attr in dir(lowercase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowercase_ ,lowercase_ ) ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Tuple: """simple docstring""" _UpperCamelCase : Optional[Any] = [] _UpperCamelCase : Any = get_test_module(lowercase_ ) for attr in dir(lowercase_ ): _UpperCamelCase : int = getattr(lowercase_ ,lowercase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). _UpperCamelCase : Optional[Any] = getattr(lowercase_ ,"all_model_classes" ,[] ) if len(lowercase_ ) > 0: test_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Any: """simple docstring""" _UpperCamelCase : Dict = get_test_classes(lowercase_ ) _UpperCamelCase : int = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" _UpperCamelCase : List[str] = test_class() if hasattr(lowercase_ ,"setUp" ): test.setUp() _UpperCamelCase : Tuple = None if hasattr(lowercase_ ,"model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: _UpperCamelCase : Tuple = test.model_tester.__class__ return model_tester def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : str = get_test_classes(lowercase_ ) _UpperCamelCase : Dict = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ,lowercase_ ) -> Dict: """simple docstring""" _UpperCamelCase : Any = get_test_classes_for_model(lowercase_ ,lowercase_ ) _UpperCamelCase : List[Any] = [] for test_class in test_classes: _UpperCamelCase : List[Any] = get_model_tester_from_test_class(lowercase_ ) if tester_class is not None: tester_classes.append(lowercase_ ) # sort with class names return sorted(lowercase_ ,key=lambda lowercase_ : x.__name__ ) def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Any = get_test_classes(lowercase_ ) _UpperCamelCase : Tuple = {test_class: get_model_tester_from_test_class(lowercase_ ) for test_class in test_classes} return test_tester_mapping def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : List[Any] = get_model_classes(lowercase_ ) _UpperCamelCase : Optional[int] = { model_class: get_test_classes_for_model(lowercase_ ,lowercase_ ) for model_class in model_classes } return model_test_mapping def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase : Optional[Any] = get_model_classes(lowercase_ ) _UpperCamelCase : Tuple = { model_class: get_tester_classes_for_model(lowercase_ ,lowercase_ ) for model_class in model_classes } return model_to_tester_mapping def lowercase__ ( lowercase_ ) -> Optional[int]: """simple docstring""" if isinstance(lowercase_ ,lowercase_ ): return o elif isinstance(lowercase_ ,lowercase_ ): return o.__name__ elif isinstance(lowercase_ ,(list, tuple) ): return [to_json(lowercase_ ) for x in o] elif isinstance(lowercase_ ,lowercase_ ): return {to_json(lowercase_ ): to_json(lowercase_ ) for k, v in o.items()} else: return o
51
0
def lowercase__ ( lowercase_ ) -> str: """simple docstring""" _UpperCamelCase : List[Any] = [] _UpperCamelCase : str = [] _UpperCamelCase : Dict = { "^": 3, "*": 2, "/": 2, "%": 2, "+": 1, "-": 1, } # Priority of each operator _UpperCamelCase : Union[str, Any] = len(lowercase_ ) if (len(lowercase_ ) > 7) else 7 # Print table header for output print( "Symbol".center(8 ) ,"Stack".center(lowercase_ ) ,"Postfix".center(lowercase_ ) ,sep=" | " ,) print("-" * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(lowercase_ ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(lowercase_ ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(lowercase_ ) == 0: stack.append(lowercase_ ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(lowercase_ ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(lowercase_ ) # push x to stack print( x.center(8 ) ,("".join(lowercase_ )).ljust(lowercase_ ) ,("".join(lowercase_ )).ljust(lowercase_ ) ,sep=" | " ,) # Output in tabular format while len(lowercase_ ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( " ".center(8 ) ,("".join(lowercase_ )).ljust(lowercase_ ) ,("".join(lowercase_ )).ljust(lowercase_ ) ,sep=" | " ,) # Output in tabular format return "".join(lowercase_ ) # return Postfix as str def lowercase__ ( lowercase_ ) -> List[str]: """simple docstring""" _UpperCamelCase : str = list(infix[::-1] ) # reverse the infix equation for i in range(len(lowercase_ ) ): if infix[i] == "(": _UpperCamelCase : Any = ")" # change "(" to ")" elif infix[i] == ")": _UpperCamelCase : Tuple = "(" # change ")" to "(" return (infix_2_postfix("".join(lowercase_ ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": lowerCamelCase__ = input("\nEnter an Infix Equation = ") # Input an Infix equation lowerCamelCase__ = "".join(Infix.split()) # Remove spaces from the input print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
702
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase__ = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure)
51
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available lowerCamelCase__ = {"tokenization_herbert": ["HerbertTokenizer"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ["HerbertTokenizerFast"] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
703
"""simple docstring""" lowerCamelCase__ = "\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCamelCase__ = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase__ = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
51
0
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "Intel/dpt-large": "https://huggingface.co/Intel/dpt-large/resolve/main/config.json", # See all DPT models at https://huggingface.co/models?filter=dpt } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[Any] = "dpt" def __init__( self : Optional[Any] , __a : Union[str, Any]=768 , __a : Tuple=12 , __a : Any=12 , __a : Any=3072 , __a : Dict="gelu" , __a : int=0.0 , __a : int=0.0 , __a : Tuple=0.02 , __a : str=1e-1_2 , __a : Dict=384 , __a : Optional[Any]=16 , __a : List[str]=3 , __a : List[str]=False , __a : Optional[Any]=True , __a : str=[2, 5, 8, 11] , __a : int="project" , __a : Union[str, Any]=[4, 2, 1, 0.5] , __a : Optional[int]=[96, 192, 384, 768] , __a : List[str]=256 , __a : Tuple=-1 , __a : Union[str, Any]=False , __a : Dict=True , __a : int=0.4 , __a : List[str]=255 , __a : Optional[Any]=0.1 , __a : Any=[1, 1024, 24, 24] , __a : Optional[Any]=[0, 1] , __a : Any=None , **__a : str , ) -> List[str]: super().__init__(**__a ) _UpperCamelCase : Union[str, Any] = hidden_size _UpperCamelCase : List[str] = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("Initializing the config with a `BiT` backbone." ) _UpperCamelCase : int = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, } _UpperCamelCase : Union[str, Any] = BitConfig(**__a ) elif isinstance(__a , __a ): logger.info("Initializing the config with a `BiT` backbone." ) _UpperCamelCase : int = BitConfig(**__a ) elif isinstance(__a , __a ): _UpperCamelCase : List[str] = backbone_config else: raise ValueError( F'''backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.''' ) _UpperCamelCase : str = backbone_featmap_shape _UpperCamelCase : Tuple = neck_ignore_stages if readout_type != "project": raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode." ) else: _UpperCamelCase : Dict = None _UpperCamelCase : Tuple = None _UpperCamelCase : Optional[int] = [] _UpperCamelCase : str = num_hidden_layers _UpperCamelCase : Optional[int] = num_attention_heads _UpperCamelCase : str = intermediate_size _UpperCamelCase : Optional[Any] = hidden_act _UpperCamelCase : Union[str, Any] = hidden_dropout_prob _UpperCamelCase : Optional[int] = attention_probs_dropout_prob _UpperCamelCase : Tuple = initializer_range _UpperCamelCase : Any = layer_norm_eps _UpperCamelCase : Optional[Any] = image_size _UpperCamelCase : Optional[Any] = patch_size _UpperCamelCase : Any = num_channels _UpperCamelCase : List[Any] = qkv_bias _UpperCamelCase : str = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']" ) _UpperCamelCase : Tuple = readout_type _UpperCamelCase : Optional[Any] = reassemble_factors _UpperCamelCase : Union[str, Any] = neck_hidden_sizes _UpperCamelCase : int = fusion_hidden_size _UpperCamelCase : List[str] = head_in_index _UpperCamelCase : Tuple = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) _UpperCamelCase : Union[str, Any] = use_auxiliary_head _UpperCamelCase : List[Any] = auxiliary_loss_weight _UpperCamelCase : int = semantic_loss_ignore_index _UpperCamelCase : Dict = semantic_classifier_dropout def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: _UpperCamelCase : List[Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: _UpperCamelCase : Any = self.backbone_config.to_dict() _UpperCamelCase : Any = self.__class__.model_type return output
704
"""simple docstring""" import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: _UpperCamelCase : Tuple = tempfile.mkdtemp() _UpperCamelCase : str = 5 # Realm tok _UpperCamelCase : Tuple = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "test", "question", "this", "is", "the", "first", "second", "third", "fourth", "fifth", "record", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _UpperCamelCase : Optional[int] = os.path.join(self.tmpdirname , "realm_tokenizer" ) os.makedirs(__a , exist_ok=__a ) _UpperCamelCase : Optional[Any] = os.path.join(__a , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) _UpperCamelCase : Optional[int] = os.path.join(self.tmpdirname , "realm_block_records" ) os.makedirs(__a , exist_ok=__a ) def __SCREAMING_SNAKE_CASE ( self : str ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , "realm_tokenizer" ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: shutil.rmtree(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: _UpperCamelCase : Optional[Any] = RealmConfig(num_block_records=self.num_block_records ) return config def __SCREAMING_SNAKE_CASE ( self : int ) -> int: _UpperCamelCase : Any = Dataset.from_dict( { "id": ["0", "1"], "question": ["foo", "bar"], "answers": [["Foo", "Bar"], ["Bar"]], } ) return dataset def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: _UpperCamelCase : int = np.array( [ b"This is the first record", b"This is the second record", b"This is the third record", b"This is the fourth record", b"This is the fifth record", b"This is a longer longer longer record", ] , dtype=__a , ) return block_records def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: _UpperCamelCase : List[str] = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def __SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: _UpperCamelCase : Tuple = self.get_config() _UpperCamelCase : int = self.get_dummy_retriever() _UpperCamelCase : Tuple = retriever.tokenizer _UpperCamelCase : List[str] = np.array([0, 3] , dtype="long" ) _UpperCamelCase : Union[str, Any] = tokenizer(["Test question"] ).input_ids _UpperCamelCase : List[str] = tokenizer( ["the fourth"] , add_special_tokens=__a , return_token_type_ids=__a , return_attention_mask=__a , ).input_ids _UpperCamelCase : str = config.reader_seq_len _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : List[Any] = retriever( __a , __a , answer_ids=__a , max_length=__a , return_tensors="np" ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(len(__a ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "first", "record", "[SEP]"] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ["[CLS]", "test", "question", "[SEP]", "this", "is", "the", "fourth", "record", "[SEP]"] , ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: _UpperCamelCase : Any = self.get_config() _UpperCamelCase : Dict = self.get_dummy_retriever() _UpperCamelCase : Dict = retriever.tokenizer _UpperCamelCase : List[Any] = np.array([0, 3, 5] , dtype="long" ) _UpperCamelCase : Optional[int] = tokenizer(["Test question"] ).input_ids _UpperCamelCase : str = tokenizer( ["the fourth", "longer longer"] , add_special_tokens=__a , return_token_type_ids=__a , return_attention_mask=__a , ).input_ids _UpperCamelCase : Union[str, Any] = config.reader_seq_len _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase : Optional[Any] = retriever( __a , __a , answer_ids=__a , max_length=__a , return_tensors="np" ) self.assertEqual([False, True, True] , __a ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , __a ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , __a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> List[str]: _UpperCamelCase : List[Any] = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) # Test local path _UpperCamelCase : int = retriever.from_pretrained(os.path.join(self.tmpdirname , "realm_block_records" ) ) self.assertEqual(retriever.block_records[0] , b"This is the first record" ) # Test mocked remote path with patch("transformers.models.realm.retrieval_realm.hf_hub_download" ) as mock_hf_hub_download: _UpperCamelCase : List[Any] = os.path.join( os.path.join(self.tmpdirname , "realm_block_records" ) , _REALM_BLOCK_RECORDS_FILENAME ) _UpperCamelCase : int = RealmRetriever.from_pretrained("google/realm-cc-news-pretrained-openqa" ) self.assertEqual(retriever.block_records[0] , b"This is the first record" )
51
0
"""simple docstring""" import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowerCamelCase__ = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.14.0", "To fix: pip install -r examples/pytorch/audio-classification/requirements.txt") def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ = 16_000 ) -> str: """simple docstring""" _UpperCamelCase : int = int(round(sample_rate * max_length ) ) if len(lowercase_ ) <= sample_length: return wav _UpperCamelCase : Dict = randint(0 ,len(lowercase_ ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class __SCREAMING_SNAKE_CASE : '''simple docstring''' SCREAMING_SNAKE_CASE__ :Optional[str] = field(default=_UpperCamelCase , metadata={"help": "Name of a dataset from the datasets package"} ) SCREAMING_SNAKE_CASE__ :Optional[str] = field( default=_UpperCamelCase , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) SCREAMING_SNAKE_CASE__ :Optional[str] = field( default=_UpperCamelCase , metadata={"help": "A file containing the training audio paths and labels."} ) SCREAMING_SNAKE_CASE__ :Optional[str] = field( default=_UpperCamelCase , metadata={"help": "A file containing the validation audio paths and labels."} ) SCREAMING_SNAKE_CASE__ :str = field( default="train" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) SCREAMING_SNAKE_CASE__ :str = field( default="validation" , metadata={ "help": ( "The name of the training data set split to use (via the datasets library). Defaults to 'validation'" ) } , ) SCREAMING_SNAKE_CASE__ :str = field( default="audio" , metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"} , ) SCREAMING_SNAKE_CASE__ :str = field( default="label" , metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"} ) SCREAMING_SNAKE_CASE__ :Optional[int] = field( default=_UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) SCREAMING_SNAKE_CASE__ :Optional[int] = field( default=_UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) SCREAMING_SNAKE_CASE__ :float = field( default=20 , metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."} , ) @dataclass class __SCREAMING_SNAKE_CASE : '''simple docstring''' SCREAMING_SNAKE_CASE__ :str = field( default="facebook/wav2vec2-base" , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} , ) SCREAMING_SNAKE_CASE__ :Optional[str] = field( default=_UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) SCREAMING_SNAKE_CASE__ :Optional[str] = field( default=_UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"} ) SCREAMING_SNAKE_CASE__ :str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) SCREAMING_SNAKE_CASE__ :Optional[str] = field( default=_UpperCamelCase , metadata={"help": "Name or path of preprocessor config."} ) SCREAMING_SNAKE_CASE__ :bool = field( default=_UpperCamelCase , metadata={"help": "Whether to freeze the feature encoder layers of the model."} ) SCREAMING_SNAKE_CASE__ :bool = field( default=_UpperCamelCase , metadata={"help": "Whether to generate an attention mask in the feature extractor."} ) SCREAMING_SNAKE_CASE__ :bool = field( default=_UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) SCREAMING_SNAKE_CASE__ :Optional[bool] = field( default=_UpperCamelCase , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) SCREAMING_SNAKE_CASE__ :bool = field( default=_UpperCamelCase , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def __SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( "The argument `--freeze_feature_extractor` is deprecated and " "will be removed in a future version. Use `--freeze_feature_encoder`" "instead. Setting `freeze_feature_encoder==True`." , __a , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( "The argument `--freeze_feature_extractor` is deprecated and " "should not be used in combination with `--freeze_feature_encoder`." "Only make use of `--freeze_feature_encoder`." ) def lowercase__ ( ) -> Tuple: """simple docstring""" _UpperCamelCase : Tuple = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _UpperCamelCase : Any = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _UpperCamelCase : List[Any] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_audio_classification" ,lowercase_ ,lowercase_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" ,datefmt="%m/%d/%Y %H:%M:%S" ,handlers=[logging.StreamHandler(sys.stdout )] ,) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _UpperCamelCase : int = training_args.get_process_log_level() logger.setLevel(lowercase_ ) transformers.utils.logging.set_verbosity(lowercase_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} ''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. _UpperCamelCase : int = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _UpperCamelCase : Union[str, Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' "Use --overwrite_output_dir to train from scratch." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Initialize our dataset and prepare it for the audio classification task. _UpperCamelCase : Dict = DatasetDict() _UpperCamelCase : Any = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.train_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) _UpperCamelCase : Any = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.eval_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F'''--audio_column_name {data_args.audio_column_name} not found in dataset \'{data_args.dataset_name}\'. ''' "Make sure to set `--audio_column_name` to the correct audio column - one of " F'''{', '.join(raw_datasets['train'].column_names )}.''' ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F'''--label_column_name {data_args.label_column_name} not found in dataset \'{data_args.dataset_name}\'. ''' "Make sure to set `--label_column_name` to the correct text column - one of " F'''{', '.join(raw_datasets['train'].column_names )}.''' ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy _UpperCamelCase : str = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path ,return_attention_mask=model_args.attention_mask ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. _UpperCamelCase : int = raw_datasets.cast_column( data_args.audio_column_name ,datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) _UpperCamelCase : Optional[int] = feature_extractor.model_input_names[0] def train_transforms(lowercase_ ): _UpperCamelCase : Dict = [] for audio in batch[data_args.audio_column_name]: _UpperCamelCase : Dict = random_subsample( audio["array"] ,max_length=data_args.max_length_seconds ,sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(lowercase_ ) _UpperCamelCase : List[Any] = feature_extractor(lowercase_ ,sampling_rate=feature_extractor.sampling_rate ) _UpperCamelCase : Optional[int] = {model_input_name: inputs.get(lowercase_ )} _UpperCamelCase : Tuple = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(lowercase_ ): _UpperCamelCase : Optional[Any] = [audio["array"] for audio in batch[data_args.audio_column_name]] _UpperCamelCase : Optional[int] = feature_extractor(lowercase_ ,sampling_rate=feature_extractor.sampling_rate ) _UpperCamelCase : List[Any] = {model_input_name: inputs.get(lowercase_ )} _UpperCamelCase : Union[str, Any] = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. _UpperCamelCase : Union[str, Any] = raw_datasets["train"].features[data_args.label_column_name].names _UpperCamelCase : int = {}, {} for i, label in enumerate(lowercase_ ): _UpperCamelCase : int = str(lowercase_ ) _UpperCamelCase : str = label # Load the accuracy metric from the datasets package _UpperCamelCase : List[Any] = evaluate.load("accuracy" ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(lowercase_ ): _UpperCamelCase : Any = np.argmax(eval_pred.predictions ,axis=1 ) return metric.compute(predictions=lowercase_ ,references=eval_pred.label_ids ) _UpperCamelCase : List[str] = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path ,num_labels=len(lowercase_ ) ,labelaid=lowercase_ ,idalabel=lowercase_ ,finetuning_task="audio-classification" ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) _UpperCamelCase : Optional[Any] = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path ,from_tf=bool(".ckpt" in model_args.model_name_or_path ) ,config=lowercase_ ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes ,) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: _UpperCamelCase : Union[str, Any] = ( raw_datasets["train"].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(lowercase_ ,output_all_columns=lowercase_ ) if training_args.do_eval: if data_args.max_eval_samples is not None: _UpperCamelCase : int = ( raw_datasets["eval"].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(lowercase_ ,output_all_columns=lowercase_ ) # Initialize our trainer _UpperCamelCase : Optional[Any] = Trainer( model=lowercase_ ,args=lowercase_ ,train_dataset=raw_datasets["train"] if training_args.do_train else None ,eval_dataset=raw_datasets["eval"] if training_args.do_eval else None ,compute_metrics=lowercase_ ,tokenizer=lowercase_ ,) # Training if training_args.do_train: _UpperCamelCase : Union[str, Any] = None if training_args.resume_from_checkpoint is not None: _UpperCamelCase : Optional[int] = training_args.resume_from_checkpoint elif last_checkpoint is not None: _UpperCamelCase : Tuple = last_checkpoint _UpperCamelCase : List[str] = trainer.train(resume_from_checkpoint=lowercase_ ) trainer.save_model() trainer.log_metrics("train" ,train_result.metrics ) trainer.save_metrics("train" ,train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _UpperCamelCase : List[str] = trainer.evaluate() trainer.log_metrics("eval" ,lowercase_ ) trainer.save_metrics("eval" ,lowercase_ ) # Write model card and (optionally) push to hub _UpperCamelCase : Dict = { "finetuned_from": model_args.model_name_or_path, "tasks": "audio-classification", "dataset": data_args.dataset_name, "tags": ["audio-classification"], } if training_args.push_to_hub: trainer.push_to_hub(**lowercase_ ) else: trainer.create_model_card(**lowercase_ ) if __name__ == "__main__": main()
705
"""simple docstring""" from __future__ import annotations import unittest from transformers import LEDConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class __SCREAMING_SNAKE_CASE : '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = LEDConfig SCREAMING_SNAKE_CASE__ :str = {} SCREAMING_SNAKE_CASE__ :List[str] = "gelu" def __init__( self : List[Any] , __a : Union[str, Any] , __a : List[Any]=13 , __a : int=7 , __a : str=True , __a : Any=False , __a : str=99 , __a : str=32 , __a : Union[str, Any]=2 , __a : Optional[Any]=4 , __a : List[Any]=37 , __a : List[Any]=0.1 , __a : Tuple=0.1 , __a : Dict=20 , __a : str=2 , __a : Dict=1 , __a : Any=0 , __a : List[Any]=4 , ) -> List[Any]: _UpperCamelCase : Optional[Any] = parent _UpperCamelCase : List[str] = batch_size _UpperCamelCase : str = seq_length _UpperCamelCase : str = is_training _UpperCamelCase : Any = use_labels _UpperCamelCase : Any = vocab_size _UpperCamelCase : List[str] = hidden_size _UpperCamelCase : Optional[Any] = num_hidden_layers _UpperCamelCase : Dict = num_attention_heads _UpperCamelCase : Optional[Any] = intermediate_size _UpperCamelCase : int = hidden_dropout_prob _UpperCamelCase : Dict = attention_probs_dropout_prob _UpperCamelCase : str = max_position_embeddings _UpperCamelCase : int = eos_token_id _UpperCamelCase : Dict = pad_token_id _UpperCamelCase : Optional[Any] = bos_token_id _UpperCamelCase : str = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after _UpperCamelCase : List[str] = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests _UpperCamelCase : int = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def __SCREAMING_SNAKE_CASE ( self : int ) -> str: _UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _UpperCamelCase : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _UpperCamelCase : Tuple = tf.concat([input_ids, eos_tensor] , axis=1 ) _UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCamelCase : List[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) _UpperCamelCase : Dict = prepare_led_inputs_dict(__a , __a , __a ) _UpperCamelCase : Union[str, Any] = tf.concat( [tf.zeros_like(__a )[:, :-1], tf.ones_like(__a )[:, -1:]] , axis=-1 , ) _UpperCamelCase : Union[str, Any] = global_attention_mask return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self : List[str] , __a : List[Any] , __a : int ) -> Tuple: _UpperCamelCase : Tuple = TFLEDModel(config=__a ).get_decoder() _UpperCamelCase : Tuple = inputs_dict["input_ids"] _UpperCamelCase : int = input_ids[:1, :] _UpperCamelCase : List[str] = inputs_dict["attention_mask"][:1, :] _UpperCamelCase : List[Any] = 1 # first forward pass _UpperCamelCase : Any = model(__a , attention_mask=__a , use_cache=__a ) _UpperCamelCase, _UpperCamelCase : Union[str, Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _UpperCamelCase : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) _UpperCamelCase : Any = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _UpperCamelCase : List[str] = tf.concat([input_ids, next_tokens] , axis=-1 ) _UpperCamelCase : Union[str, Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _UpperCamelCase : Tuple = model(__a , attention_mask=__a )[0] _UpperCamelCase : int = model(__a , attention_mask=__a , past_key_values=__a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _UpperCamelCase : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _UpperCamelCase : List[str] = output_from_no_past[:, -3:, random_slice_idx] _UpperCamelCase : Optional[int] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__a , __a , rtol=1e-3 ) def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_=None ,lowercase_=None ,) -> Dict: """simple docstring""" if attention_mask is None: _UpperCamelCase : str = tf.cast(tf.math.not_equal(lowercase_ ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: _UpperCamelCase : str = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: _UpperCamelCase : List[str] = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _UpperCamelCase : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Any = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :List[str] = (TFLEDForConditionalGeneration,) if is_tf_available() else () SCREAMING_SNAKE_CASE__ :List[str] = ( { "conversational": TFLEDForConditionalGeneration, "feature-extraction": TFLEDModel, "summarization": TFLEDForConditionalGeneration, "text2text-generation": TFLEDForConditionalGeneration, "translation": TFLEDForConditionalGeneration, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ :Tuple = True SCREAMING_SNAKE_CASE__ :str = False SCREAMING_SNAKE_CASE__ :Optional[Any] = False SCREAMING_SNAKE_CASE__ :int = False def __SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: _UpperCamelCase : int = TFLEDModelTester(self ) _UpperCamelCase : Any = ConfigTester(self , config_class=__a ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: _UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__a ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase, _UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase : Optional[int] = tf.zeros_like(inputs_dict["attention_mask"] ) _UpperCamelCase : Union[str, Any] = 2 _UpperCamelCase : str = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) _UpperCamelCase : Dict = True _UpperCamelCase : str = self.model_tester.seq_length _UpperCamelCase : Union[str, Any] = self.model_tester.encoder_seq_length def check_decoder_attentions_output(__a : Optional[int] ): _UpperCamelCase : Optional[int] = outputs.decoder_attentions self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(__a : Optional[Any] ): _UpperCamelCase : Union[str, Any] = [t.numpy() for t in outputs.encoder_attentions] _UpperCamelCase : List[Any] = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(__a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: _UpperCamelCase : Dict = True _UpperCamelCase : Optional[Any] = False _UpperCamelCase : int = False _UpperCamelCase : Optional[int] = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) _UpperCamelCase : Any = len(__a ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) if self.is_encoder_decoder: _UpperCamelCase : Optional[Any] = model_class(__a ) _UpperCamelCase : List[Any] = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_decoder_attentions_output(__a ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _UpperCamelCase : int = True _UpperCamelCase : Tuple = model_class(__a ) _UpperCamelCase : str = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) # Check attention is always last and order is fine _UpperCamelCase : Any = True _UpperCamelCase : List[str] = True _UpperCamelCase : Tuple = model_class(__a ) _UpperCamelCase : int = model(self._prepare_for_class(__a , __a ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(__a ) ) self.assertEqual(model.config.output_hidden_states , __a ) check_encoder_attentions_output(__a ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: pass def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: # TODO: Head-masking not yet implement pass def lowercase__ ( lowercase_ ) -> Union[str, Any]: """simple docstring""" return tf.constant(lowercase_ ,dtype=tf.intaa ) lowerCamelCase__ = 1E-4 @slow @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: _UpperCamelCase : Any = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here _UpperCamelCase : int = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Tuple = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Optional[Any] = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Optional[int] = model(**__a )[0] _UpperCamelCase : Optional[int] = (1, 1024, 768) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : Tuple = tf.convert_to_tensor( [[2.30_50, 2.82_79, 0.65_31], [-1.84_57, -0.14_55, -3.56_61], [-1.01_86, 0.45_86, -2.20_43]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> str: _UpperCamelCase : Optional[int] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here _UpperCamelCase : Optional[int] = _long_tensor([512 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : List[str] = _long_tensor([128 * [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69]] ) _UpperCamelCase : Optional[Any] = prepare_led_inputs_dict(model.config , __a , __a ) _UpperCamelCase : Union[str, Any] = model(**__a )[0] _UpperCamelCase : int = (1, 1024, model.config.vocab_size) self.assertEqual(output.shape , __a ) # change to expected output here _UpperCamelCase : Optional[int] = tf.convert_to_tensor( [[33.65_07, 6.45_72, 16.80_89], [5.87_39, -2.42_38, 11.29_02], [-3.21_39, -4.31_49, 4.27_83]] , ) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-3 , rtol=1e-3 )
51
0
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=_UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :str = field(default="text-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) SCREAMING_SNAKE_CASE__ :ClassVar[Features] = Features({"text": Value("string" )} ) SCREAMING_SNAKE_CASE__ :ClassVar[Features] = Features({"labels": ClassLabel} ) SCREAMING_SNAKE_CASE__ :str = "text" SCREAMING_SNAKE_CASE__ :str = "labels" def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : Tuple ) -> Optional[int]: if self.label_column not in features: raise ValueError(F'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __a ): raise ValueError(F'''Column {self.label_column} is not a ClassLabel.''' ) _UpperCamelCase : Tuple = copy.deepcopy(self ) _UpperCamelCase : Optional[Any] = self.label_schema.copy() _UpperCamelCase : Optional[Any] = features[self.label_column] _UpperCamelCase : Union[str, Any] = label_schema return task_template @property def __SCREAMING_SNAKE_CASE ( self : int ) -> Dict[str, str]: return { self.text_column: "text", self.label_column: "labels", }
706
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Union[str, Any] = RoCBertTokenizer SCREAMING_SNAKE_CASE__ :Dict = None SCREAMING_SNAKE_CASE__ :List[Any] = False SCREAMING_SNAKE_CASE__ :Union[str, Any] = True SCREAMING_SNAKE_CASE__ :Union[str, Any] = filter_non_english def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict: super().setUp() _UpperCamelCase : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] _UpperCamelCase : List[str] = {} _UpperCamelCase : Tuple = {} for i, value in enumerate(__a ): _UpperCamelCase : List[str] = i _UpperCamelCase : Optional[Any] = i _UpperCamelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) _UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) _UpperCamelCase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(__a , __a , ensure_ascii=__a ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(__a , __a , ensure_ascii=__a ) def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: _UpperCamelCase : Tuple = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : int = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(__a , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__a ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__a ) , [5, 6, 2, 5, 7, 8] ) def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: _UpperCamelCase : Dict = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: _UpperCamelCase : List[Any] = RoCBertBasicTokenizer(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 : Optional[Any] ) -> Tuple: _UpperCamelCase : Optional[Any] = RoCBertBasicTokenizer(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 : Dict ) -> str: _UpperCamelCase : Dict = RoCBertBasicTokenizer(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 : Union[str, Any] ) -> Union[str, Any]: _UpperCamelCase : List[str] = RoCBertBasicTokenizer(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[int]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: _UpperCamelCase : Union[str, Any] = RoCBertBasicTokenizer(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 : Tuple ) -> List[Any]: _UpperCamelCase : Tuple = RoCBertBasicTokenizer(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 : Optional[Any] ) -> int: _UpperCamelCase : int = RoCBertBasicTokenizer(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 : List[str] ) -> Optional[Any]: _UpperCamelCase : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] _UpperCamelCase : Any = {} for i, token in enumerate(__a ): _UpperCamelCase : str = i _UpperCamelCase : Optional[int] = RoCBertWordpieceTokenizer(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 : Dict ) -> Optional[Any]: 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: 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 : Optional[int] ) -> Optional[int]: 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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = self.get_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]"]] ) if self.test_rust_tokenizer: _UpperCamelCase : Tuple = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__a ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Union[str, Any] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' _UpperCamelCase : Optional[Any] = tokenizer_r.encode_plus( __a , return_attention_mask=__a , return_token_type_ids=__a , return_offsets_mapping=__a , add_special_tokens=__a , ) _UpperCamelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(__a , "do_lower_case" ) else False _UpperCamelCase : Dict = ( [ ((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 : int ) -> List[Any]: _UpperCamelCase : Optional[Any] = ["的", "人", "有"] _UpperCamelCase : int = "".join(__a ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): _UpperCamelCase : int = True _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : int = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : int = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : List[Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Union[str, Any] = 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 ) _UpperCamelCase : Any = False _UpperCamelCase : Dict = self.rust_tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a ) _UpperCamelCase : Any = tokenizer_r.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Any = tokenizer_p.encode(__a , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(__a ) _UpperCamelCase : Dict = tokenizer_p.convert_ids_to_tokens(__a ) # it is expected that only the first Chinese character is not preceded by "##". _UpperCamelCase : Any = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(__a ) ] self.assertListEqual(__a , __a ) self.assertListEqual(__a , __a ) @slow def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: _UpperCamelCase : Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) _UpperCamelCase : Optional[int] = tokenizer.encode("你好" , add_special_tokens=__a ) _UpperCamelCase : Dict = tokenizer.encode("你是谁" , add_special_tokens=__a ) _UpperCamelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__a ) _UpperCamelCase : Tuple = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int: _UpperCamelCase : Optional[Any] = self.get_tokenizers(do_lower_case=__a ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): _UpperCamelCase : int = "你好,你是谁" _UpperCamelCase : Any = tokenizer.tokenize(__a ) _UpperCamelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(__a ) _UpperCamelCase : List[str] = tokenizer.convert_tokens_to_shape_ids(__a ) _UpperCamelCase : Any = tokenizer.convert_tokens_to_pronunciation_ids(__a ) _UpperCamelCase : Optional[int] = tokenizer.prepare_for_model( __a , __a , __a , add_special_tokens=__a ) _UpperCamelCase : Tuple = tokenizer.encode_plus(__a , add_special_tokens=__a ) self.assertEqual(__a , __a )
51
0
"""simple docstring""" from collections import defaultdict class __SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , __a : List[str] , __a : Tuple ) -> Optional[Any]: _UpperCamelCase : Optional[Any] = total # total no of tasks (N) # DP table will have a dimension of (2^M)*N # initially all values are set to -1 _UpperCamelCase : Tuple = [ [-1 for i in range(total + 1 )] for j in range(2 ** len(__a ) ) ] _UpperCamelCase : List[Any] = defaultdict(__a ) # stores the list of persons for each task # final_mask is used to check if all persons are included by setting all bits # to 1 _UpperCamelCase : List[Any] = (1 << len(__a )) - 1 def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __a : Optional[int] , __a : Any ) -> Optional[int]: # if mask == self.finalmask all persons are distributed tasks, return 1 if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 if task_no > self.total_tasks: return 0 # if case already considered if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement _UpperCamelCase : Optional[Any] = self.count_ways_until(__a , task_no + 1 ) # now assign the tasks one by one to all possible persons and recursively # assign for the remaining tasks. if task_no in self.task: for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively # assign tasks with the new mask value. total_ways_util += self.count_ways_until(mask | (1 << p) , task_no + 1 ) # save the value. _UpperCamelCase : Union[str, Any] = total_ways_util return self.dp[mask][task_no] def __SCREAMING_SNAKE_CASE ( self : str , __a : Tuple ) -> List[str]: # Store the list of persons for each task for i in range(len(__a ) ): for j in task_performed[i]: self.task[j].append(__a ) # call the function to fill the DP table, final answer is stored in dp[0][1] return self.count_ways_until(0 , 1 ) if __name__ == "__main__": lowerCamelCase__ = 5 # total no of tasks (the value of N) # the list of tasks that can be done by M persons. lowerCamelCase__ = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) )
707
"""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 lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "hustvl/yolos-small": "https://huggingface.co/hustvl/yolos-small/resolve/main/config.json", # See all YOLOS models at https://huggingface.co/models?filter=yolos } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :Tuple = "yolos" def __init__( self : Dict , __a : Optional[Any]=768 , __a : List[Any]=12 , __a : Any=12 , __a : List[Any]=3072 , __a : Optional[int]="gelu" , __a : Dict=0.0 , __a : Optional[Any]=0.0 , __a : Any=0.02 , __a : Optional[int]=1e-1_2 , __a : List[Any]=[512, 864] , __a : List[str]=16 , __a : str=3 , __a : Optional[Any]=True , __a : Optional[Any]=100 , __a : List[str]=True , __a : Any=False , __a : List[str]=1 , __a : str=5 , __a : Optional[Any]=2 , __a : Tuple=5 , __a : Any=2 , __a : Union[str, Any]=0.1 , **__a : List[str] , ) -> List[str]: super().__init__(**__a ) _UpperCamelCase : Dict = hidden_size _UpperCamelCase : Any = num_hidden_layers _UpperCamelCase : str = num_attention_heads _UpperCamelCase : Dict = intermediate_size _UpperCamelCase : List[str] = hidden_act _UpperCamelCase : List[str] = hidden_dropout_prob _UpperCamelCase : str = attention_probs_dropout_prob _UpperCamelCase : Tuple = initializer_range _UpperCamelCase : List[str] = layer_norm_eps _UpperCamelCase : Tuple = image_size _UpperCamelCase : Tuple = patch_size _UpperCamelCase : Dict = num_channels _UpperCamelCase : Any = qkv_bias _UpperCamelCase : str = num_detection_tokens _UpperCamelCase : str = use_mid_position_embeddings _UpperCamelCase : List[str] = auxiliary_loss # Hungarian matcher _UpperCamelCase : List[Any] = class_cost _UpperCamelCase : int = bbox_cost _UpperCamelCase : Optional[int] = giou_cost # Loss coefficients _UpperCamelCase : List[Any] = bbox_loss_coefficient _UpperCamelCase : str = giou_loss_coefficient _UpperCamelCase : Dict = eos_coefficient class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[str] = version.parse("1.11" ) @property def __SCREAMING_SNAKE_CASE ( self : str ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> float: return 1e-4 @property def __SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return 12
51
0
"""simple docstring""" from __future__ import annotations lowerCamelCase__ = "Muhammad Umer Farooq" lowerCamelCase__ = "MIT" lowerCamelCase__ = "1.0.0" lowerCamelCase__ = "Muhammad Umer Farooq" lowerCamelCase__ = "contact@muhammadumerfarooq.me" lowerCamelCase__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' def __init__( self : List[Any] , __a : str ) -> None: super().__init__() _UpperCamelCase : list[str] = [] _UpperCamelCase : int = domain def __SCREAMING_SNAKE_CASE ( self : List[Any] , __a : str , __a : list[tuple[str, str | None]] ) -> None: # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: _UpperCamelCase : Union[str, Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def lowercase__ ( lowercase_ ) -> str: """simple docstring""" return ".".join(get_sub_domain_name(lowercase_ ).split("." )[-2:] ) def lowercase__ ( lowercase_ ) -> str: """simple docstring""" return parse.urlparse(lowercase_ ).netloc def lowercase__ ( lowercase_ = "https://github.com" ) -> list[str]: """simple docstring""" _UpperCamelCase : int = get_domain_name(lowercase_ ) # Initialize the parser _UpperCamelCase : Any = Parser(lowercase_ ) try: # Open URL _UpperCamelCase : Optional[int] = requests.get(lowercase_ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through _UpperCamelCase : Union[str, Any] = set() for link in parser.urls: # open URL. # read = requests.get(link) try: _UpperCamelCase : Optional[int] = requests.get(lowercase_ ) # Get the valid email. _UpperCamelCase : Union[str, Any] = re.findall("[a-zA-Z0-9]+@" + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(lowercase_ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(lowercase_ ) if __name__ == "__main__": lowerCamelCase__ = emails_from_url("https://github.com") print(f"""{len(emails)} emails found:""") print("\n".join(sorted(emails)))
708
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path lowerCamelCase__ = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) lowerCamelCase__ = [ord(letter) for letter in string.ascii_lowercase] lowerCamelCase__ = {ord(char) for char in VALID_CHARS} lowerCamelCase__ = ["the", "be", "to", "of", "and", "in", "that", "have"] def lowercase__ ( lowercase_ ,lowercase_ ) -> str | None: """simple docstring""" _UpperCamelCase : str = "" _UpperCamelCase : int _UpperCamelCase : int _UpperCamelCase : int for keychar, cipherchar in zip(cycle(lowercase_ ) ,lowercase_ ): _UpperCamelCase : Dict = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(lowercase_ ) return decoded def lowercase__ ( lowercase_ ) -> list[str]: """simple docstring""" _UpperCamelCase : list[str] = [] for key in product(lowercase_ ,repeat=3 ): _UpperCamelCase : int = try_key(lowercase_ ,lowercase_ ) if encoded is not None: possibles.append(lowercase_ ) return possibles def lowercase__ ( lowercase_ ,lowercase_ ) -> list[str]: """simple docstring""" return [possible for possible in possibles if common_word in possible.lower()] def lowercase__ ( lowercase_ = "p059_cipher.txt" ) -> int: """simple docstring""" _UpperCamelCase : list[int] _UpperCamelCase : list[str] _UpperCamelCase : str _UpperCamelCase : str _UpperCamelCase : str = Path(lowercase_ ).parent.joinpath(lowercase_ ).read_text(encoding="utf-8" ) _UpperCamelCase : Optional[Any] = [int(lowercase_ ) for number in data.strip().split("," )] _UpperCamelCase : List[str] = filter_valid_chars(lowercase_ ) for common_word in COMMON_WORDS: _UpperCamelCase : Union[str, Any] = filter_common_word(lowercase_ ,lowercase_ ) if len(lowercase_ ) == 1: break _UpperCamelCase : Union[str, Any] = possibles[0] return sum(ord(lowercase_ ) for char in decoded_text ) if __name__ == "__main__": print(f"""{solution() = }""")
51
0