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""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: # Base Case if index == len(_SCREAMING_SNAKE_CASE ): return True # Recursive Step for i in range(_SCREAMING_SNAKE_CASE ): if valid_coloring(graph[index] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Color current vertex snake_case_ = i # Validate coloring if util_color(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 ): return True # Backtrack snake_case_ = -1 return False def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = [-1] * len(_SCREAMING_SNAKE_CASE ) if util_color(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0 ): return colored_vertices return []
2
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 20 ) -> int: snake_case_ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... snake_case_ = n // 2 return int(factorial(_SCREAMING_SNAKE_CASE ) / (factorial(_SCREAMING_SNAKE_CASE ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: __SCREAMING_SNAKE_CASE : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
2
1
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__) def _a ( _SCREAMING_SNAKE_CASE ) -> Dict: snake_case_ = OrderedDict() for key, value in state_dict.items(): if key.startswith("""module.encoder""" ): snake_case_ = key.replace("""module.encoder""" , """glpn.encoder""" ) if key.startswith("""module.decoder""" ): snake_case_ = key.replace("""module.decoder""" , """decoder.stages""" ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 snake_case_ = key[key.find("""patch_embed""" ) + len("""patch_embed""" )] snake_case_ = key.replace(f"""patch_embed{idx}""" , f"""patch_embeddings.{int(_SCREAMING_SNAKE_CASE )-1}""" ) if "norm" in key: snake_case_ = key.replace("""norm""" , """layer_norm""" ) if "glpn.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 snake_case_ = key[key.find("""glpn.encoder.layer_norm""" ) + len("""glpn.encoder.layer_norm""" )] snake_case_ = key.replace(f"""layer_norm{idx}""" , f"""layer_norm.{int(_SCREAMING_SNAKE_CASE )-1}""" ) if "layer_norm1" in key: snake_case_ = key.replace("""layer_norm1""" , """layer_norm_1""" ) if "layer_norm2" in key: snake_case_ = key.replace("""layer_norm2""" , """layer_norm_2""" ) if "block" in key: # replace for example block1 by block.0 snake_case_ = key[key.find("""block""" ) + len("""block""" )] snake_case_ = key.replace(f"""block{idx}""" , f"""block.{int(_SCREAMING_SNAKE_CASE )-1}""" ) if "attn.q" in key: snake_case_ = key.replace("""attn.q""" , """attention.self.query""" ) if "attn.proj" in key: snake_case_ = key.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in key: snake_case_ = key.replace("""attn""" , """attention.self""" ) if "fc1" in key: snake_case_ = key.replace("""fc1""" , """dense1""" ) if "fc2" in key: snake_case_ = key.replace("""fc2""" , """dense2""" ) if "linear_pred" in key: snake_case_ = key.replace("""linear_pred""" , """classifier""" ) if "linear_fuse" in key: snake_case_ = key.replace("""linear_fuse.conv""" , """linear_fuse""" ) snake_case_ = key.replace("""linear_fuse.bn""" , """batch_norm""" ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 snake_case_ = key[key.find("""linear_c""" ) + len("""linear_c""" )] snake_case_ = key.replace(f"""linear_c{idx}""" , f"""linear_c.{int(_SCREAMING_SNAKE_CASE )-1}""" ) if "bot_conv" in key: snake_case_ = key.replace("""bot_conv""" , """0.convolution""" ) if "skip_conv1" in key: snake_case_ = key.replace("""skip_conv1""" , """1.convolution""" ) if "skip_conv2" in key: snake_case_ = key.replace("""skip_conv2""" , """2.convolution""" ) if "fusion1" in key: snake_case_ = key.replace("""fusion1""" , """1.fusion""" ) if "fusion2" in key: snake_case_ = key.replace("""fusion2""" , """2.fusion""" ) if "fusion3" in key: snake_case_ = key.replace("""fusion3""" , """3.fusion""" ) if "fusion" in key and "conv" in key: snake_case_ = key.replace("""conv""" , """convolutional_layer""" ) if key.startswith("""module.last_layer_depth""" ): snake_case_ = key.replace("""module.last_layer_depth""" , """head.head""" ) snake_case_ = value return new_state_dict def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: # for each of the encoder blocks: for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) snake_case_ = state_dict.pop(f"""glpn.encoder.block.{i}.{j}.attention.self.kv.weight""" ) snake_case_ = state_dict.pop(f"""glpn.encoder.block.{i}.{j}.attention.self.kv.bias""" ) # next, add keys and values (in that order) to the state dict snake_case_ = kv_weight[ : config.hidden_sizes[i], : ] snake_case_ = kv_bias[: config.hidden_sizes[i]] snake_case_ = kv_weight[ config.hidden_sizes[i] :, : ] snake_case_ = kv_bias[config.hidden_sizes[i] :] def _a ( ) -> str: snake_case_ = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return image @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=None ) -> Optional[Any]: snake_case_ = GLPNConfig(hidden_sizes=[64, 128, 320, 512] , decoder_hidden_size=64 , depths=[3, 8, 27, 3] ) # load image processor (only resize + rescale) snake_case_ = GLPNImageProcessor() # prepare image snake_case_ = prepare_img() snake_case_ = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values logger.info("""Converting model...""" ) # load original state dict snake_case_ = torch.load(_SCREAMING_SNAKE_CASE , map_location=torch.device("""cpu""" ) ) # rename keys snake_case_ = rename_keys(_SCREAMING_SNAKE_CASE ) # key and value matrices need special treatment read_in_k_v(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # create HuggingFace model and load state dict snake_case_ = GLPNForDepthEstimation(_SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) model.eval() # forward pass snake_case_ = model(_SCREAMING_SNAKE_CASE ) snake_case_ = outputs.predicted_depth # verify output if model_name is not None: if "nyu" in model_name: snake_case_ = torch.tensor( [[4.4147, 4.0873, 4.0673], [3.7890, 3.2881, 3.1525], [3.7674, 3.5423, 3.4913]] ) elif "kitti" in model_name: snake_case_ = torch.tensor( [[3.4291, 2.7865, 2.5151], [3.2841, 2.7021, 2.3502], [3.1147, 2.4625, 2.2481]] ) else: raise ValueError(f"""Unknown model name: {model_name}""" ) snake_case_ = torch.Size([1, 480, 640] ) assert predicted_depth.shape == expected_shape assert torch.allclose(predicted_depth[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) print("""Looks ok!""" ) # finally, push to hub if required if push_to_hub: logger.info("""Pushing model and image processor to the hub...""" ) model.push_to_hub( repo_path_or_name=Path(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , organization="""nielsr""" , commit_message="""Add model""" , use_temp_dir=_SCREAMING_SNAKE_CASE , ) image_processor.push_to_hub( repo_path_or_name=Path(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , organization="""nielsr""" , commit_message="""Add image processor""" , use_temp_dir=_SCREAMING_SNAKE_CASE , ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to upload the model to the HuggingFace hub.' ) parser.add_argument( '--model_name', default='glpn-kitti', type=str, help='Name of the model in case you\'re pushing to the hub.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_glpn_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
2
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _a ( _SCREAMING_SNAKE_CASE = 8 ) -> str: snake_case_ = ascii_letters + digits + punctuation return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(_SCREAMING_SNAKE_CASE ) snake_case_ = i // 3 snake_case_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case_ = ( chars_incl + random(_SCREAMING_SNAKE_CASE , quotient + remainder ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) snake_case_ = list(_SCREAMING_SNAKE_CASE ) shuffle(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) # random is a generalised function for letters, characters and numbers def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 8 ) -> bool: if len(_SCREAMING_SNAKE_CASE ) < min_length: # Your Password must be at least 8 characters long return False snake_case_ = any(char in ascii_uppercase for char in password ) snake_case_ = any(char in ascii_lowercase for char in password ) snake_case_ = any(char in digits for char in password ) snake_case_ = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _a ( ) -> str: snake_case_ = int(input("""Please indicate the max length of your password: """ ).strip() ) snake_case_ = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(_SCREAMING_SNAKE_CASE ) ) print( """Alternative Password generated:""" , alternative_password_generator(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
2
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __SCREAMING_SNAKE_CASE : List[Any] = { 'configuration_roberta': ['ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RobertaConfig', 'RobertaOnnxConfig'], 'tokenization_roberta': ['RobertaTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = ['RobertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : List[Any] = [ 'ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'RobertaForCausalLM', 'RobertaForMaskedLM', 'RobertaForMultipleChoice', 'RobertaForQuestionAnswering', 'RobertaForSequenceClassification', 'RobertaForTokenClassification', 'RobertaModel', 'RobertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : List[str] = [ 'TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRobertaForCausalLM', 'TFRobertaForMaskedLM', 'TFRobertaForMultipleChoice', 'TFRobertaForQuestionAnswering', 'TFRobertaForSequenceClassification', 'TFRobertaForTokenClassification', 'TFRobertaMainLayer', 'TFRobertaModel', 'TFRobertaPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[int] = [ 'FlaxRobertaForCausalLM', 'FlaxRobertaForMaskedLM', 'FlaxRobertaForMultipleChoice', 'FlaxRobertaForQuestionAnswering', 'FlaxRobertaForSequenceClassification', 'FlaxRobertaForTokenClassification', 'FlaxRobertaModel', 'FlaxRobertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset 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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=18 , UpperCAmelCase_ : Optional[Any]=30 , UpperCAmelCase_ : str=400 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[Any]=True , ) ->Optional[Any]: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = ImageGPTImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """clusters""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) snake_case_ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key] ) ) else: self.assertEqual(obj[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(UpperCAmelCase_ , """image_processor.json""" ) image_processor_first.to_json_file(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_json_file(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_pretrained(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" pass def _a ( ) -> str: snake_case_ = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) snake_case_ = Image.open(dataset[4]["""file"""] ) snake_case_ = Image.open(dataset[5]["""file"""] ) snake_case_ = [imagea, imagea] return images @require_vision @require_torch class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) snake_case_ = prepare_images() # test non-batched snake_case_ = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_024) ) snake_case_ = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_ ) # test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_024) ) snake_case_ = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_ )
2
1
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __SCREAMING_SNAKE_CASE : Any = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[str] = PegasusTokenizer __lowercase: List[Any] = PegasusTokenizerFast __lowercase: Optional[Any] = True __lowercase: Dict = True def lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing snake_case_ = PegasusTokenizer(UpperCAmelCase_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" return PegasusTokenizer.from_pretrained("""google/pegasus-large""" ) def lowerCAmelCase ( self : int , **UpperCAmelCase_ : List[str] ) ->PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Dict ) ->List[str]: """simple docstring""" return ("This is a test", "This is a test") def lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" snake_case_ = """</s>""" snake_case_ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_ ) , UpperCAmelCase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_ ) , UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" snake_case_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<pad>""" ) self.assertEqual(vocab_keys[1] , """</s>""" ) self.assertEqual(vocab_keys[-1] , """v""" ) self.assertEqual(len(UpperCAmelCase_ ) , 1_103 ) def lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_103 ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) snake_case_ = self.tokenizer_class.from_pretrained(self.tmpdirname ) snake_case_ = ( """Let's see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important""" """ </s> <pad> <pad> <pad>""" ) snake_case_ = rust_tokenizer([raw_input_str] , return_tensors=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ).input_ids[0] snake_case_ = py_tokenizer([raw_input_str] , return_tensors=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ).input_ids[0] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word snake_case_ = """<mask_1> To ensure a <mask_2> flow of bank resolutions.""" snake_case_ = [2, 413, 615, 114, 3, 1_971, 113, 1_679, 10_710, 107, 1] snake_case_ = tokenizer([raw_input_str] , return_tensors=UpperCAmelCase_ ).input_ids[0] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" snake_case_ = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 96_103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1_024 snake_case_ = """To ensure a smooth flow of bank resolutions.""" snake_case_ = [413, 615, 114, 2_291, 1_971, 113, 1_679, 10_710, 107, 1] snake_case_ = tokenizer([raw_input_str] , return_tensors=UpperCAmelCase_ ).input_ids[0] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def lowerCAmelCase ( self : Optional[Any] ) ->str: """simple docstring""" snake_case_ = ["""This is going to be way too long.""" * 150, """short example"""] snake_case_ = ["""not super long but more than 5 tokens""", """tiny"""] snake_case_ = self._large_tokenizer(UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , return_tensors="""pt""" ) snake_case_ = self._large_tokenizer( text_target=UpperCAmelCase_ , max_length=5 , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , return_tensors="""pt""" ) assert batch.input_ids.shape == (2, 1_024) assert batch.attention_mask.shape == (2, 1_024) assert targets["input_ids"].shape == (2, 5) assert len(UpperCAmelCase_ ) == 2 # input_ids, attention_mask. @slow def lowerCAmelCase ( self : str ) ->str: """simple docstring""" snake_case_ = {"""input_ids""": [[38_979, 143, 18_485, 606, 130, 26_669, 87_686, 121, 54_189, 1_129, 111, 26_669, 87_686, 121, 9_114, 14_787, 121, 13_249, 158, 592, 956, 121, 14_621, 31_576, 143, 62_613, 108, 9_688, 930, 43_430, 11_562, 62_613, 304, 108, 11_443, 897, 108, 9_314, 17_415, 63_399, 108, 11_443, 7_614, 18_316, 118, 4_284, 7_148, 12_430, 143, 1_400, 25_703, 158, 111, 4_284, 7_148, 11_772, 143, 21_297, 1_064, 158, 122, 204, 3_506, 1_754, 1_133, 14_787, 1_581, 115, 33_224, 4_482, 111, 1_355, 110, 29_173, 317, 50_833, 108, 20_147, 94_665, 111, 77_198, 107, 1], [110, 62_613, 117, 638, 112, 1_133, 121, 20_098, 1_355, 79_050, 13_872, 135, 1_596, 53_541, 1_352, 141, 13_039, 5_542, 124, 302, 518, 111, 268, 2_956, 115, 149, 4_427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1_235, 2_799, 18_289, 17_780, 204, 109, 9_474, 1_296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ , model_name="""google/bigbird-pegasus-large-arxiv""" , revision="""ba85d0851d708441f91440d509690f1ab6353415""" , ) @require_sentencepiece @require_tokenizers class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Tuple = PegasusTokenizer __lowercase: Tuple = PegasusTokenizerFast __lowercase: str = True __lowercase: Dict = True def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing snake_case_ = PegasusTokenizer(UpperCAmelCase_ , offset=0 , mask_token_sent=UpperCAmelCase_ , mask_token="""[MASK]""" ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" return PegasusTokenizer.from_pretrained("""google/bigbird-pegasus-large-arxiv""" ) def lowerCAmelCase ( self : List[str] , **UpperCAmelCase_ : Any ) ->PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] ) ->str: """simple docstring""" return ("This is a test", "This is a test") def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) snake_case_ = self.tokenizer_class.from_pretrained(self.tmpdirname ) snake_case_ = ( """Let's see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>""" """ <pad> <pad> <pad>""" ) snake_case_ = rust_tokenizer([raw_input_str] , return_tensors=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ).input_ids[0] snake_case_ = py_tokenizer([raw_input_str] , return_tensors=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ).input_ids[0] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) @require_torch def lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" snake_case_ = ["""This is going to be way too long.""" * 1_000, """short example"""] snake_case_ = ["""not super long but more than 5 tokens""", """tiny"""] snake_case_ = self._large_tokenizer(UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , return_tensors="""pt""" ) snake_case_ = self._large_tokenizer( text_target=UpperCAmelCase_ , max_length=5 , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , return_tensors="""pt""" ) assert batch.input_ids.shape == (2, 4_096) assert batch.attention_mask.shape == (2, 4_096) assert targets["input_ids"].shape == (2, 5) assert len(UpperCAmelCase_ ) == 2 # input_ids, attention_mask. def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" snake_case_ = ( """This is an example string that is used to test the original TF implementation against the HF""" """ implementation""" ) snake_case_ = self._large_tokenizer(UpperCAmelCase_ ).input_ids self.assertListEqual( UpperCAmelCase_ , [182, 117, 142, 587, 4_211, 120, 117, 263, 112, 804, 109, 856, 25_016, 3_137, 464, 109, 26_955, 3_137, 1] , )
2
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : Dict=24 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=1_000 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = scope snake_case_ = range_bbox def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = t if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = t snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->str: """simple docstring""" snake_case_ = LiltModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , ) ->Dict: """simple docstring""" snake_case_ = self.num_labels snake_case_ = LiltForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , ) ->Dict: """simple docstring""" snake_case_ = LiltForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowercase: Optional[Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: List[str] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ = LiltModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = LiltModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCAmelCase_ ) snake_case_ = torch.tensor([[1, 2]] , device=UpperCAmelCase_ ) snake_case_ = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ ) snake_case_ = torch.Size([1, 2, 768] ) snake_case_ = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=UpperCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase_ , atol=1E-3 ) )
2
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Dict = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class __A (snake_case__): '''simple docstring''' __lowercase: List[Any] = """realm""" def __init__( self : Optional[int] , UpperCAmelCase_ : str=30_522 , UpperCAmelCase_ : Any=768 , UpperCAmelCase_ : Optional[Any]=128 , UpperCAmelCase_ : int=12 , UpperCAmelCase_ : List[str]=12 , UpperCAmelCase_ : Union[str, Any]=8 , UpperCAmelCase_ : Optional[Any]=3_072 , UpperCAmelCase_ : str="gelu_new" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Optional[Any]=512 , UpperCAmelCase_ : Optional[int]=2 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : List[Any]=1E-12 , UpperCAmelCase_ : Optional[int]=256 , UpperCAmelCase_ : Optional[Any]=10 , UpperCAmelCase_ : Any=1E-3 , UpperCAmelCase_ : Tuple=5 , UpperCAmelCase_ : Optional[int]=320 , UpperCAmelCase_ : Dict=13_353_718 , UpperCAmelCase_ : List[str]=5_000 , UpperCAmelCase_ : Union[str, Any]=1 , UpperCAmelCase_ : Optional[Any]=0 , UpperCAmelCase_ : Tuple=2 , **UpperCAmelCase_ : List[Any] , ) ->Union[str, Any]: """simple docstring""" super().__init__(pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ ) # Common config snake_case_ = vocab_size snake_case_ = max_position_embeddings snake_case_ = hidden_size snake_case_ = retriever_proj_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = num_candidates snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = type_vocab_size snake_case_ = layer_norm_eps # Reader config snake_case_ = span_hidden_size snake_case_ = max_span_width snake_case_ = reader_layer_norm_eps snake_case_ = reader_beam_size snake_case_ = reader_seq_len # Retrieval config snake_case_ = num_block_records snake_case_ = searcher_beam_size
2
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
2
1
"""simple docstring""" import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) __SCREAMING_SNAKE_CASE : int = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation='relu') ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(32, (3, 3), activation='relu')) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=128, activation='relu')) classifier.add(layers.Dense(units=1, activation='sigmoid')) # Compiling the CNN classifier.compile( optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') __SCREAMING_SNAKE_CASE : List[str] = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) __SCREAMING_SNAKE_CASE : Any = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255) __SCREAMING_SNAKE_CASE : Tuple = train_datagen.flow_from_directory( 'dataset/training_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) __SCREAMING_SNAKE_CASE : Dict = test_datagen.flow_from_directory( 'dataset/test_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=30, validation_data=test_set ) classifier.save('cnn.h5') # Part 3 - Making new predictions __SCREAMING_SNAKE_CASE : Optional[int] = tf.keras.preprocessing.image.load_img( 'dataset/single_prediction/image.png', target_size=(64, 64) ) __SCREAMING_SNAKE_CASE : List[str] = tf.keras.preprocessing.image.img_to_array(test_image) __SCREAMING_SNAKE_CASE : List[str] = np.expand_dims(test_image, axis=0) __SCREAMING_SNAKE_CASE : Optional[int] = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: __SCREAMING_SNAKE_CASE : Dict = 'Normal' if result[0][0] == 1: __SCREAMING_SNAKE_CASE : int = 'Abnormality detected'
2
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
"""simple docstring""" import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class __A : '''simple docstring''' def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int ) ->List[Any]: """simple docstring""" return None class __A : '''simple docstring''' def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int ) ->Tuple: """simple docstring""" return None class __A (unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = [ # (model_name, model_kwargs) ("""bert-base-cased""", {}), ("""gpt2""", {"""use_cache""": False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def lowerCAmelCase ( self : Union[str, Any] ) ->str: """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(UpperCAmelCase_ , """tf""" , 12 , **UpperCAmelCase_ ) @require_torch @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(UpperCAmelCase_ , """pt""" , 12 , **UpperCAmelCase_ ) @require_torch @slow def lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" from transformers import BertModel snake_case_ = ["""[UNK]""", """[SEP]""", """[CLS]""", """[PAD]""", """[MASK]""", """some""", """other""", """words"""] with NamedTemporaryFile(mode="""w+t""" ) as vocab_file: vocab_file.write("""\n""".join(UpperCAmelCase_ ) ) vocab_file.flush() snake_case_ = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: snake_case_ = BertModel(BertConfig(vocab_size=len(UpperCAmelCase_ ) ) ) model.save_pretrained(UpperCAmelCase_ ) self._test_export(UpperCAmelCase_ , """pt""" , 12 , UpperCAmelCase_ ) @require_tf @slow def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ = self._test_export(UpperCAmelCase_ , """tf""" , 12 , **UpperCAmelCase_ ) snake_case_ = quantize(Path(UpperCAmelCase_ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(UpperCAmelCase_ ).stat().st_size: self.fail("""Quantized model is bigger than initial ONNX model""" ) @require_torch @slow def lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ = self._test_export(UpperCAmelCase_ , """pt""" , 12 , **UpperCAmelCase_ ) snake_case_ = quantize(UpperCAmelCase_ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(UpperCAmelCase_ ).stat().st_size: self.fail("""Quantized model is bigger than initial ONNX model""" ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict=None , **UpperCAmelCase_ : Optional[int] ) ->int: """simple docstring""" try: # Compute path with TemporaryDirectory() as tempdir: snake_case_ = Path(UpperCAmelCase_ ).joinpath("""model.onnx""" ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ ) return path except Exception as e: self.fail(UpperCAmelCase_ ) @require_torch @require_tokenizers @slow def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" from transformers import BertModel snake_case_ = BertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random""" ) ) snake_case_ = BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random""" ) self._test_infer_dynamic_axis(UpperCAmelCase_ , UpperCAmelCase_ , """pt""" ) @require_tf @require_tokenizers @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" from transformers import TFBertModel snake_case_ = TFBertModel(BertConfig.from_pretrained("""lysandre/tiny-bert-random""" ) ) snake_case_ = BertTokenizerFast.from_pretrained("""lysandre/tiny-bert-random""" ) self._test_infer_dynamic_axis(UpperCAmelCase_ , UpperCAmelCase_ , """tf""" ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int ) ->Union[str, Any]: """simple docstring""" snake_case_ = FeatureExtractionPipeline(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = ["""input_ids""", """token_type_ids""", """attention_mask""", """output_0""", """output_1"""] snake_case_ , snake_case_ , snake_case_ , snake_case_ = infer_shapes(UpperCAmelCase_ , UpperCAmelCase_ ) # Assert all variables are present self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , UpperCAmelCase_ ) self.assertSequenceEqual(variable_names[3:] , UpperCAmelCase_ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: """batch""", 1: """sequence"""} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes["""output_0"""] , {0: """batch""", 1: """sequence"""} ) self.assertDictEqual(shapes["""output_1"""] , {0: """batch"""} ) def lowerCAmelCase ( self : List[str] ) ->Tuple: """simple docstring""" snake_case_ = ["""input_ids""", """attention_mask""", """token_type_ids"""] snake_case_ = {"""input_ids""": [1, 2, 3, 4], """attention_mask""": [0, 0, 0, 0], """token_type_ids""": [1, 1, 1, 1]} snake_case_ , snake_case_ = ensure_valid_input(FuncContiguousArgs() , UpperCAmelCase_ , UpperCAmelCase_ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(UpperCAmelCase_ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(UpperCAmelCase_ ) , set(UpperCAmelCase_ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(UpperCAmelCase_ , (tokens["""input_ids"""], tokens["""token_type_ids"""], tokens["""attention_mask"""]) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) snake_case_ , snake_case_ = ensure_valid_input(FuncNonContiguousArgs() , UpperCAmelCase_ , UpperCAmelCase_ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(UpperCAmelCase_ ) , 1 ) self.assertEqual(len(UpperCAmelCase_ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens["""input_ids"""] ) self.assertEqual(ordered_input_names[0] , """input_ids""" ) def lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = generate_identified_filename(Path("""/home/something/my_fake_model.onnx""" ) , """-test""" ) self.assertEqual("""/home/something/my_fake_model-test.onnx""" , generated.as_posix() )
2
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" from __future__ import annotations from functools import lru_cache from math import ceil __SCREAMING_SNAKE_CASE : List[Any] = 100 __SCREAMING_SNAKE_CASE : Any = set(range(3, NUM_PRIMES, 2)) primes.add(2) __SCREAMING_SNAKE_CASE : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100 ) def _a ( _SCREAMING_SNAKE_CASE ) -> set[int]: if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} snake_case_ = set() snake_case_ = 42 snake_case_ = 42 for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def _a ( _SCREAMING_SNAKE_CASE = 5_000 ) -> int | None: for number_to_partition in range(1 , _SCREAMING_SNAKE_CASE ): if len(partition(_SCREAMING_SNAKE_CASE ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"""{solution() = }""")
2
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : List[str] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __SCREAMING_SNAKE_CASE : List[str] = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __SCREAMING_SNAKE_CASE : int = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[Any] = VOCAB_FILES_NAMES __lowercase: Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowercase: Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]="[CLS]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : str="<unk>" , UpperCAmelCase_ : str="[SEP]" , UpperCAmelCase_ : Optional[Any]="<pad>" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : int="[MASK]" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->None: """simple docstring""" snake_case_ = ( AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ , normalized=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token ) snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = do_lower_case snake_case_ = remove_space snake_case_ = keep_accents snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return len(self.sp_model ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Any ) ->str: """simple docstring""" if self.remove_space: snake_case_ = """ """.join(inputs.strip().split() ) else: snake_case_ = inputs snake_case_ = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: snake_case_ = unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) snake_case_ = """""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: snake_case_ = outputs.lower() return outputs def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.preprocess_text(UpperCAmelCase_ ) snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) snake_case_ = [] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): snake_case_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case_ = cur_pieces[1:] else: snake_case_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" return self.sp_model.PieceToId(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" return self.sp_model.IdToPiece(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Dict ) ->Any: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
2
1
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: if any(not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or x < 0 for x in sequence ): raise TypeError("""Sequence must be list of non-negative integers""" ) for _ in range(len(_SCREAMING_SNAKE_CASE ) ): for i, (rod_upper, rod_lower) in enumerate(zip(_SCREAMING_SNAKE_CASE , sequence[1:] ) ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
2
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""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() __SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) def _a ( _SCREAMING_SNAKE_CASE ) -> YolosConfig: snake_case_ = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: snake_case_ = 192 snake_case_ = 768 snake_case_ = 12 snake_case_ = 3 snake_case_ = [800, 1_333] snake_case_ = False elif yolos_name == "yolos_s_dWr": snake_case_ = 330 snake_case_ = 14 snake_case_ = 6 snake_case_ = 1_320 elif "yolos_s" in yolos_name: snake_case_ = 384 snake_case_ = 1_536 snake_case_ = 12 snake_case_ = 6 elif "yolos_b" in yolos_name: snake_case_ = [800, 1_344] snake_case_ = 91 snake_case_ = """huggingface/label-files""" snake_case_ = """coco-detection-id2label.json""" snake_case_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) snake_case_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} snake_case_ = idalabel snake_case_ = {v: k for k, v in idalabel.items()} return config def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = False ) -> Union[str, Any]: for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) snake_case_ = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case_ = in_proj_weight[: config.hidden_size, :] snake_case_ = in_proj_bias[: config.hidden_size] snake_case_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case_ = in_proj_weight[-config.hidden_size :, :] snake_case_ = in_proj_bias[-config.hidden_size :] def _a ( _SCREAMING_SNAKE_CASE ) -> str: if "backbone" in name: snake_case_ = name.replace("""backbone""" , """vit""" ) if "cls_token" in name: snake_case_ = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "det_token" in name: snake_case_ = name.replace("""det_token""" , """embeddings.detection_tokens""" ) if "mid_pos_embed" in name: snake_case_ = name.replace("""mid_pos_embed""" , """encoder.mid_position_embeddings""" ) if "pos_embed" in name: snake_case_ = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: snake_case_ = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "blocks" in name: snake_case_ = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: snake_case_ = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: snake_case_ = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: snake_case_ = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: snake_case_ = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: snake_case_ = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: snake_case_ = name.replace("""mlp.fc2""" , """output.dense""" ) if "class_embed" in name: snake_case_ = name.replace("""class_embed""" , """class_labels_classifier""" ) if "bbox_embed" in name: snake_case_ = name.replace("""bbox_embed""" , """bbox_predictor""" ) if "vit.norm" in name: snake_case_ = name.replace("""vit.norm""" , """vit.layernorm""" ) return name def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> dict: for key in orig_state_dict.copy().keys(): snake_case_ = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "qkv" in key: snake_case_ = key.split(""".""" ) snake_case_ = int(key_split[2] ) snake_case_ = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: snake_case_ = val[:dim, :] snake_case_ = val[ dim : dim * 2, : ] snake_case_ = val[-dim:, :] else: snake_case_ = val[:dim] snake_case_ = val[dim : dim * 2] snake_case_ = val[-dim:] else: snake_case_ = val return orig_state_dict def _a ( ) -> torch.Tensor: snake_case_ = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = False ) -> Any: snake_case_ = get_yolos_config(_SCREAMING_SNAKE_CASE ) # load original state_dict snake_case_ = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" )["""model"""] # load 🤗 model snake_case_ = YolosForObjectDetection(_SCREAMING_SNAKE_CASE ) model.eval() snake_case_ = convert_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) # Check outputs on an image, prepared by YolosImageProcessor snake_case_ = 800 if yolos_name != """yolos_ti""" else 512 snake_case_ = YolosImageProcessor(format="""coco_detection""" , size=_SCREAMING_SNAKE_CASE ) snake_case_ = image_processor(images=prepare_img() , return_tensors="""pt""" ) snake_case_ = model(**_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ = outputs.logits, outputs.pred_boxes snake_case_ , snake_case_ = None, None if yolos_name == "yolos_ti": snake_case_ = torch.tensor( [[-39.5022, -11.9820, -17.6888], [-29.9574, -9.9769, -17.7691], [-42.3281, -20.7200, -30.6294]] ) snake_case_ = 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": snake_case_ = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] ) snake_case_ = 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": snake_case_ = torch.tensor( [[-36.2220, -14.4385, -23.5457], [-35.6970, -14.7583, -21.3935], [-31.5939, -13.6042, -16.8049]] ) snake_case_ = 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": snake_case_ = torch.tensor( [[-42.8668, -24.1049, -41.1690], [-34.7456, -14.1274, -24.9194], [-33.7898, -12.1946, -25.6495]] ) snake_case_ = 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": snake_case_ = torch.tensor( [[-40.6064, -24.3084, -32.6447], [-55.1990, -30.7719, -35.5877], [-51.4311, -33.3507, -35.6462]] ) snake_case_ = 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] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) print(f"""Saving model {yolos_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if push_to_hub: snake_case_ = { """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...""" ) snake_case_ = model_mapping[yolos_name] image_processor.push_to_hub(_SCREAMING_SNAKE_CASE , organization="""hustvl""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE , organization="""hustvl""" ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = 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.' ) __SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
2
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=13 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=[10, 20, 30, 40] , UpperCAmelCase_ : List[Any]=[2, 2, 3, 2] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : int=["stage2", "stage3", "stage4"] , UpperCAmelCase_ : Optional[int]=[2, 3, 4] , UpperCAmelCase_ : List[str]=None , ) ->Union[str, Any]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = num_stages snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = out_features snake_case_ = out_indices snake_case_ = scope def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = ConvNextVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = ConvNextVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __lowercase: Union[str, Any] = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Optional[Any] = False __lowercase: Any = False __lowercase: Union[str, Any] = False __lowercase: Dict = False def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = True if model_class.__name__ in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ]: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = False snake_case_ = True if ( model_class.__name__ in [*get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ )] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ): snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ConvNextVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> str: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(UpperCAmelCase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = preprocessor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
2
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor __SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' def __init__( self : Dict , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Tuple ) ->None: """simple docstring""" warnings.warn( """The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use VideoMAEImageProcessor instead.""" , UpperCAmelCase_ , ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ )
2
"""simple docstring""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): '''simple docstring''' @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
2
1
"""simple docstring""" from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __A (snake_case__): '''simple docstring''' __lowercase: List[str] = ["""image_processor""", """tokenizer"""] __lowercase: List[Any] = """BlipImageProcessor""" __lowercase: Union[str, Any] = ("""BertTokenizer""", """BertTokenizerFast""") def __init__( self : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str ) ->Optional[Any]: """simple docstring""" snake_case_ = False super().__init__(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = self.image_processor def __call__( self : str , UpperCAmelCase_ : ImageInput = None , UpperCAmelCase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[bool, str, PaddingStrategy] = False , UpperCAmelCase_ : Union[bool, str, TruncationStrategy] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , **UpperCAmelCase_ : Tuple , ) ->BatchEncoding: """simple docstring""" if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: snake_case_ = self.tokenizer snake_case_ = self.tokenizer( text=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=UpperCAmelCase_ , stride=UpperCAmelCase_ , pad_to_multiple_of=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_overflowing_tokens=UpperCAmelCase_ , return_special_tokens_mask=UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , return_length=UpperCAmelCase_ , verbose=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ , ) return text_encoding # add pixel_values snake_case_ = self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ ) if text is not None: snake_case_ = self.tokenizer( text=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=UpperCAmelCase_ , stride=UpperCAmelCase_ , pad_to_multiple_of=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_overflowing_tokens=UpperCAmelCase_ , return_special_tokens_mask=UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , return_length=UpperCAmelCase_ , verbose=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ , ) else: snake_case_ = None if text_encoding is not None: encoding_image_processor.update(UpperCAmelCase_ ) return encoding_image_processor def lowerCAmelCase ( self : str , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Optional[Any] ) ->Optional[int]: """simple docstring""" return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : int , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : str ) ->List[Any]: """simple docstring""" return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->int: """simple docstring""" snake_case_ = self.tokenizer.model_input_names snake_case_ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
2
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=snake_case__) class __A (snake_case__): '''simple docstring''' __lowercase: str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True}) __lowercase: ClassVar[Features] = Features({"""audio""": Audio()}) __lowercase: ClassVar[Features] = Features({"""transcription""": Value("""string""")}) __lowercase: str = "audio" __lowercase: str = "transcription" def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , UpperCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) snake_case_ = copy.deepcopy(self ) snake_case_ = self.input_schema.copy() snake_case_ = features[self.audio_column] snake_case_ = input_schema return task_template @property def lowerCAmelCase ( self : List[str] ) ->Dict[str, str]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
2
1
"""simple docstring""" from heapq import heappop, heappush import numpy as np def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> tuple[float | int, list[tuple[int, int]]]: snake_case_ , snake_case_ = grid.shape snake_case_ = [-1, 1, 0, 0] snake_case_ = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] snake_case_ , snake_case_ = [(0, source)], set() snake_case_ = np.full((rows, cols) , np.inf ) snake_case_ = 0 snake_case_ = np.empty((rows, cols) , dtype=_SCREAMING_SNAKE_CASE ) snake_case_ = None while queue: ((snake_case_) , (snake_case_)) = heappop(_SCREAMING_SNAKE_CASE ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: snake_case_ = [] while (x, y) != source: path.append((x, y) ) snake_case_ , snake_case_ = predecessors[x, y] path.append(_SCREAMING_SNAKE_CASE ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ , snake_case_ = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: snake_case_ = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(_SCREAMING_SNAKE_CASE , (dist + 1, (nx, ny)) ) snake_case_ = dist + 1 snake_case_ = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
2
"""simple docstring""" from functools import reduce __SCREAMING_SNAKE_CASE : Tuple = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _a ( _SCREAMING_SNAKE_CASE = N ) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str(int(_SCREAMING_SNAKE_CASE ) * int(_SCREAMING_SNAKE_CASE ) ) , n[i : i + 13] ) ) for i in range(len(_SCREAMING_SNAKE_CASE ) - 12 ) ) if __name__ == "__main__": print(f"""{solution() = }""")
2
1
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
2
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str = { 'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json', # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class __A (snake_case__): '''simple docstring''' __lowercase: Any = """mctct""" def __init__( self : Dict , UpperCAmelCase_ : List[Any]=8_065 , UpperCAmelCase_ : Tuple=1_536 , UpperCAmelCase_ : Optional[Any]=36 , UpperCAmelCase_ : int=6_144 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Any=384 , UpperCAmelCase_ : List[str]=920 , UpperCAmelCase_ : Any=1E-5 , UpperCAmelCase_ : Any=0.3 , UpperCAmelCase_ : Tuple="relu" , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Dict=0.3 , UpperCAmelCase_ : str=0.3 , UpperCAmelCase_ : Any=1 , UpperCAmelCase_ : Any=0 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=0.3 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : Optional[Any]=(7,) , UpperCAmelCase_ : Optional[Any]=(3,) , UpperCAmelCase_ : List[str]=80 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[str]="sum" , UpperCAmelCase_ : Union[str, Any]=False , **UpperCAmelCase_ : Any , ) ->Dict: """simple docstring""" super().__init__(**UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = intermediate_size snake_case_ = num_attention_heads snake_case_ = attention_head_dim snake_case_ = max_position_embeddings snake_case_ = layer_norm_eps snake_case_ = layerdrop snake_case_ = hidden_act snake_case_ = initializer_range snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id snake_case_ = conv_glu_dim snake_case_ = conv_dropout snake_case_ = num_conv_layers snake_case_ = input_feat_per_channel snake_case_ = input_channels snake_case_ = conv_channels snake_case_ = ctc_loss_reduction snake_case_ = ctc_zero_infinity # prevents config testing fail with exporting to json snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """ F"""but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, """ F"""`config.num_conv_layers = {self.num_conv_layers}`.""" )
2
1
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> str: return "".join([hex(_SCREAMING_SNAKE_CASE )[2:].zfill(2 ).upper() for byte in list(_SCREAMING_SNAKE_CASE )] ) def _a ( _SCREAMING_SNAKE_CASE ) -> bytes: # Check data validity, following RFC3548 # https://www.ietf.org/rfc/rfc3548.txt if (len(_SCREAMING_SNAKE_CASE ) % 2) != 0: raise ValueError( """Base16 encoded data is invalid: Data does not have an even number of hex digits.""" ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(_SCREAMING_SNAKE_CASE ) <= set("""0123456789ABCDEF""" ): raise ValueError( """Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters.""" ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(_SCREAMING_SNAKE_CASE ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
2
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 100 ) -> int: return sum(int(_SCREAMING_SNAKE_CASE ) for x in str(factorial(_SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
2
1
"""simple docstring""" __SCREAMING_SNAKE_CASE : Any = 256 # Modulus to hash a string __SCREAMING_SNAKE_CASE : int = 1_000_003 def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: snake_case_ = len(_SCREAMING_SNAKE_CASE ) snake_case_ = len(_SCREAMING_SNAKE_CASE ) if p_len > t_len: return False snake_case_ = 0 snake_case_ = 0 snake_case_ = 1 # Calculating the hash of pattern and substring of text for i in range(_SCREAMING_SNAKE_CASE ): snake_case_ = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus snake_case_ = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue snake_case_ = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash snake_case_ = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def _a ( ) -> None: snake_case_ = """abc1abc12""" snake_case_ = """alskfjaldsabc1abc1abc12k23adsfabcabc""" snake_case_ = """alskfjaldsk23adsfabcabc""" assert rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and not rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Test 2) snake_case_ = """ABABX""" snake_case_ = """ABABZABABYABABX""" assert rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Test 3) snake_case_ = """AAAB""" snake_case_ = """ABAAAAAB""" assert rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Test 4) snake_case_ = """abcdabcy""" snake_case_ = """abcxabcdabxabcdabcdabcy""" assert rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Test 5) snake_case_ = """Lü""" snake_case_ = """Lüsai""" assert rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = """Lue""" assert not rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print("""Success.""" ) if __name__ == "__main__": test_rabin_karp()
2
"""simple docstring""" import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: str = VQModel __lowercase: Union[str, Any] = """sample""" @property def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[str]=(32, 32) ) ->Tuple: """simple docstring""" snake_case_ = 4 snake_case_ = 3 snake_case_ = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase_ ) return {"sample": image} @property def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" return (3, 32, 32) @property def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" return (3, 32, 32) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } snake_case_ = self.dummy_input return init_dict, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(UpperCAmelCase_ ) snake_case_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(UpperCAmelCase_ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) snake_case_ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) snake_case_ = image.to(UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = model(UpperCAmelCase_ ).sample snake_case_ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off snake_case_ = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 ) )
2
1
"""simple docstring""" import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(snake_case__) , """Tatoeba directory does not exist.""") class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Tuple ) ->Optional[int]: """simple docstring""" snake_case_ = tempfile.mkdtemp() return TatoebaConverter(save_dir=UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" self.resolver.convert_models(["""heb-eng"""] ) @slow def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ , snake_case_ = self.resolver.write_model_card("""opus-mt-he-en""" , dry_run=UpperCAmelCase_ ) assert mmeta["long_pair"] == "heb-eng"
2
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = KandinskyVaaControlnetPipeline __lowercase: str = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: Union[str, Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowercase: Tuple = False @property def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return 100 @property def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) snake_case_ = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } snake_case_ = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=UpperCAmelCase_ , ) snake_case_ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]=0 ) ->List[str]: """simple docstring""" snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) # create hint snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("""mps""" ): snake_case_ = torch.manual_seed(UpperCAmelCase_ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) snake_case_ = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" snake_case_ = """cpu""" snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**UpperCAmelCase_ ) snake_case_ = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) snake_case_ = torch.from_numpy(np.array(UpperCAmelCase_ ) ).float() / 255.0 snake_case_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case_ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) snake_case_ = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = """A robot, 4k photo""" snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ , snake_case_ = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , hint=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
2
1
"""simple docstring""" from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __A : '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str=2 , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : Union[str, Any]=4 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Dict=7 , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Tuple=99 , UpperCAmelCase_ : Optional[int]=36 , UpperCAmelCase_ : Tuple=2 , UpperCAmelCase_ : Tuple=4 , UpperCAmelCase_ : Dict=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Optional[int]=512 , UpperCAmelCase_ : Optional[int]=16 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : Tuple=6 , UpperCAmelCase_ : Tuple=6 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Union[str, Any]=4 , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : List[Any]=1_000 , ) ->Dict: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = patch_size snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = coordinate_size snake_case_ = shape_size snake_case_ = num_labels snake_case_ = num_choices snake_case_ = scope snake_case_ = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) snake_case_ = text_seq_length snake_case_ = (image_size // patch_size) ** 2 + 1 snake_case_ = self.text_seq_length + self.image_seq_length def lowerCAmelCase ( self : str ) ->List[str]: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) snake_case_ = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = tmp_coordinate snake_case_ = tf.constant(UpperCAmelCase_ ) snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_input_mask: snake_case_ = random_attention_mask([self.batch_size, self.text_seq_length] ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) snake_case_ = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = TFLayoutLMvaModel(config=UpperCAmelCase_ ) # text + image snake_case_ = model(UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , training=UpperCAmelCase_ ) snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , training=UpperCAmelCase_ , ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , training=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only snake_case_ = model(UpperCAmelCase_ , training=UpperCAmelCase_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only snake_case_ = model({"""pixel_values""": pixel_values} , training=UpperCAmelCase_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : Dict ) ->Optional[int]: """simple docstring""" snake_case_ = self.num_labels snake_case_ = TFLayoutLMvaForSequenceClassification(config=UpperCAmelCase_ ) snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , training=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict ) ->int: """simple docstring""" snake_case_ = self.num_labels snake_case_ = TFLayoutLMvaForTokenClassification(config=UpperCAmelCase_ ) snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , training=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) ->Union[str, Any]: """simple docstring""" snake_case_ = 2 snake_case_ = TFLayoutLMvaForQuestionAnswering(config=UpperCAmelCase_ ) snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , training=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : Union[str, Any] ) ->str: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ((snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_)) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_tf class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __lowercase: Optional[int] = ( {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel} if is_tf_available() else {} ) __lowercase: Any = False __lowercase: List[str] = False __lowercase: Optional[int] = False def lowerCAmelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str]=False ) ->dict: """simple docstring""" snake_case_ = copy.deepcopy(UpperCAmelCase_ ) if model_class in get_values(UpperCAmelCase_ ): snake_case_ = { k: tf.tile(tf.expand_dims(UpperCAmelCase_ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(UpperCAmelCase_ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(UpperCAmelCase_ ): snake_case_ = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(UpperCAmelCase_ ): snake_case_ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) snake_case_ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(UpperCAmelCase_ ): snake_case_ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(UpperCAmelCase_ ): snake_case_ = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = TFLayoutLMvaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : Tuple ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) if getattr(UpperCAmelCase_ , """hf_compute_loss""" , UpperCAmelCase_ ): # The number of elements in the loss should be the same as the number of elements in the label snake_case_ = self._prepare_for_class(inputs_dict.copy() , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=UpperCAmelCase_ )[0] ] snake_case_ = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs snake_case_ = self._prepare_for_class(inputs_dict.copy() , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = prepared_for_class.pop("""input_ids""" ) snake_case_ = model(UpperCAmelCase_ , **UpperCAmelCase_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions snake_case_ = self._prepare_for_class(inputs_dict.copy() , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = prepared_for_class.pop("""input_ids""" ) if "labels" in prepared_for_class: snake_case_ = prepared_for_class["""labels"""].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: snake_case_ = -100 snake_case_ = tf.convert_to_tensor(UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , **UpperCAmelCase_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict snake_case_ = self._prepare_for_class(inputs_dict.copy() , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple snake_case_ = self._prepare_for_class(inputs_dict.copy() , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) # Get keys that were added with the _prepare_for_class function snake_case_ = prepared_for_class.keys() - inputs_dict.keys() snake_case_ = inspect.signature(model.call ).parameters snake_case_ = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple snake_case_ = {0: """input_ids"""} for label_key in label_keys: snake_case_ = signature_names.index(UpperCAmelCase_ ) snake_case_ = label_key snake_case_ = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple snake_case_ = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: snake_case_ = prepared_for_class[value] snake_case_ = tuple(UpperCAmelCase_ ) # Send to model snake_case_ = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[Any]: """simple docstring""" ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Optional[Any] ) ->Optional[Any]: """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = TFLayoutLMvaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> Any: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase_ ) if is_vision_available() else None @slow def lowerCAmelCase ( self : List[Any] ) ->List[Any]: """simple docstring""" snake_case_ = TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(images=UpperCAmelCase_ , return_tensors="""tf""" ).pixel_values snake_case_ = tf.constant([[1, 2]] ) snake_case_ = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ , pixel_values=UpperCAmelCase_ , training=UpperCAmelCase_ ) # verify the logits snake_case_ = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , UpperCAmelCase_ ) snake_case_ = tf.constant( [[-0.0_529, 0.3_618, 0.1_632], [-0.1_587, -0.1_667, -0.0_400], [-0.1_557, -0.1_671, -0.0_505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
2
"""simple docstring""" from __future__ import annotations from collections import deque class __A : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : list[str] ) ->List[Any]: """simple docstring""" snake_case_ = [] self.adlist.append( {"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} ) for keyword in keywords: self.add_keyword(UpperCAmelCase_ ) self.set_fail_transitions() def lowerCAmelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : str ) ->int | None: """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def lowerCAmelCase ( self : int , UpperCAmelCase_ : str ) ->None: """simple docstring""" snake_case_ = 0 for character in keyword: snake_case_ = self.find_next_state(UpperCAmelCase_ , UpperCAmelCase_ ) if next_state is None: self.adlist.append( { """value""": character, """next_states""": [], """fail_state""": 0, """output""": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) snake_case_ = len(self.adlist ) - 1 else: snake_case_ = next_state self.adlist[current_state]["output"].append(UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->None: """simple docstring""" snake_case_ = deque() for node in self.adlist[0]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = 0 while q: snake_case_ = q.popleft() for child in self.adlist[r]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = self.adlist[r]["""fail_state"""] while ( self.find_next_state(UpperCAmelCase_ , self.adlist[child]["""value"""] ) is None and state != 0 ): snake_case_ = self.adlist[state]["""fail_state"""] snake_case_ = self.find_next_state( UpperCAmelCase_ , self.adlist[child]["""value"""] ) if self.adlist[child]["fail_state"] is None: snake_case_ = 0 snake_case_ = ( self.adlist[child]["""output"""] + self.adlist[self.adlist[child]["""fail_state"""]]["""output"""] ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->dict[str, list[int]]: """simple docstring""" snake_case_ = {} # returns a dict with keywords and list of its occurrences snake_case_ = 0 for i in range(len(UpperCAmelCase_ ) ): while ( self.find_next_state(UpperCAmelCase_ , string[i] ) is None and current_state != 0 ): snake_case_ = self.adlist[current_state]["""fail_state"""] snake_case_ = self.find_next_state(UpperCAmelCase_ , string[i] ) if next_state is None: snake_case_ = 0 else: snake_case_ = next_state for key in self.adlist[current_state]["output"]: if key not in result: snake_case_ = [] result[key].append(i - len(UpperCAmelCase_ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import numpy as np def _a ( _SCREAMING_SNAKE_CASE ) -> np.array: return (2 / (1 + np.exp(-2 * vector ))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
2
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=13 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=[10, 20, 30, 40] , UpperCAmelCase_ : List[Any]=[2, 2, 3, 2] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : int=["stage2", "stage3", "stage4"] , UpperCAmelCase_ : Optional[int]=[2, 3, 4] , UpperCAmelCase_ : List[str]=None , ) ->Union[str, Any]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = num_stages snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = out_features snake_case_ = out_indices snake_case_ = scope def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = ConvNextVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = ConvNextVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __lowercase: Union[str, Any] = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Optional[Any] = False __lowercase: Any = False __lowercase: Union[str, Any] = False __lowercase: Dict = False def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = True if model_class.__name__ in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ]: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = False snake_case_ = True if ( model_class.__name__ in [*get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ )] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ): snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ConvNextVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> str: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(UpperCAmelCase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = preprocessor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
2
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' def __init__( self : Dict , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Union[str, Any] ) ->None: """simple docstring""" warnings.warn( """The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use MobileViTImageProcessor instead.""" , UpperCAmelCase_ , ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ )
2
"""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() __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : int = ['model.decoder.embed_positions.weights'] def _a ( _SCREAMING_SNAKE_CASE ) -> str: if "emb" in name: snake_case_ = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: snake_case_ = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: snake_case_ = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: snake_case_ = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: snake_case_ = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: snake_case_ = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: snake_case_ = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: snake_case_ = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: snake_case_ = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: snake_case_ = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: snake_case_ = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple[Dict, Dict]: snake_case_ = list(state_dict.keys() ) snake_case_ = {} for key in keys: snake_case_ = state_dict.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = rename_keys(_SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj snake_case_ = val[:hidden_size, :] snake_case_ = val[hidden_size : 2 * hidden_size, :] snake_case_ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: snake_case_ = val else: snake_case_ = val return state_dict, enc_dec_proj_state_dict def _a ( _SCREAMING_SNAKE_CASE ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values snake_case_ = 1_024 snake_case_ = 24 snake_case_ = 16 elif checkpoint == "medium": snake_case_ = 1_536 snake_case_ = 48 snake_case_ = 24 elif checkpoint == "large": snake_case_ = 2_048 snake_case_ = 48 snake_case_ = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) snake_case_ = MusicgenDecoderConfig( hidden_size=_SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=_SCREAMING_SNAKE_CASE , num_attention_heads=_SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="cpu" ) -> Tuple: snake_case_ = MusicGen.get_pretrained(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) snake_case_ = decoder_config_from_checkpoint(_SCREAMING_SNAKE_CASE ) snake_case_ = fairseq_model.lm.state_dict() snake_case_ , snake_case_ = rename_state_dict( _SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) snake_case_ = TaEncoderModel.from_pretrained("""t5-base""" ) snake_case_ = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) snake_case_ = MusicgenForCausalLM(_SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection snake_case_ , snake_case_ = decoder.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model snake_case_ = MusicgenForConditionalGeneration(text_encoder=_SCREAMING_SNAKE_CASE , audio_encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_SCREAMING_SNAKE_CASE ) # check we can do a forward pass snake_case_ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) snake_case_ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): snake_case_ = model(input_ids=_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor snake_case_ = AutoTokenizer.from_pretrained("""t5-base""" ) snake_case_ = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) snake_case_ = MusicgenProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids snake_case_ = 2_048 snake_case_ = 2_048 # set other default generation config params snake_case_ = int(30 * audio_encoder.config.frame_rate ) snake_case_ = True snake_case_ = 3.0 if pytorch_dump_folder is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) processor.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = 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.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
2
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[int] = {'configuration_wavlm': ['WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'WavLMConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : int = [ 'WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'WavLMForAudioFrameClassification', 'WavLMForCTC', 'WavLMForSequenceClassification', 'WavLMForXVector', 'WavLMModel', 'WavLMPreTrainedModel', ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: if index == number_of_items: return 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 ) if weights[index] <= max_weight: snake_case_ = values[index] + knapsack( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 ) return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer __SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE : Any = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } __SCREAMING_SNAKE_CASE : int = { 'YituTech/conv-bert-base': 512, 'YituTech/conv-bert-medium-small': 512, 'YituTech/conv-bert-small': 512, } __SCREAMING_SNAKE_CASE : int = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class __A (snake_case__): '''simple docstring''' __lowercase: Tuple = VOCAB_FILES_NAMES __lowercase: int = PRETRAINED_VOCAB_FILES_MAP __lowercase: Dict = PRETRAINED_INIT_CONFIGURATION __lowercase: Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase: Dict = ConvBertTokenizer def __init__( self : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Tuple="[PAD]" , UpperCAmelCase_ : Dict="[CLS]" , UpperCAmelCase_ : Any="[MASK]" , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Any=None , **UpperCAmelCase_ : Dict , ) ->Tuple: """simple docstring""" super().__init__( UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , tokenize_chinese_chars=UpperCAmelCase_ , strip_accents=UpperCAmelCase_ , **UpperCAmelCase_ , ) snake_case_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , UpperCAmelCase_ ) != do_lower_case or normalizer_state.get("""strip_accents""" , UpperCAmelCase_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , UpperCAmelCase_ ) != tokenize_chinese_chars ): snake_case_ = getattr(UpperCAmelCase_ , normalizer_state.pop("""type""" ) ) snake_case_ = do_lower_case snake_case_ = strip_accents snake_case_ = tokenize_chinese_chars snake_case_ = normalizer_class(**UpperCAmelCase_ ) snake_case_ = do_lower_case def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int=None ) ->List[Any]: """simple docstring""" snake_case_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" snake_case_ = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ )
2
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 20 ) -> int: snake_case_ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... snake_case_ = n // 2 return int(factorial(_SCREAMING_SNAKE_CASE ) / (factorial(_SCREAMING_SNAKE_CASE ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: __SCREAMING_SNAKE_CASE : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
2
1
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[Any] = { 'microsoft/unispeech-sat-base-100h-libri-ft': ( 'https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json' ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class __A (snake_case__): '''simple docstring''' __lowercase: int = """unispeech-sat""" def __init__( self : int , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : Optional[Any]=768 , UpperCAmelCase_ : Dict=12 , UpperCAmelCase_ : Tuple=12 , UpperCAmelCase_ : Optional[int]=3_072 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Optional[Any]=0.0 , UpperCAmelCase_ : str=0.0 , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : Union[str, Any]=1E-5 , UpperCAmelCase_ : Any="group" , UpperCAmelCase_ : Tuple="gelu" , UpperCAmelCase_ : List[str]=(512, 512, 512, 512, 512, 512, 512) , UpperCAmelCase_ : List[str]=(5, 2, 2, 2, 2, 2, 2) , UpperCAmelCase_ : List[str]=(10, 3, 3, 3, 3, 2, 2) , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Dict=128 , UpperCAmelCase_ : Union[str, Any]=16 , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Dict=0.05 , UpperCAmelCase_ : List[Any]=10 , UpperCAmelCase_ : List[Any]=2 , UpperCAmelCase_ : Any=0.0 , UpperCAmelCase_ : List[Any]=10 , UpperCAmelCase_ : Dict=0 , UpperCAmelCase_ : str=320 , UpperCAmelCase_ : Optional[Any]=2 , UpperCAmelCase_ : Dict=0.1 , UpperCAmelCase_ : List[str]=100 , UpperCAmelCase_ : Any=256 , UpperCAmelCase_ : List[Any]=256 , UpperCAmelCase_ : Dict=0.1 , UpperCAmelCase_ : Any="mean" , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Dict=False , UpperCAmelCase_ : Optional[Any]=256 , UpperCAmelCase_ : Optional[Any]=(512, 512, 512, 512, 1_500) , UpperCAmelCase_ : Optional[Any]=(5, 3, 3, 1, 1) , UpperCAmelCase_ : Dict=(1, 2, 3, 1, 1) , UpperCAmelCase_ : str=512 , UpperCAmelCase_ : int=0 , UpperCAmelCase_ : Any=1 , UpperCAmelCase_ : Any=2 , UpperCAmelCase_ : Tuple=504 , **UpperCAmelCase_ : str , ) ->Any: """simple docstring""" super().__init__(**UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ ) snake_case_ = hidden_size snake_case_ = feat_extract_norm snake_case_ = feat_extract_activation snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) snake_case_ = conv_bias snake_case_ = num_conv_pos_embeddings snake_case_ = num_conv_pos_embedding_groups snake_case_ = len(self.conv_dim ) snake_case_ = num_hidden_layers snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_attention_heads snake_case_ = hidden_dropout snake_case_ = attention_dropout snake_case_ = activation_dropout snake_case_ = feat_proj_dropout snake_case_ = final_dropout snake_case_ = layerdrop snake_case_ = layer_norm_eps snake_case_ = initializer_range snake_case_ = vocab_size snake_case_ = num_clusters snake_case_ = do_stable_layer_norm snake_case_ = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" F""" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 snake_case_ = apply_spec_augment snake_case_ = mask_time_prob snake_case_ = mask_time_length snake_case_ = mask_time_min_masks snake_case_ = mask_feature_prob snake_case_ = mask_feature_length snake_case_ = mask_feature_min_masks # parameters for pretraining with codevector quantized representations snake_case_ = num_codevectors_per_group snake_case_ = num_codevector_groups snake_case_ = contrastive_logits_temperature snake_case_ = feat_quantizer_dropout snake_case_ = num_negatives snake_case_ = codevector_dim snake_case_ = proj_codevector_dim snake_case_ = diversity_loss_weight # ctc loss snake_case_ = ctc_loss_reduction snake_case_ = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. snake_case_ = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) snake_case_ = xvector_output_dim @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
2
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _a ( _SCREAMING_SNAKE_CASE = 8 ) -> str: snake_case_ = ascii_letters + digits + punctuation return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(_SCREAMING_SNAKE_CASE ) snake_case_ = i // 3 snake_case_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case_ = ( chars_incl + random(_SCREAMING_SNAKE_CASE , quotient + remainder ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) snake_case_ = list(_SCREAMING_SNAKE_CASE ) shuffle(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) # random is a generalised function for letters, characters and numbers def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 8 ) -> bool: if len(_SCREAMING_SNAKE_CASE ) < min_length: # Your Password must be at least 8 characters long return False snake_case_ = any(char in ascii_uppercase for char in password ) snake_case_ = any(char in ascii_lowercase for char in password ) snake_case_ = any(char in digits for char in password ) snake_case_ = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _a ( ) -> str: snake_case_ = int(input("""Please indicate the max length of your password: """ ).strip() ) snake_case_ = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(_SCREAMING_SNAKE_CASE ) ) print( """Alternative Password generated:""" , alternative_password_generator(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
2
1
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: if len(_SCREAMING_SNAKE_CASE ) == 0: return False snake_case_ = len(_SCREAMING_SNAKE_CASE ) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint] , _SCREAMING_SNAKE_CASE ) else: return binary_search(a_list[midpoint + 1 :] , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[str] = input('Enter numbers separated by comma:\n').strip() __SCREAMING_SNAKE_CASE : Tuple = [int(item.strip()) for item in user_input.split(',')] __SCREAMING_SNAKE_CASE : Union[str, Any] = int(input('Enter the number to be found in the list:\n').strip()) __SCREAMING_SNAKE_CASE : int = '' if binary_search(sequence, target) else 'not ' print(f"""{target} was {not_str}found in {sequence}""")
2
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset 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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=18 , UpperCAmelCase_ : Optional[Any]=30 , UpperCAmelCase_ : str=400 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[Any]=True , ) ->Optional[Any]: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = ImageGPTImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """clusters""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) snake_case_ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key] ) ) else: self.assertEqual(obj[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(UpperCAmelCase_ , """image_processor.json""" ) image_processor_first.to_json_file(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_json_file(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_pretrained(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" pass def _a ( ) -> str: snake_case_ = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) snake_case_ = Image.open(dataset[4]["""file"""] ) snake_case_ = Image.open(dataset[5]["""file"""] ) snake_case_ = [imagea, imagea] return images @require_vision @require_torch class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) snake_case_ = prepare_images() # test non-batched snake_case_ = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_024) ) snake_case_ = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_ ) # test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_024) ) snake_case_ = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_ )
2
1
"""simple docstring""" from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("""repo_id""" , ["""canonical_dataset_name""", """org-name/dataset-name"""] ) @pytest.mark.parametrize("""path""" , ["""filename.csv""", """filename with blanks.csv"""] ) @pytest.mark.parametrize("""revision""" , [None, """v2"""] ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: snake_case_ = hf_hub_url(repo_id=_SCREAMING_SNAKE_CASE , path=_SCREAMING_SNAKE_CASE , revision=_SCREAMING_SNAKE_CASE ) assert url == f"""https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(_SCREAMING_SNAKE_CASE )}"""
2
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : Dict=24 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=1_000 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = scope snake_case_ = range_bbox def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = t if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = t snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->str: """simple docstring""" snake_case_ = LiltModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , ) ->Dict: """simple docstring""" snake_case_ = self.num_labels snake_case_ = LiltForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , ) ->Dict: """simple docstring""" snake_case_ = LiltForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowercase: Optional[Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: List[str] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ = LiltModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = LiltModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCAmelCase_ ) snake_case_ = torch.tensor([[1, 2]] , device=UpperCAmelCase_ ) snake_case_ = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ ) snake_case_ = torch.Size([1, 2, 768] ) snake_case_ = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=UpperCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase_ , atol=1E-3 ) )
2
1
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE = 4 ) -> list[list[int]]: snake_case_ = abs(_SCREAMING_SNAKE_CASE ) or 4 return [[1 + x + y * row_size for x in range(_SCREAMING_SNAKE_CASE )] for y in range(_SCREAMING_SNAKE_CASE )] def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: return reverse_row(transpose(_SCREAMING_SNAKE_CASE ) ) # OR.. transpose(reverse_column(matrix)) def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: return reverse_row(reverse_column(_SCREAMING_SNAKE_CASE ) ) # OR.. reverse_column(reverse_row(matrix)) def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: return reverse_column(transpose(_SCREAMING_SNAKE_CASE ) ) # OR.. transpose(reverse_row(matrix)) def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: snake_case_ = [list(_SCREAMING_SNAKE_CASE ) for x in zip(*_SCREAMING_SNAKE_CASE )] return matrix def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: snake_case_ = matrix[::-1] return matrix def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: snake_case_ = [x[::-1] for x in matrix] return matrix def _a ( _SCREAMING_SNAKE_CASE ) -> None: for i in matrix: print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : int = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 90 counterclockwise:\n') print_matrix(rotate_aa(matrix)) __SCREAMING_SNAKE_CASE : Tuple = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 180:\n') print_matrix(rotate_aaa(matrix)) __SCREAMING_SNAKE_CASE : Optional[int] = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 270 counterclockwise:\n') print_matrix(rotate_aaa(matrix))
2
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
2
1
"""simple docstring""" import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __SCREAMING_SNAKE_CASE : int = logging.getLogger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , ) -> Union[str, Any]: snake_case_ = bnb_quantization_config.load_in_abit snake_case_ = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( """You have a version of `bitsandbytes` that is not compatible with 8bit quantization,""" """ make sure you have the latest version of `bitsandbytes` installed.""" ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( """You have a version of `bitsandbytes` that is not compatible with 4bit quantization,""" """make sure you have the latest version of `bitsandbytes` installed.""" ) snake_case_ = [] # custom device map if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(device_map.keys() ) > 1: snake_case_ = [key for key, value in device_map.items() if value in ["""disk""", """cpu"""]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: snake_case_ = get_keys_to_not_convert(_SCREAMING_SNAKE_CASE ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(_SCREAMING_SNAKE_CASE ) snake_case_ = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: snake_case_ = [] snake_case_ = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(_SCREAMING_SNAKE_CASE ) # compatibility with peft snake_case_ = load_in_abit snake_case_ = load_in_abit snake_case_ = get_parameter_device(_SCREAMING_SNAKE_CASE ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( """It is not recommended to quantize a loaded model. """ """The model should be instantiated under the `init_empty_weights` context manager.""" ) snake_case_ = replace_with_bnb_layers(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE ) # convert param to the right dtype snake_case_ = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: snake_case_ = name.replace(""".weight""" , """""" ).replace(""".bias""" , """""" ) snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(_SCREAMING_SNAKE_CASE ): param.to(_SCREAMING_SNAKE_CASE ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info( f"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" """We move the model to cuda.""" ) return model elif weights_location is None: raise RuntimeError( f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): snake_case_ = replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE ) snake_case_ = get_quantized_model_device_map( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_memory=_SCREAMING_SNAKE_CASE , no_split_module_classes=_SCREAMING_SNAKE_CASE , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): snake_case_ = True snake_case_ = any(x in list(device_map.values() ) for x in ["""cpu""", """disk"""] ) load_checkpoint_in_model( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=bnb_quantization_config.torch_dtype , offload_folder=_SCREAMING_SNAKE_CASE , offload_state_dict=_SCREAMING_SNAKE_CASE , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(_SCREAMING_SNAKE_CASE , device_map=_SCREAMING_SNAKE_CASE , offload_dir=_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[Any]: if device_map is None: if torch.cuda.is_available(): snake_case_ = {"""""": torch.cuda.current_device()} else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`.""" ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( """If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """ """'sequential'.""" ) snake_case_ = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) snake_case_ = {} snake_case_ = special_dtypes snake_case_ = no_split_module_classes snake_case_ = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": snake_case_ = get_balanced_memory( _SCREAMING_SNAKE_CASE , low_zero=(device_map == """balanced_low_0""") , max_memory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) snake_case_ = max_memory snake_case_ = infer_auto_device_map(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # check if don't have any quantized module on the cpu snake_case_ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules snake_case_ = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( """ Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. """ ) else: logger.info( """Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit""" ) del device_map_without_some_modules return device_map def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: if modules_to_not_convert is None: snake_case_ = [] snake_case_ , snake_case_ = _replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , ) -> List[str]: snake_case_ = False for name, module in model.named_children(): if current_key_name is None: snake_case_ = [] current_key_name.append(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` snake_case_ = """.""".join(_SCREAMING_SNAKE_CASE ) snake_case_ = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: snake_case_ = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_SCREAMING_SNAKE_CASE , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("""load_in_8bit and load_in_4bit can't be both False""" ) snake_case_ = module.weight.data if module.bias is not None: snake_case_ = module.bias.data bnb_module.requires_grad_(_SCREAMING_SNAKE_CASE ) setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = True if len(list(module.children() ) ) > 0: snake_case_ , snake_case_ = _replace_with_bnb_layers( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _a ( _SCREAMING_SNAKE_CASE ) -> Dict: # Create a copy of the model with init_empty_weights(): snake_case_ = deepcopy(_SCREAMING_SNAKE_CASE ) # this has 0 cost since it is done inside `init_empty_weights` context manager` snake_case_ = find_tied_parameters(_SCREAMING_SNAKE_CASE ) # For compatibility with Accelerate < 0.18 if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: snake_case_ = sum(_SCREAMING_SNAKE_CASE , [] ) snake_case_ = len(_SCREAMING_SNAKE_CASE ) > 0 # Check if it is a base model snake_case_ = False if hasattr(_SCREAMING_SNAKE_CASE , """base_model_prefix""" ): snake_case_ = not hasattr(_SCREAMING_SNAKE_CASE , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head snake_case_ = list(model.named_children() ) snake_case_ = [list_modules[-1][0]] # add last module together with tied weights snake_case_ = set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE ) snake_case_ = list(set(_SCREAMING_SNAKE_CASE ) ) + list(_SCREAMING_SNAKE_CASE ) # remove ".weight" from the keys snake_case_ = [""".weight""", """.bias"""] snake_case_ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: snake_case_ = name.replace(_SCREAMING_SNAKE_CASE , """""" ) filtered_module_names.append(_SCREAMING_SNAKE_CASE ) return filtered_module_names def _a ( _SCREAMING_SNAKE_CASE ) -> str: for m in model.modules(): if isinstance(_SCREAMING_SNAKE_CASE , bnb.nn.Linearabit ): return True return False def _a ( _SCREAMING_SNAKE_CASE ) -> Tuple: return next(parameter.parameters() ).device def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0 , dtype=_SCREAMING_SNAKE_CASE , value=_SCREAMING_SNAKE_CASE ) snake_case_ = param_name snake_case_ = model if "." in tensor_name: snake_case_ = tensor_name.split(""".""" ) for split in splits[:-1]: snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) snake_case_ = new_module snake_case_ = splits[-1] # offload weights snake_case_ = False offload_weight(module._parameters[tensor_name] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) if hasattr(module._parameters[tensor_name] , """SCB""" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("""weight""" , """SCB""" ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE , ) else: offload_weight(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) offload_weight(_SCREAMING_SNAKE_CASE , param_name.replace("""weight""" , """SCB""" ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE ) set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , """meta""" , dtype=_SCREAMING_SNAKE_CASE , value=torch.empty(*param.size() ) )
2
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="pt" ) -> str: snake_case_ = {"""add_prefix_space""": True} if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and not line.startswith(""" """ ) else {} snake_case_ = padding_side return tokenizer( [line] , max_length=_SCREAMING_SNAKE_CASE , padding="""max_length""" if pad_to_max_length else None , truncation=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , ) -> Any: snake_case_ = input_ids.ne(_SCREAMING_SNAKE_CASE ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __A (snake_case__): '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int="train" , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : str="" , ) ->Tuple: """simple docstring""" super().__init__() snake_case_ = Path(UpperCAmelCase_ ).joinpath(type_path + """.source""" ) snake_case_ = Path(UpperCAmelCase_ ).joinpath(type_path + """.target""" ) snake_case_ = self.get_char_lens(self.src_file ) snake_case_ = max_source_length snake_case_ = max_target_length assert min(self.src_lens ) > 0, F"""found empty line in {self.src_file}""" snake_case_ = tokenizer snake_case_ = prefix if n_obs is not None: snake_case_ = self.src_lens[:n_obs] snake_case_ = src_lang snake_case_ = tgt_lang def __len__( self : Any ) ->List[Any]: """simple docstring""" return len(self.src_lens ) def __getitem__( self : Any , UpperCAmelCase_ : Dict ) ->Dict[str, torch.Tensor]: """simple docstring""" snake_case_ = index + 1 # linecache starts at 1 snake_case_ = self.prefix + linecache.getline(str(self.src_file ) , UpperCAmelCase_ ).rstrip("""\n""" ) snake_case_ = linecache.getline(str(self.tgt_file ) , UpperCAmelCase_ ).rstrip("""\n""" ) assert source_line, F"""empty source line for index {index}""" assert tgt_line, F"""empty tgt line for index {index}""" # Need to add eos token manually for T5 if isinstance(self.tokenizer , UpperCAmelCase_ ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right snake_case_ = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , UpperCAmelCase_ ) else self.tokenizer ) snake_case_ = self.tokenizer.generator if isinstance(self.tokenizer , UpperCAmelCase_ ) else self.tokenizer snake_case_ = encode_line(UpperCAmelCase_ , UpperCAmelCase_ , self.max_source_length , """right""" ) snake_case_ = encode_line(UpperCAmelCase_ , UpperCAmelCase_ , self.max_target_length , """right""" ) snake_case_ = source_inputs["""input_ids"""].squeeze() snake_case_ = target_inputs["""input_ids"""].squeeze() snake_case_ = source_inputs["""attention_mask"""].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowerCAmelCase ( UpperCAmelCase_ : Union[str, Any] ) ->List[str]: """simple docstring""" return [len(UpperCAmelCase_ ) for x in Path(UpperCAmelCase_ ).open().readlines()] def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[Any] ) ->Dict[str, torch.Tensor]: """simple docstring""" snake_case_ = torch.stack([x["""input_ids"""] for x in batch] ) snake_case_ = torch.stack([x["""attention_mask"""] for x in batch] ) snake_case_ = torch.stack([x["""decoder_input_ids"""] for x in batch] ) snake_case_ = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , UpperCAmelCase_ ) else self.tokenizer.pad_token_id ) snake_case_ = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , UpperCAmelCase_ ) else self.tokenizer.pad_token_id ) snake_case_ = trim_batch(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ , snake_case_ = trim_batch(UpperCAmelCase_ , UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) snake_case_ = { """input_ids""": source_ids, """attention_mask""": source_mask, """decoder_input_ids""": y, } return batch __SCREAMING_SNAKE_CASE : List[Any] = getLogger(__name__) def _a ( _SCREAMING_SNAKE_CASE ) -> int: return list(itertools.chain.from_iterable(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE ) -> None: snake_case_ = get_git_info() save_json(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , """git_log.json""" ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=4 , **_SCREAMING_SNAKE_CASE ) -> int: with open(_SCREAMING_SNAKE_CASE , """w""" ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , indent=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: with open(_SCREAMING_SNAKE_CASE ) as f: return json.load(_SCREAMING_SNAKE_CASE ) def _a ( ) -> Any: snake_case_ = git.Repo(search_parent_directories=_SCREAMING_SNAKE_CASE ) snake_case_ = { """repo_id""": str(_SCREAMING_SNAKE_CASE ), """repo_sha""": str(repo.head.object.hexsha ), """repo_branch""": str(repo.active_branch ), """hostname""": str(socket.gethostname() ), } return repo_infos def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List: return list(map(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: with open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: return pickle.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> str: def remove_articles(_SCREAMING_SNAKE_CASE ): return re.sub(r"""\b(a|an|the)\b""" , """ """ , _SCREAMING_SNAKE_CASE ) def white_space_fix(_SCREAMING_SNAKE_CASE ): return " ".join(text.split() ) def remove_punc(_SCREAMING_SNAKE_CASE ): snake_case_ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_SCREAMING_SNAKE_CASE ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_SCREAMING_SNAKE_CASE ) ) ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = normalize_answer(_SCREAMING_SNAKE_CASE ).split() snake_case_ = normalize_answer(_SCREAMING_SNAKE_CASE ).split() snake_case_ = Counter(_SCREAMING_SNAKE_CASE ) & Counter(_SCREAMING_SNAKE_CASE ) snake_case_ = sum(common.values() ) if num_same == 0: return 0 snake_case_ = 1.0 * num_same / len(_SCREAMING_SNAKE_CASE ) snake_case_ = 1.0 * num_same / len(_SCREAMING_SNAKE_CASE ) snake_case_ = (2 * precision * recall) / (precision + recall) return fa def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: return normalize_answer(_SCREAMING_SNAKE_CASE ) == normalize_answer(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: assert len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) snake_case_ = 0 for hypo, pred in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): em += exact_match_score(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: em /= len(_SCREAMING_SNAKE_CASE ) return {"em": em} def _a ( _SCREAMING_SNAKE_CASE ) -> Dict: return model_prefix.startswith("""rag""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead snake_case_ = """dropout_rate""" for p in extra_params: if getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if not hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and not hasattr(_SCREAMING_SNAKE_CASE , equivalent_param[p] ): logger.info("""config doesn't have a `{}` attribute""".format(_SCREAMING_SNAKE_CASE ) ) delattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue snake_case_ = p if hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else equivalent_param[p] setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) delattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return hparams, config
2
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import math __SCREAMING_SNAKE_CASE : Optional[int] = 10 __SCREAMING_SNAKE_CASE : Optional[Any] = 7 __SCREAMING_SNAKE_CASE : Dict = BALLS_PER_COLOUR * NUM_COLOURS def _a ( _SCREAMING_SNAKE_CASE = 20 ) -> str: snake_case_ = math.comb(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = math.comb(NUM_BALLS - BALLS_PER_COLOUR , _SCREAMING_SNAKE_CASE ) snake_case_ = NUM_COLOURS * (1 - missing_colour / total) return f"""{result:.9f}""" if __name__ == "__main__": print(solution(20))
2
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : List[str] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __SCREAMING_SNAKE_CASE : List[str] = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __SCREAMING_SNAKE_CASE : int = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[Any] = VOCAB_FILES_NAMES __lowercase: Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowercase: Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]="[CLS]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : str="<unk>" , UpperCAmelCase_ : str="[SEP]" , UpperCAmelCase_ : Optional[Any]="<pad>" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : int="[MASK]" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->None: """simple docstring""" snake_case_ = ( AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ , normalized=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token ) snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = do_lower_case snake_case_ = remove_space snake_case_ = keep_accents snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return len(self.sp_model ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Any ) ->str: """simple docstring""" if self.remove_space: snake_case_ = """ """.join(inputs.strip().split() ) else: snake_case_ = inputs snake_case_ = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: snake_case_ = unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) snake_case_ = """""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: snake_case_ = outputs.lower() return outputs def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.preprocess_text(UpperCAmelCase_ ) snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) snake_case_ = [] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): snake_case_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case_ = cur_pieces[1:] else: snake_case_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" return self.sp_model.PieceToId(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" return self.sp_model.IdToPiece(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Dict ) ->Any: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
2
1
"""simple docstring""" import argparse import os import re import packaging.version __SCREAMING_SNAKE_CASE : Optional[Any] = 'examples/' __SCREAMING_SNAKE_CASE : int = { 'examples': (re.compile(R'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'), 'init': (re.compile(R'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'), 'setup': (re.compile(R'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), R'\1version="VERSION",'), 'doc': (re.compile(R'^(\s*)release\s*=\s*"[^"]+"$', re.MULTILINE), 'release = "VERSION"\n'), } __SCREAMING_SNAKE_CASE : Optional[int] = { 'init': 'src/transformers/__init__.py', 'setup': 'setup.py', } __SCREAMING_SNAKE_CASE : List[Any] = 'README.md' def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: with open(_SCREAMING_SNAKE_CASE , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: snake_case_ = f.read() snake_case_ , snake_case_ = REPLACE_PATTERNS[pattern] snake_case_ = replace.replace("""VERSION""" , _SCREAMING_SNAKE_CASE ) snake_case_ = re_pattern.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> int: for folder, directories, fnames in os.walk(_SCREAMING_SNAKE_CASE ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE , pattern="""examples""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Union[str, Any]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not patch: update_version_in_examples(_SCREAMING_SNAKE_CASE ) def _a ( ) -> Union[str, Any]: snake_case_ = """🤗 Transformers currently provides the following architectures""" snake_case_ = """1. Want to contribute a new model?""" with open(_SCREAMING_SNAKE_CASE , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: snake_case_ = f.readlines() # Find the start of the list. snake_case_ = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 snake_case_ = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): snake_case_ = lines[index].replace( """https://huggingface.co/docs/transformers/main/model_doc""" , """https://huggingface.co/docs/transformers/model_doc""" , ) index += 1 with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(_SCREAMING_SNAKE_CASE ) def _a ( ) -> List[str]: with open(REPLACE_FILES["""init"""] , """r""" ) as f: snake_case_ = f.read() snake_case_ = REPLACE_PATTERNS["""init"""][0].search(_SCREAMING_SNAKE_CASE ).groups()[0] return packaging.version.parse(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE=False ) -> List[str]: snake_case_ = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: snake_case_ = default_version.base_version elif patch: snake_case_ = f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: snake_case_ = f"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. snake_case_ = input(f"""Which version are you releasing? [{default_version}]""" ) if len(_SCREAMING_SNAKE_CASE ) == 0: snake_case_ = default_version print(f"""Updating version to {version}.""" ) global_version_update(_SCREAMING_SNAKE_CASE , patch=_SCREAMING_SNAKE_CASE ) if not patch: print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() def _a ( ) -> Optional[int]: snake_case_ = get_version() snake_case_ = f"""{current_version.major}.{current_version.minor + 1}.0.dev0""" snake_case_ = current_version.base_version # Check with the user we got that right. snake_case_ = input(f"""Which version are we developing now? [{dev_version}]""" ) if len(_SCREAMING_SNAKE_CASE ) == 0: snake_case_ = dev_version print(f"""Updating version to {version}.""" ) global_version_update(_SCREAMING_SNAKE_CASE ) print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() if __name__ == "__main__": __SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('--post_release', action='store_true', help='Whether this is pre or post release.') parser.add_argument('--patch', action='store_true', help='Whether or not this is a patch release.') __SCREAMING_SNAKE_CASE : Any = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('Nothing to do after a patch :-)') else: post_release_work()
2
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , _SCREAMING_SNAKE_CASE , ) if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): return image elif isinstance(_SCREAMING_SNAKE_CASE , PIL.Image.Image ): snake_case_ = [image] if isinstance(image[0] , PIL.Image.Image ): snake_case_ , snake_case_ = image[0].size snake_case_ , snake_case_ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 snake_case_ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] snake_case_ = np.concatenate(_SCREAMING_SNAKE_CASE , axis=0 ) snake_case_ = np.array(_SCREAMING_SNAKE_CASE ).astype(np.floataa ) / 255.0 snake_case_ = image.transpose(0 , 3 , 1 , 2 ) snake_case_ = 2.0 * image - 1.0 snake_case_ = torch.from_numpy(_SCREAMING_SNAKE_CASE ) elif isinstance(image[0] , torch.Tensor ): snake_case_ = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) return image def _a ( _SCREAMING_SNAKE_CASE ) -> Dict: if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): return mask elif isinstance(_SCREAMING_SNAKE_CASE , PIL.Image.Image ): snake_case_ = [mask] if isinstance(mask[0] , PIL.Image.Image ): snake_case_ , snake_case_ = mask[0].size snake_case_ , snake_case_ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 snake_case_ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] snake_case_ = np.concatenate(_SCREAMING_SNAKE_CASE , axis=0 ) snake_case_ = mask.astype(np.floataa ) / 255.0 snake_case_ = 0 snake_case_ = 1 snake_case_ = torch.from_numpy(_SCREAMING_SNAKE_CASE ) elif isinstance(mask[0] , torch.Tensor ): snake_case_ = torch.cat(_SCREAMING_SNAKE_CASE , dim=0 ) return mask class __A (snake_case__): '''simple docstring''' __lowercase: UNetaDModel __lowercase: RePaintScheduler def __init__( self : Dict , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" super().__init__() self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_ ) @torch.no_grad() def __call__( self : Dict , UpperCAmelCase_ : Union[torch.Tensor, PIL.Image.Image] , UpperCAmelCase_ : Union[torch.Tensor, PIL.Image.Image] , UpperCAmelCase_ : int = 250 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: """simple docstring""" snake_case_ = image snake_case_ = _preprocess_image(UpperCAmelCase_ ) snake_case_ = original_image.to(device=self.device , dtype=self.unet.dtype ) snake_case_ = _preprocess_mask(UpperCAmelCase_ ) snake_case_ = mask_image.to(device=self.device , dtype=self.unet.dtype ) snake_case_ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and len(UpperCAmelCase_ ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(UpperCAmelCase_ )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) snake_case_ = original_image.shape snake_case_ = randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.device ) snake_case_ = eta snake_case_ = self.scheduler.timesteps[0] + 1 snake_case_ = generator[0] if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual snake_case_ = self.unet(UpperCAmelCase_ , UpperCAmelCase_ ).sample # compute previous image: x_t -> x_t-1 snake_case_ = self.scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ).prev_sample else: # compute the reverse: x_t-1 -> x_t snake_case_ = self.scheduler.undo_step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = t snake_case_ = (image / 2 + 0.5).clamp(0 , 1 ) snake_case_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case_ = self.numpy_to_pil(UpperCAmelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase_ )
2
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: __SCREAMING_SNAKE_CASE : Any = None __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE : Union[str, Any] = { 'vocab_file': { 'facebook/nllb-200-distilled-600M': ( 'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model' ), }, 'tokenizer_file': { 'facebook/nllb-200-distilled-600M': ( 'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json' ), }, } __SCREAMING_SNAKE_CASE : List[str] = { 'facebook/nllb-large-en-ro': 1_024, 'facebook/nllb-200-distilled-600M': 1_024, } # fmt: off __SCREAMING_SNAKE_CASE : Dict = ['ace_Arab', 'ace_Latn', 'acm_Arab', 'acq_Arab', 'aeb_Arab', 'afr_Latn', 'ajp_Arab', 'aka_Latn', 'amh_Ethi', 'apc_Arab', 'arb_Arab', 'ars_Arab', 'ary_Arab', 'arz_Arab', 'asm_Beng', 'ast_Latn', 'awa_Deva', 'ayr_Latn', 'azb_Arab', 'azj_Latn', 'bak_Cyrl', 'bam_Latn', 'ban_Latn', 'bel_Cyrl', 'bem_Latn', 'ben_Beng', 'bho_Deva', 'bjn_Arab', 'bjn_Latn', 'bod_Tibt', 'bos_Latn', 'bug_Latn', 'bul_Cyrl', 'cat_Latn', 'ceb_Latn', 'ces_Latn', 'cjk_Latn', 'ckb_Arab', 'crh_Latn', 'cym_Latn', 'dan_Latn', 'deu_Latn', 'dik_Latn', 'dyu_Latn', 'dzo_Tibt', 'ell_Grek', 'eng_Latn', 'epo_Latn', 'est_Latn', 'eus_Latn', 'ewe_Latn', 'fao_Latn', 'pes_Arab', 'fij_Latn', 'fin_Latn', 'fon_Latn', 'fra_Latn', 'fur_Latn', 'fuv_Latn', 'gla_Latn', 'gle_Latn', 'glg_Latn', 'grn_Latn', 'guj_Gujr', 'hat_Latn', 'hau_Latn', 'heb_Hebr', 'hin_Deva', 'hne_Deva', 'hrv_Latn', 'hun_Latn', 'hye_Armn', 'ibo_Latn', 'ilo_Latn', 'ind_Latn', 'isl_Latn', 'ita_Latn', 'jav_Latn', 'jpn_Jpan', 'kab_Latn', 'kac_Latn', 'kam_Latn', 'kan_Knda', 'kas_Arab', 'kas_Deva', 'kat_Geor', 'knc_Arab', 'knc_Latn', 'kaz_Cyrl', 'kbp_Latn', 'kea_Latn', 'khm_Khmr', 'kik_Latn', 'kin_Latn', 'kir_Cyrl', 'kmb_Latn', 'kon_Latn', 'kor_Hang', 'kmr_Latn', 'lao_Laoo', 'lvs_Latn', 'lij_Latn', 'lim_Latn', 'lin_Latn', 'lit_Latn', 'lmo_Latn', 'ltg_Latn', 'ltz_Latn', 'lua_Latn', 'lug_Latn', 'luo_Latn', 'lus_Latn', 'mag_Deva', 'mai_Deva', 'mal_Mlym', 'mar_Deva', 'min_Latn', 'mkd_Cyrl', 'plt_Latn', 'mlt_Latn', 'mni_Beng', 'khk_Cyrl', 'mos_Latn', 'mri_Latn', 'zsm_Latn', 'mya_Mymr', 'nld_Latn', 'nno_Latn', 'nob_Latn', 'npi_Deva', 'nso_Latn', 'nus_Latn', 'nya_Latn', 'oci_Latn', 'gaz_Latn', 'ory_Orya', 'pag_Latn', 'pan_Guru', 'pap_Latn', 'pol_Latn', 'por_Latn', 'prs_Arab', 'pbt_Arab', 'quy_Latn', 'ron_Latn', 'run_Latn', 'rus_Cyrl', 'sag_Latn', 'san_Deva', 'sat_Beng', 'scn_Latn', 'shn_Mymr', 'sin_Sinh', 'slk_Latn', 'slv_Latn', 'smo_Latn', 'sna_Latn', 'snd_Arab', 'som_Latn', 'sot_Latn', 'spa_Latn', 'als_Latn', 'srd_Latn', 'srp_Cyrl', 'ssw_Latn', 'sun_Latn', 'swe_Latn', 'swh_Latn', 'szl_Latn', 'tam_Taml', 'tat_Cyrl', 'tel_Telu', 'tgk_Cyrl', 'tgl_Latn', 'tha_Thai', 'tir_Ethi', 'taq_Latn', 'taq_Tfng', 'tpi_Latn', 'tsn_Latn', 'tso_Latn', 'tuk_Latn', 'tum_Latn', 'tur_Latn', 'twi_Latn', 'tzm_Tfng', 'uig_Arab', 'ukr_Cyrl', 'umb_Latn', 'urd_Arab', 'uzn_Latn', 'vec_Latn', 'vie_Latn', 'war_Latn', 'wol_Latn', 'xho_Latn', 'ydd_Hebr', 'yor_Latn', 'yue_Hant', 'zho_Hans', 'zho_Hant', 'zul_Latn'] class __A (snake_case__): '''simple docstring''' __lowercase: Tuple = VOCAB_FILES_NAMES __lowercase: Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase: List[str] = PRETRAINED_VOCAB_FILES_MAP __lowercase: Optional[int] = ["""input_ids""", """attention_mask"""] __lowercase: List[Any] = NllbTokenizer __lowercase: List[int] = [] __lowercase: List[int] = [] def __init__( self : Optional[int] , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : List[str]="<s>" , UpperCAmelCase_ : List[Any]="</s>" , UpperCAmelCase_ : Optional[int]="</s>" , UpperCAmelCase_ : Tuple="<s>" , UpperCAmelCase_ : Any="<unk>" , UpperCAmelCase_ : int="<pad>" , UpperCAmelCase_ : Optional[Any]="<mask>" , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : int=False , **UpperCAmelCase_ : Dict , ) ->int: """simple docstring""" snake_case_ = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token snake_case_ = legacy_behaviour super().__init__( vocab_file=UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , src_lang=UpperCAmelCase_ , tgt_lang=UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , legacy_behaviour=UpperCAmelCase_ , **UpperCAmelCase_ , ) snake_case_ = vocab_file snake_case_ = False if not self.vocab_file else True snake_case_ = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens} ) snake_case_ = { lang_code: self.convert_tokens_to_ids(UpperCAmelCase_ ) for lang_code in FAIRSEQ_LANGUAGE_CODES } snake_case_ = src_lang if src_lang is not None else """eng_Latn""" snake_case_ = self.convert_tokens_to_ids(self._src_lang ) snake_case_ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" return self._src_lang @src_lang.setter def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : str ) ->None: """simple docstring""" snake_case_ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def lowerCAmelCase ( self : str , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] , UpperCAmelCase_ : Optional[str] , **UpperCAmelCase_ : int ) ->List[str]: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) snake_case_ = src_lang snake_case_ = self(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ ) snake_case_ = self.convert_tokens_to_ids(UpperCAmelCase_ ) snake_case_ = tgt_lang_id return inputs def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str = "eng_Latn" , UpperCAmelCase_ : Optional[List[str]] = None , UpperCAmelCase_ : str = "fra_Latn" , **UpperCAmelCase_ : List[Any] , ) ->BatchEncoding: """simple docstring""" snake_case_ = src_lang snake_case_ = tgt_lang return super().prepare_seqaseq_batch(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->None: """simple docstring""" snake_case_ = self.convert_tokens_to_ids(UpperCAmelCase_ ) if self.legacy_behaviour: snake_case_ = [] snake_case_ = [self.eos_token_id, self.cur_lang_code] else: snake_case_ = [self.cur_lang_code] snake_case_ = [self.eos_token_id] snake_case_ = self.convert_ids_to_tokens(self.prefix_tokens ) snake_case_ = self.convert_ids_to_tokens(self.suffix_tokens ) snake_case_ = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : str ) ->None: """simple docstring""" snake_case_ = self.convert_tokens_to_ids(UpperCAmelCase_ ) if self.legacy_behaviour: snake_case_ = [] snake_case_ = [self.eos_token_id, self.cur_lang_code] else: snake_case_ = [self.cur_lang_code] snake_case_ = [self.eos_token_id] snake_case_ = self.convert_ids_to_tokens(self.prefix_tokens ) snake_case_ = self.convert_ids_to_tokens(self.suffix_tokens ) snake_case_ = processors.TemplateProcessing( single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str , pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory.""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ): copyfile(self.vocab_file , UpperCAmelCase_ ) return (out_vocab_file,)
2
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
1
"""simple docstring""" import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class __A (snake_case__): '''simple docstring''' __lowercase: torch.FloatTensor __lowercase: Optional[torch.FloatTensor] = None def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0.999 , _SCREAMING_SNAKE_CASE="cosine" , ) -> Optional[int]: if alpha_transform_type == "cosine": def alpha_bar_fn(_SCREAMING_SNAKE_CASE ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(_SCREAMING_SNAKE_CASE ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) snake_case_ = [] for i in range(_SCREAMING_SNAKE_CASE ): snake_case_ = i / num_diffusion_timesteps snake_case_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_SCREAMING_SNAKE_CASE ) / alpha_bar_fn(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) ) return torch.tensor(_SCREAMING_SNAKE_CASE , dtype=torch.floataa ) class __A (snake_case__ , snake_case__): '''simple docstring''' @register_to_config def __init__( self : Union[str, Any] , UpperCAmelCase_ : int = 1_000 , UpperCAmelCase_ : str = "fixed_small_log" , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[float] = 1.0 , UpperCAmelCase_ : str = "epsilon" , UpperCAmelCase_ : str = "squaredcos_cap_v2" , ) ->Optional[int]: """simple docstring""" if beta_schedule != "squaredcos_cap_v2": raise ValueError("""UnCLIPScheduler only supports `beta_schedule`: 'squaredcos_cap_v2'""" ) snake_case_ = betas_for_alpha_bar(UpperCAmelCase_ ) snake_case_ = 1.0 - self.betas snake_case_ = torch.cumprod(self.alphas , dim=0 ) snake_case_ = torch.tensor(1.0 ) # standard deviation of the initial noise distribution snake_case_ = 1.0 # setable values snake_case_ = None snake_case_ = torch.from_numpy(np.arange(0 , UpperCAmelCase_ )[::-1].copy() ) snake_case_ = variance_type def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : Optional[int] = None ) ->torch.FloatTensor: """simple docstring""" return sample def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, torch.device] = None ) ->Tuple: """simple docstring""" snake_case_ = num_inference_steps snake_case_ = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) snake_case_ = (np.arange(0 , UpperCAmelCase_ ) * step_ratio).round()[::-1].copy().astype(np.intaa ) snake_case_ = torch.from_numpy(UpperCAmelCase_ ).to(UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[str]=None ) ->str: """simple docstring""" if prev_timestep is None: snake_case_ = t - 1 snake_case_ = self.alphas_cumprod[t] snake_case_ = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one snake_case_ = 1 - alpha_prod_t snake_case_ = 1 - alpha_prod_t_prev if prev_timestep == t - 1: snake_case_ = self.betas[t] else: snake_case_ = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample snake_case_ = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: snake_case_ = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": snake_case_ = torch.log(torch.clamp(UpperCAmelCase_ , min=1E-20 ) ) snake_case_ = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler snake_case_ = variance.log() snake_case_ = beta.log() snake_case_ = (predicted_variance + 1) / 2 snake_case_ = frac * max_log + (1 - frac) * min_log return variance def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : int , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : bool = True , ) ->Union[UnCLIPSchedulerOutput, Tuple]: """simple docstring""" snake_case_ = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": snake_case_ , snake_case_ = torch.split(UpperCAmelCase_ , sample.shape[1] , dim=1 ) else: snake_case_ = None # 1. compute alphas, betas if prev_timestep is None: snake_case_ = t - 1 snake_case_ = self.alphas_cumprod[t] snake_case_ = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one snake_case_ = 1 - alpha_prod_t snake_case_ = 1 - alpha_prod_t_prev if prev_timestep == t - 1: snake_case_ = self.betas[t] snake_case_ = self.alphas[t] else: snake_case_ = 1 - alpha_prod_t / alpha_prod_t_prev snake_case_ = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": snake_case_ = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": snake_case_ = model_output else: raise ValueError( F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`""" """ for the UnCLIPScheduler.""" ) # 3. Clip "predicted x_0" if self.config.clip_sample: snake_case_ = torch.clamp( UpperCAmelCase_ , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf snake_case_ = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t snake_case_ = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf snake_case_ = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise snake_case_ = 0 if t > 0: snake_case_ = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=UpperCAmelCase_ , device=model_output.device ) snake_case_ = self._get_variance( UpperCAmelCase_ , predicted_variance=UpperCAmelCase_ , prev_timestep=UpperCAmelCase_ , ) if self.variance_type == "fixed_small_log": snake_case_ = variance elif self.variance_type == "learned_range": snake_case_ = (0.5 * variance).exp() else: raise ValueError( F"""variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`""" """ for the UnCLIPScheduler.""" ) snake_case_ = variance * variance_noise snake_case_ = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=UpperCAmelCase_ , pred_original_sample=UpperCAmelCase_ ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : torch.IntTensor , ) ->torch.FloatTensor: """simple docstring""" snake_case_ = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) snake_case_ = timesteps.to(original_samples.device ) snake_case_ = alphas_cumprod[timesteps] ** 0.5 snake_case_ = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): snake_case_ = sqrt_alpha_prod.unsqueeze(-1 ) snake_case_ = (1 - alphas_cumprod[timesteps]) ** 0.5 snake_case_ = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): snake_case_ = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) snake_case_ = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
2
"""simple docstring""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): '''simple docstring''' @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
2
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Any = { 'configuration_instructblip': [ 'INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InstructBlipConfig', 'InstructBlipQFormerConfig', 'InstructBlipVisionConfig', ], 'processing_instructblip': ['InstructBlipProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : str = [ 'INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'InstructBlipQFormerModel', 'InstructBlipPreTrainedModel', 'InstructBlipForConditionalGeneration', 'InstructBlipVisionModel', ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys __SCREAMING_SNAKE_CASE : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=snake_case__) class __A (snake_case__): '''simple docstring''' __lowercase: str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True}) __lowercase: ClassVar[Features] = Features({"""audio""": Audio()}) __lowercase: ClassVar[Features] = Features({"""transcription""": Value("""string""")}) __lowercase: str = "audio" __lowercase: str = "transcription" def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , UpperCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) snake_case_ = copy.deepcopy(self ) snake_case_ = self.input_schema.copy() snake_case_ = features[self.audio_column] snake_case_ = input_schema return task_template @property def lowerCAmelCase ( self : List[str] ) ->Dict[str, str]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
2
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
"""simple docstring""" from functools import reduce __SCREAMING_SNAKE_CASE : Tuple = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _a ( _SCREAMING_SNAKE_CASE = N ) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str(int(_SCREAMING_SNAKE_CASE ) * int(_SCREAMING_SNAKE_CASE ) ) , n[i : i + 13] ) ) for i in range(len(_SCREAMING_SNAKE_CASE ) - 12 ) ) if __name__ == "__main__": print(f"""{solution() = }""")
2
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Any = {'openai-gpt': 'https://huggingface.co/openai-gpt/resolve/main/config.json'} class __A (snake_case__): '''simple docstring''' __lowercase: str = """openai-gpt""" __lowercase: List[str] = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Optional[int] , UpperCAmelCase_ : List[str]=40_478 , UpperCAmelCase_ : Dict=512 , UpperCAmelCase_ : Optional[int]=768 , UpperCAmelCase_ : Optional[Any]=12 , UpperCAmelCase_ : Optional[Any]=12 , UpperCAmelCase_ : Tuple="gelu" , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Dict=0.1 , UpperCAmelCase_ : List[Any]=1E-5 , UpperCAmelCase_ : List[str]=0.02 , UpperCAmelCase_ : Dict="cls_index" , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Dict=0.1 , **UpperCAmelCase_ : Union[str, Any] , ) ->Dict: """simple docstring""" snake_case_ = vocab_size snake_case_ = n_positions snake_case_ = n_embd snake_case_ = n_layer snake_case_ = n_head snake_case_ = afn snake_case_ = resid_pdrop snake_case_ = embd_pdrop snake_case_ = attn_pdrop snake_case_ = layer_norm_epsilon snake_case_ = initializer_range snake_case_ = summary_type snake_case_ = summary_use_proj snake_case_ = summary_activation snake_case_ = summary_first_dropout snake_case_ = summary_proj_to_labels super().__init__(**UpperCAmelCase_ )
2
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str = { 'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json', # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class __A (snake_case__): '''simple docstring''' __lowercase: Any = """mctct""" def __init__( self : Dict , UpperCAmelCase_ : List[Any]=8_065 , UpperCAmelCase_ : Tuple=1_536 , UpperCAmelCase_ : Optional[Any]=36 , UpperCAmelCase_ : int=6_144 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Any=384 , UpperCAmelCase_ : List[str]=920 , UpperCAmelCase_ : Any=1E-5 , UpperCAmelCase_ : Any=0.3 , UpperCAmelCase_ : Tuple="relu" , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Dict=0.3 , UpperCAmelCase_ : str=0.3 , UpperCAmelCase_ : Any=1 , UpperCAmelCase_ : Any=0 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=0.3 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : Optional[Any]=(7,) , UpperCAmelCase_ : Optional[Any]=(3,) , UpperCAmelCase_ : List[str]=80 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[str]="sum" , UpperCAmelCase_ : Union[str, Any]=False , **UpperCAmelCase_ : Any , ) ->Dict: """simple docstring""" super().__init__(**UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = intermediate_size snake_case_ = num_attention_heads snake_case_ = attention_head_dim snake_case_ = max_position_embeddings snake_case_ = layer_norm_eps snake_case_ = layerdrop snake_case_ = hidden_act snake_case_ = initializer_range snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id snake_case_ = conv_glu_dim snake_case_ = conv_dropout snake_case_ = num_conv_layers snake_case_ = input_feat_per_channel snake_case_ = input_channels snake_case_ = conv_channels snake_case_ = ctc_loss_reduction snake_case_ = ctc_zero_infinity # prevents config testing fail with exporting to json snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """ F"""but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, """ F"""`config.num_conv_layers = {self.num_conv_layers}`.""" )
2
1
"""simple docstring""" from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def _a ( _SCREAMING_SNAKE_CASE ) -> int: # A local function to see if a dot lands in the circle. def is_in_circle(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: snake_case_ = sqrt((x**2) + (y**2) ) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle snake_case_ = mean( int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) ) for _ in range(_SCREAMING_SNAKE_CASE ) ) # The ratio of the area for circle to square is pi/4. snake_case_ = proportion * 4 print(f"""The estimated value of pi is {pi_estimate}""" ) print(f"""The numpy value of pi is {pi}""" ) print(f"""The total error is {abs(pi - pi_estimate )}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = 1.0 , ) -> float: return mean( function_to_integrate(uniform(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) for _ in range(_SCREAMING_SNAKE_CASE ) ) * (max_value - min_value) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = 1.0 ) -> None: def identity_function(_SCREAMING_SNAKE_CASE ) -> float: return x snake_case_ = area_under_curve_estimator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = (max_value * max_value - min_value * min_value) / 2 print("""******************""" ) print(f"""Estimating area under y=x where x varies from {min_value} to {max_value}""" ) print(f"""Estimated value is {estimated_value}""" ) print(f"""Expected value is {expected_value}""" ) print(f"""Total error is {abs(estimated_value - expected_value )}""" ) print("""******************""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> None: def function_to_integrate(_SCREAMING_SNAKE_CASE ) -> float: return sqrt(4.0 - x * x ) snake_case_ = area_under_curve_estimator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0.0 , 2.0 ) print("""******************""" ) print("""Estimating pi using area_under_curve_estimator""" ) print(f"""Estimated value is {estimated_value}""" ) print(f"""Expected value is {pi}""" ) print(f"""Total error is {abs(estimated_value - pi )}""" ) print("""******************""" ) if __name__ == "__main__": import doctest doctest.testmod()
2
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 100 ) -> int: return sum(int(_SCREAMING_SNAKE_CASE ) for x in str(factorial(_SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
2
1
"""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 __A (nn.Module): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int]=0.0 , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : str = "geglu" , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : str = "layer_norm" , UpperCAmelCase_ : bool = False , ) ->Tuple: """simple docstring""" super().__init__() snake_case_ = only_cross_attention snake_case_ = (num_embeds_ada_norm is not None) and norm_type == """ada_norm_zero""" snake_case_ = (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: snake_case_ = AdaLayerNorm(UpperCAmelCase_ , UpperCAmelCase_ ) elif self.use_ada_layer_norm_zero: snake_case_ = AdaLayerNormZero(UpperCAmelCase_ , UpperCAmelCase_ ) else: snake_case_ = nn.LayerNorm(UpperCAmelCase_ , elementwise_affine=UpperCAmelCase_ ) snake_case_ = Attention( query_dim=UpperCAmelCase_ , heads=UpperCAmelCase_ , dim_head=UpperCAmelCase_ , dropout=UpperCAmelCase_ , bias=UpperCAmelCase_ , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=UpperCAmelCase_ , ) # 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. snake_case_ = ( AdaLayerNorm(UpperCAmelCase_ , UpperCAmelCase_ ) if self.use_ada_layer_norm else nn.LayerNorm(UpperCAmelCase_ , elementwise_affine=UpperCAmelCase_ ) ) snake_case_ = Attention( query_dim=UpperCAmelCase_ , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=UpperCAmelCase_ , dim_head=UpperCAmelCase_ , dropout=UpperCAmelCase_ , bias=UpperCAmelCase_ , upcast_attention=UpperCAmelCase_ , ) # is self-attn if encoder_hidden_states is none else: snake_case_ = None snake_case_ = None # 3. Feed-forward snake_case_ = nn.LayerNorm(UpperCAmelCase_ , elementwise_affine=UpperCAmelCase_ ) snake_case_ = FeedForward(UpperCAmelCase_ , dropout=UpperCAmelCase_ , activation_fn=UpperCAmelCase_ , final_dropout=UpperCAmelCase_ ) # let chunk size default to None snake_case_ = None snake_case_ = 0 def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int ) ->str: """simple docstring""" snake_case_ = chunk_size snake_case_ = dim def lowerCAmelCase ( self : int , UpperCAmelCase_ : torch.FloatTensor , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[torch.LongTensor] = None , UpperCAmelCase_ : Dict[str, Any] = None , UpperCAmelCase_ : Optional[torch.LongTensor] = None , ) ->Union[str, Any]: """simple docstring""" if self.use_ada_layer_norm: snake_case_ = self.norma(UpperCAmelCase_ , UpperCAmelCase_ ) elif self.use_ada_layer_norm_zero: snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.norma( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , hidden_dtype=hidden_states.dtype ) else: snake_case_ = self.norma(UpperCAmelCase_ ) snake_case_ = cross_attention_kwargs if cross_attention_kwargs is not None else {} snake_case_ = self.attna( UpperCAmelCase_ , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=UpperCAmelCase_ , **UpperCAmelCase_ , ) if self.use_ada_layer_norm_zero: snake_case_ = gate_msa.unsqueeze(1 ) * attn_output snake_case_ = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: snake_case_ = ( self.norma(UpperCAmelCase_ , UpperCAmelCase_ ) if self.use_ada_layer_norm else self.norma(UpperCAmelCase_ ) ) snake_case_ = self.attna( UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , **UpperCAmelCase_ , ) snake_case_ = attn_output + hidden_states # 3. Feed-forward snake_case_ = self.norma(UpperCAmelCase_ ) if self.use_ada_layer_norm_zero: snake_case_ = 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`.""" ) snake_case_ = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size snake_case_ = torch.cat( [self.ff(UpperCAmelCase_ ) for hid_slice in norm_hidden_states.chunk(UpperCAmelCase_ , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: snake_case_ = self.ff(UpperCAmelCase_ ) if self.use_ada_layer_norm_zero: snake_case_ = gate_mlp.unsqueeze(1 ) * ff_output snake_case_ = ff_output + hidden_states return hidden_states class __A (nn.Module): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : int = 4 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : str = "geglu" , UpperCAmelCase_ : bool = False , ) ->List[str]: """simple docstring""" super().__init__() snake_case_ = int(dim * mult ) snake_case_ = dim_out if dim_out is not None else dim if activation_fn == "gelu": snake_case_ = GELU(UpperCAmelCase_ , UpperCAmelCase_ ) if activation_fn == "gelu-approximate": snake_case_ = GELU(UpperCAmelCase_ , UpperCAmelCase_ , approximate="""tanh""" ) elif activation_fn == "geglu": snake_case_ = GEGLU(UpperCAmelCase_ , UpperCAmelCase_ ) elif activation_fn == "geglu-approximate": snake_case_ = ApproximateGELU(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = nn.ModuleList([] ) # project in self.net.append(UpperCAmelCase_ ) # project dropout self.net.append(nn.Dropout(UpperCAmelCase_ ) ) # project out self.net.append(nn.Linear(UpperCAmelCase_ , UpperCAmelCase_ ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(UpperCAmelCase_ ) ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : int ) ->Any: """simple docstring""" for module in self.net: snake_case_ = module(UpperCAmelCase_ ) return hidden_states class __A (nn.Module): '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : str = "none" ) ->Dict: """simple docstring""" super().__init__() snake_case_ = nn.Linear(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = approximate def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" if gate.device.type != "mps": return F.gelu(UpperCAmelCase_ , 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 lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->int: """simple docstring""" snake_case_ = self.proj(UpperCAmelCase_ ) snake_case_ = self.gelu(UpperCAmelCase_ ) return hidden_states class __A (nn.Module): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) ->Union[str, Any]: """simple docstring""" super().__init__() snake_case_ = nn.Linear(UpperCAmelCase_ , dim_out * 2 ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Tuple ) ->Optional[Any]: """simple docstring""" if gate.device.type != "mps": return F.gelu(UpperCAmelCase_ ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : int ) ->str: """simple docstring""" snake_case_ , snake_case_ = self.proj(UpperCAmelCase_ ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(UpperCAmelCase_ ) class __A (nn.Module): '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) ->Union[str, Any]: """simple docstring""" super().__init__() snake_case_ = nn.Linear(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.proj(UpperCAmelCase_ ) return x * torch.sigmoid(1.702 * x ) class __A (nn.Module): '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int ) ->Union[str, Any]: """simple docstring""" super().__init__() snake_case_ = nn.Embedding(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = nn.SiLU() snake_case_ = nn.Linear(UpperCAmelCase_ , embedding_dim * 2 ) snake_case_ = nn.LayerNorm(UpperCAmelCase_ , elementwise_affine=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple ) ->int: """simple docstring""" snake_case_ = self.linear(self.silu(self.emb(UpperCAmelCase_ ) ) ) snake_case_ , snake_case_ = torch.chunk(UpperCAmelCase_ , 2 ) snake_case_ = self.norm(UpperCAmelCase_ ) * (1 + scale) + shift return x class __A (nn.Module): '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] ) ->Tuple: """simple docstring""" super().__init__() snake_case_ = CombinedTimestepLabelEmbeddings(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = nn.SiLU() snake_case_ = nn.Linear(UpperCAmelCase_ , 6 * embedding_dim , bias=UpperCAmelCase_ ) snake_case_ = nn.LayerNorm(UpperCAmelCase_ , elementwise_affine=UpperCAmelCase_ , eps=1E-6 ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any=None ) ->Any: """simple docstring""" snake_case_ = self.linear(self.silu(self.emb(UpperCAmelCase_ , UpperCAmelCase_ , hidden_dtype=UpperCAmelCase_ ) ) ) snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ = emb.chunk(6 , dim=1 ) snake_case_ = self.norm(UpperCAmelCase_ ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class __A (nn.Module): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[str] = None , UpperCAmelCase_ : float = 1E-5 ) ->str: """simple docstring""" super().__init__() snake_case_ = num_groups snake_case_ = eps if act_fn is None: snake_case_ = None else: snake_case_ = get_activation(UpperCAmelCase_ ) snake_case_ = nn.Linear(UpperCAmelCase_ , out_dim * 2 ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] ) ->Dict: """simple docstring""" if self.act: snake_case_ = self.act(UpperCAmelCase_ ) snake_case_ = self.linear(UpperCAmelCase_ ) snake_case_ = emb[:, :, None, None] snake_case_ , snake_case_ = emb.chunk(2 , dim=1 ) snake_case_ = F.group_norm(UpperCAmelCase_ , self.num_groups , eps=self.eps ) snake_case_ = x * (1 + scale) + shift return x
2
"""simple docstring""" import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: str = VQModel __lowercase: Union[str, Any] = """sample""" @property def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[str]=(32, 32) ) ->Tuple: """simple docstring""" snake_case_ = 4 snake_case_ = 3 snake_case_ = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase_ ) return {"sample": image} @property def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" return (3, 32, 32) @property def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" return (3, 32, 32) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } snake_case_ = self.dummy_input return init_dict, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(UpperCAmelCase_ ) snake_case_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(UpperCAmelCase_ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) snake_case_ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) snake_case_ = image.to(UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = model(UpperCAmelCase_ ).sample snake_case_ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off snake_case_ = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 ) )
2
1
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = KandinskyVaaControlnetPipeline __lowercase: str = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: Union[str, Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowercase: Tuple = False @property def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return 100 @property def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) snake_case_ = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } snake_case_ = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=UpperCAmelCase_ , ) snake_case_ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]=0 ) ->List[str]: """simple docstring""" snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) # create hint snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("""mps""" ): snake_case_ = torch.manual_seed(UpperCAmelCase_ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) snake_case_ = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" snake_case_ = """cpu""" snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**UpperCAmelCase_ ) snake_case_ = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) snake_case_ = torch.from_numpy(np.array(UpperCAmelCase_ ) ).float() / 255.0 snake_case_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case_ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) snake_case_ = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = """A robot, 4k photo""" snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ , snake_case_ = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , hint=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
2
1
"""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 _a ( _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = 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.""" ) snake_case_ = 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.""" ) snake_case_ = components[:-1] + [test_fn.replace(""".py""" , """""" )] snake_case_ = """.""".join(_SCREAMING_SNAKE_CASE ) return test_module_path def _a ( _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = get_module_path(_SCREAMING_SNAKE_CASE ) snake_case_ = importlib.import_module(_SCREAMING_SNAKE_CASE ) return test_module def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = [] snake_case_ = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): if attr.endswith("""ModelTester""" ): tester_classes.append(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ = [] snake_case_ = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # (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). snake_case_ = getattr(_SCREAMING_SNAKE_CASE , """all_model_classes""" , [] ) if len(_SCREAMING_SNAKE_CASE ) > 0: test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = get_test_classes(_SCREAMING_SNAKE_CASE ) snake_case_ = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = test_class() if hasattr(_SCREAMING_SNAKE_CASE , """setUp""" ): test.setUp() snake_case_ = None if hasattr(_SCREAMING_SNAKE_CASE , """model_tester""" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: snake_case_ = test.model_tester.__class__ return model_tester def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = get_test_classes(_SCREAMING_SNAKE_CASE ) snake_case_ = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: snake_case_ = get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = [] for test_class in test_classes: snake_case_ = get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) if tester_class is not None: tester_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def _a ( _SCREAMING_SNAKE_CASE ) -> Dict: snake_case_ = get_test_classes(_SCREAMING_SNAKE_CASE ) snake_case_ = {test_class: get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) for test_class in test_classes} return test_tester_mapping def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: snake_case_ = get_model_classes(_SCREAMING_SNAKE_CASE ) snake_case_ = { model_class: get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_test_mapping def _a ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = get_model_classes(_SCREAMING_SNAKE_CASE ) snake_case_ = { model_class: get_tester_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_to_tester_mapping def _a ( _SCREAMING_SNAKE_CASE ) -> Any: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o.__name__ elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): return [to_json(_SCREAMING_SNAKE_CASE ) for x in o] elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {to_json(_SCREAMING_SNAKE_CASE ): to_json(_SCREAMING_SNAKE_CASE ) for k, v in o.items()} else: return o
2
"""simple docstring""" from __future__ import annotations from collections import deque class __A : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : list[str] ) ->List[Any]: """simple docstring""" snake_case_ = [] self.adlist.append( {"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} ) for keyword in keywords: self.add_keyword(UpperCAmelCase_ ) self.set_fail_transitions() def lowerCAmelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : str ) ->int | None: """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def lowerCAmelCase ( self : int , UpperCAmelCase_ : str ) ->None: """simple docstring""" snake_case_ = 0 for character in keyword: snake_case_ = self.find_next_state(UpperCAmelCase_ , UpperCAmelCase_ ) if next_state is None: self.adlist.append( { """value""": character, """next_states""": [], """fail_state""": 0, """output""": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) snake_case_ = len(self.adlist ) - 1 else: snake_case_ = next_state self.adlist[current_state]["output"].append(UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->None: """simple docstring""" snake_case_ = deque() for node in self.adlist[0]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = 0 while q: snake_case_ = q.popleft() for child in self.adlist[r]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = self.adlist[r]["""fail_state"""] while ( self.find_next_state(UpperCAmelCase_ , self.adlist[child]["""value"""] ) is None and state != 0 ): snake_case_ = self.adlist[state]["""fail_state"""] snake_case_ = self.find_next_state( UpperCAmelCase_ , self.adlist[child]["""value"""] ) if self.adlist[child]["fail_state"] is None: snake_case_ = 0 snake_case_ = ( self.adlist[child]["""output"""] + self.adlist[self.adlist[child]["""fail_state"""]]["""output"""] ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->dict[str, list[int]]: """simple docstring""" snake_case_ = {} # returns a dict with keywords and list of its occurrences snake_case_ = 0 for i in range(len(UpperCAmelCase_ ) ): while ( self.find_next_state(UpperCAmelCase_ , string[i] ) is None and current_state != 0 ): snake_case_ = self.adlist[current_state]["""fail_state"""] snake_case_ = self.find_next_state(UpperCAmelCase_ , string[i] ) if next_state is None: snake_case_ = 0 else: snake_case_ = next_state for key in self.adlist[current_state]["output"]: if key not in result: snake_case_ = [] result[key].append(i - len(UpperCAmelCase_ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = KandinskyVaaControlnetPipeline __lowercase: str = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: Union[str, Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowercase: Tuple = False @property def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return 100 @property def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) snake_case_ = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } snake_case_ = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=UpperCAmelCase_ , ) snake_case_ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]=0 ) ->List[str]: """simple docstring""" snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) # create hint snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("""mps""" ): snake_case_ = torch.manual_seed(UpperCAmelCase_ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) snake_case_ = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" snake_case_ = """cpu""" snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**UpperCAmelCase_ ) snake_case_ = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) snake_case_ = torch.from_numpy(np.array(UpperCAmelCase_ ) ).float() / 255.0 snake_case_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case_ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) snake_case_ = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = """A robot, 4k photo""" snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ , snake_case_ = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , hint=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
2
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=13 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=[10, 20, 30, 40] , UpperCAmelCase_ : List[Any]=[2, 2, 3, 2] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : int=["stage2", "stage3", "stage4"] , UpperCAmelCase_ : Optional[int]=[2, 3, 4] , UpperCAmelCase_ : List[str]=None , ) ->Union[str, Any]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = num_stages snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = out_features snake_case_ = out_indices snake_case_ = scope def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = ConvNextVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = ConvNextVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __lowercase: Union[str, Any] = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Optional[Any] = False __lowercase: Any = False __lowercase: Union[str, Any] = False __lowercase: Dict = False def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = True if model_class.__name__ in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ]: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = False snake_case_ = True if ( model_class.__name__ in [*get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ )] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ): snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ConvNextVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> str: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(UpperCAmelCase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = preprocessor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
2
1
"""simple docstring""" import requests from bsa import BeautifulSoup def _a ( _SCREAMING_SNAKE_CASE = "AAPL" ) -> str: snake_case_ = f"""https://in.finance.yahoo.com/quote/{symbol}?s={symbol}""" snake_case_ = BeautifulSoup(requests.get(_SCREAMING_SNAKE_CASE ).text , """html.parser""" ) snake_case_ = """My(6px) Pos(r) smartphone_Mt(6px)""" return soup.find("""div""" , class_=class_ ).find("""span""" ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f"""Current {symbol:<4} stock price is {stock_price(symbol):>8}""")
2
"""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() __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : int = ['model.decoder.embed_positions.weights'] def _a ( _SCREAMING_SNAKE_CASE ) -> str: if "emb" in name: snake_case_ = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: snake_case_ = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: snake_case_ = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: snake_case_ = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: snake_case_ = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: snake_case_ = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: snake_case_ = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: snake_case_ = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: snake_case_ = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: snake_case_ = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: snake_case_ = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple[Dict, Dict]: snake_case_ = list(state_dict.keys() ) snake_case_ = {} for key in keys: snake_case_ = state_dict.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = rename_keys(_SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj snake_case_ = val[:hidden_size, :] snake_case_ = val[hidden_size : 2 * hidden_size, :] snake_case_ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: snake_case_ = val else: snake_case_ = val return state_dict, enc_dec_proj_state_dict def _a ( _SCREAMING_SNAKE_CASE ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values snake_case_ = 1_024 snake_case_ = 24 snake_case_ = 16 elif checkpoint == "medium": snake_case_ = 1_536 snake_case_ = 48 snake_case_ = 24 elif checkpoint == "large": snake_case_ = 2_048 snake_case_ = 48 snake_case_ = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) snake_case_ = MusicgenDecoderConfig( hidden_size=_SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=_SCREAMING_SNAKE_CASE , num_attention_heads=_SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="cpu" ) -> Tuple: snake_case_ = MusicGen.get_pretrained(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) snake_case_ = decoder_config_from_checkpoint(_SCREAMING_SNAKE_CASE ) snake_case_ = fairseq_model.lm.state_dict() snake_case_ , snake_case_ = rename_state_dict( _SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) snake_case_ = TaEncoderModel.from_pretrained("""t5-base""" ) snake_case_ = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) snake_case_ = MusicgenForCausalLM(_SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection snake_case_ , snake_case_ = decoder.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model snake_case_ = MusicgenForConditionalGeneration(text_encoder=_SCREAMING_SNAKE_CASE , audio_encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_SCREAMING_SNAKE_CASE ) # check we can do a forward pass snake_case_ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) snake_case_ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): snake_case_ = model(input_ids=_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor snake_case_ = AutoTokenizer.from_pretrained("""t5-base""" ) snake_case_ = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) snake_case_ = MusicgenProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids snake_case_ = 2_048 snake_case_ = 2_048 # set other default generation config params snake_case_ = int(30 * audio_encoder.config.frame_rate ) snake_case_ = True snake_case_ = 3.0 if pytorch_dump_folder is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) processor.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = 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.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
2
1
"""simple docstring""" import itertools import math def _a ( _SCREAMING_SNAKE_CASE ) -> bool: 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(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _a ( ) -> List[Any]: snake_case_ = 2 while True: if is_prime(_SCREAMING_SNAKE_CASE ): yield num num += 1 def _a ( _SCREAMING_SNAKE_CASE = 10_001 ) -> int: return next(itertools.islice(prime_generator() , nth - 1 , _SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": print(f"""{solution() = }""")
2
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: if index == number_of_items: return 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 ) if weights[index] <= max_weight: snake_case_ = values[index] + knapsack( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 ) return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
2
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 20 ) -> int: snake_case_ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... snake_case_ = n // 2 return int(factorial(_SCREAMING_SNAKE_CASE ) / (factorial(_SCREAMING_SNAKE_CASE ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: __SCREAMING_SNAKE_CASE : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
2
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : List[str]=30 , UpperCAmelCase_ : Union[str, Any]=400 , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[int]=0.9 , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Dict=[0.5, 0.5, 0.5] , UpperCAmelCase_ : int=[0.5, 0.5, 0.5] , ) ->int: """simple docstring""" snake_case_ = size if size is not None else {"""shortest_edge""": 30} snake_case_ = crop_size if crop_size is not None else {"""height""": 30, """width""": 30} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize_and_center_crop snake_case_ = size snake_case_ = crop_pct snake_case_ = crop_size snake_case_ = do_normalize snake_case_ = image_mean snake_case_ = image_std def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = PoolFormerImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" snake_case_ = PoolFormerImageProcessingTester(self ) @property def lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize_and_center_crop""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """crop_pct""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """image_mean""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """image_std""" ) ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 30} ) self.assertEqual(image_processor.crop_size , {"""height""": 30, """width""": 30} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" pass def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , Image.Image ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , numpify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , np.ndarray ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , torchify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
2
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _a ( _SCREAMING_SNAKE_CASE = 8 ) -> str: snake_case_ = ascii_letters + digits + punctuation return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(_SCREAMING_SNAKE_CASE ) snake_case_ = i // 3 snake_case_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case_ = ( chars_incl + random(_SCREAMING_SNAKE_CASE , quotient + remainder ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) snake_case_ = list(_SCREAMING_SNAKE_CASE ) shuffle(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) # random is a generalised function for letters, characters and numbers def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 8 ) -> bool: if len(_SCREAMING_SNAKE_CASE ) < min_length: # Your Password must be at least 8 characters long return False snake_case_ = any(char in ascii_uppercase for char in password ) snake_case_ = any(char in ascii_lowercase for char in password ) snake_case_ = any(char in digits for char in password ) snake_case_ = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _a ( ) -> str: snake_case_ = int(input("""Please indicate the max length of your password: """ ).strip() ) snake_case_ = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(_SCREAMING_SNAKE_CASE ) ) print( """Alternative Password generated:""" , alternative_password_generator(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
2
1
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = tempfile.mkdtemp() snake_case_ = BlipImageProcessor() snake_case_ = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-BertModel""" ) snake_case_ = BlipProcessor(UpperCAmelCase_ , UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : str , **UpperCAmelCase_ : List[str] ) ->Dict: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).tokenizer def lowerCAmelCase ( self : Dict , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).image_processor def lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case_ = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case_ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) snake_case_ = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) snake_case_ = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=UpperCAmelCase_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = BlipProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = self.prepare_image_inputs() snake_case_ = image_processor(UpperCAmelCase_ , return_tensors="""np""" ) snake_case_ = processor(images=UpperCAmelCase_ , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = BlipProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = """lower newer""" snake_case_ = processor(text=UpperCAmelCase_ ) snake_case_ = tokenizer(UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = BlipProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = """lower newer""" snake_case_ = self.prepare_image_inputs() snake_case_ = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase_ ): processor() def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = BlipProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] snake_case_ = processor.batch_decode(UpperCAmelCase_ ) snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = BlipProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = """lower newer""" snake_case_ = self.prepare_image_inputs() snake_case_ = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] )
2
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset 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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=18 , UpperCAmelCase_ : Optional[Any]=30 , UpperCAmelCase_ : str=400 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[Any]=True , ) ->Optional[Any]: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = ImageGPTImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """clusters""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) snake_case_ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key] ) ) else: self.assertEqual(obj[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(UpperCAmelCase_ , """image_processor.json""" ) image_processor_first.to_json_file(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_json_file(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_pretrained(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" pass def _a ( ) -> str: snake_case_ = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) snake_case_ = Image.open(dataset[4]["""file"""] ) snake_case_ = Image.open(dataset[5]["""file"""] ) snake_case_ = [imagea, imagea] return images @require_vision @require_torch class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) snake_case_ = prepare_images() # test non-batched snake_case_ = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_024) ) snake_case_ = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_ ) # test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_024) ) snake_case_ = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_ )
2
1
"""simple docstring""" import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup __SCREAMING_SNAKE_CASE : List[Any] = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582' } def _a ( _SCREAMING_SNAKE_CASE = "dhaka" , _SCREAMING_SNAKE_CASE = 5 ) -> int: snake_case_ = min(_SCREAMING_SNAKE_CASE , 50 ) # Prevent abuse! snake_case_ = { """q""": query, """tbm""": """isch""", """hl""": """en""", """ijn""": """0""", } snake_case_ = requests.get("""https://www.google.com/search""" , params=_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ) snake_case_ = BeautifulSoup(html.text , """html.parser""" ) snake_case_ = """""".join( re.findall(r"""AF_initDataCallback\(([^<]+)\);""" , str(soup.select("""script""" ) ) ) ) snake_case_ = json.dumps(_SCREAMING_SNAKE_CASE ) snake_case_ = json.loads(_SCREAMING_SNAKE_CASE ) snake_case_ = re.findall( r"""\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",""" , _SCREAMING_SNAKE_CASE , ) if not matched_google_image_data: return 0 snake_case_ = re.sub( r"""\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]""" , """""" , str(_SCREAMING_SNAKE_CASE ) , ) snake_case_ = re.findall( r"""(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]""" , _SCREAMING_SNAKE_CASE , ) for index, fixed_full_res_image in enumerate(_SCREAMING_SNAKE_CASE ): if index >= max_images: return index snake_case_ = bytes(_SCREAMING_SNAKE_CASE , """ascii""" ).decode( """unicode-escape""" ) snake_case_ = bytes(_SCREAMING_SNAKE_CASE , """ascii""" ).decode( """unicode-escape""" ) snake_case_ = urllib.request.build_opener() snake_case_ = [ ( """User-Agent""", """Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36""" """ (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582""", ) ] urllib.request.install_opener(_SCREAMING_SNAKE_CASE ) snake_case_ = f"""query_{query.replace(" " , "_" )}""" if not os.path.exists(_SCREAMING_SNAKE_CASE ): os.makedirs(_SCREAMING_SNAKE_CASE ) urllib.request.urlretrieve( # noqa: S310 _SCREAMING_SNAKE_CASE , f"""{path_name}/original_size_img_{index}.jpg""" ) return index if __name__ == "__main__": try: __SCREAMING_SNAKE_CASE : Optional[int] = download_images_from_google_query(sys.argv[1]) print(f"""{image_count} images were downloaded to disk.""") except IndexError: print('Please provide a search term.') raise
2
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : Dict=24 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=1_000 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = scope snake_case_ = range_bbox def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = t if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = t snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->str: """simple docstring""" snake_case_ = LiltModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , ) ->Dict: """simple docstring""" snake_case_ = self.num_labels snake_case_ = LiltForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , ) ->Dict: """simple docstring""" snake_case_ = LiltForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowercase: Optional[Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: List[str] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ = LiltModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = LiltModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCAmelCase_ ) snake_case_ = torch.tensor([[1, 2]] , device=UpperCAmelCase_ ) snake_case_ = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ ) snake_case_ = torch.Size([1, 2, 768] ) snake_case_ = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=UpperCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase_ , atol=1E-3 ) )
2
1
"""simple docstring""" import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any]=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : List[Any]=18 , UpperCAmelCase_ : int=30 , UpperCAmelCase_ : List[Any]=400 , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=[0.5, 0.5, 0.5] , UpperCAmelCase_ : Optional[int]=[0.5, 0.5, 0.5] , UpperCAmelCase_ : int=False , ) ->str: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 20, """width""": 20} snake_case_ = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_center_crop snake_case_ = crop_size snake_case_ = do_normalize snake_case_ = image_mean snake_case_ = image_std snake_case_ = do_reduce_labels def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def _a ( ) -> List[Any]: snake_case_ = load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) snake_case_ = Image.open(dataset[0]["""file"""] ) snake_case_ = Image.open(dataset[1]["""file"""] ) return image, map def _a ( ) -> Dict: snake_case_ = load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) snake_case_ = Image.open(ds[0]["""file"""] ) snake_case_ = Image.open(ds[1]["""file"""] ) snake_case_ = Image.open(ds[2]["""file"""] ) snake_case_ = Image.open(ds[3]["""file"""] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[str] = BeitImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" snake_case_ = BeitImageProcessingTester(self ) @property def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_center_crop""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """center_crop""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """image_mean""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """image_std""" ) ) def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 20, """width""": 20} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) self.assertEqual(image_processor.do_reduce_labels , UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=UpperCAmelCase_ ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) self.assertEqual(image_processor.do_reduce_labels , UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , Image.Image ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , numpify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , np.ndarray ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , torchify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , torchify=UpperCAmelCase_ ) snake_case_ = [] for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , maps[0] , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 1, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , UpperCAmelCase_ , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test not batched input (PIL images) snake_case_ , snake_case_ = prepare_semantic_single_inputs() snake_case_ = image_processing(UpperCAmelCase_ , UpperCAmelCase_ , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 1, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test batched input (PIL images) snake_case_ , snake_case_ = prepare_semantic_batch_inputs() snake_case_ = image_processing(UpperCAmelCase_ , UpperCAmelCase_ , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 2, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 snake_case_ , snake_case_ = prepare_semantic_single_inputs() snake_case_ = image_processing(UpperCAmelCase_ , UpperCAmelCase_ , return_tensors="""pt""" ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 150 ) snake_case_ = True snake_case_ = image_processing(UpperCAmelCase_ , UpperCAmelCase_ , return_tensors="""pt""" ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 )
2
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
2
1
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset 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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=18 , UpperCAmelCase_ : Optional[Any]=30 , UpperCAmelCase_ : str=400 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[Any]=True , ) ->Optional[Any]: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = ImageGPTImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """clusters""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) snake_case_ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key] ) ) else: self.assertEqual(obj[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(UpperCAmelCase_ , """image_processor.json""" ) image_processor_first.to_json_file(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_json_file(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_pretrained(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" pass def _a ( ) -> str: snake_case_ = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) snake_case_ = Image.open(dataset[4]["""file"""] ) snake_case_ = Image.open(dataset[5]["""file"""] ) snake_case_ = [imagea, imagea] return images @require_vision @require_torch class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) snake_case_ = prepare_images() # test non-batched snake_case_ = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_024) ) snake_case_ = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_ ) # test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_024) ) snake_case_ = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_ )
2
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
"""simple docstring""" import datasets __SCREAMING_SNAKE_CASE : Dict = '\\n@InProceedings{conneau2018xnli,\n author = "Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin",\n title = "XNLI: Evaluating Cross-lingual Sentence Representations",\n booktitle = "Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing",\n year = "2018",\n publisher = "Association for Computational Linguistics",\n location = "Brussels, Belgium",\n}\n' __SCREAMING_SNAKE_CASE : str = '\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n' __SCREAMING_SNAKE_CASE : List[Any] = '\nComputes XNLI score which is just simple accuracy.\nArgs:\n predictions: Predicted labels.\n references: Ground truth labels.\nReturns:\n \'accuracy\': accuracy\nExamples:\n\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> xnli_metric = datasets.load_metric("xnli")\n >>> results = xnli_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n' def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __A (datasets.Metric): '''simple docstring''' def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), """references""": datasets.Value("""int64""" if self.config_name != """sts-b""" else """float32""" ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" , ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple ) ->List[str]: """simple docstring""" return {"accuracy": simple_accuracy(UpperCAmelCase_ , UpperCAmelCase_ )}
2
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): __SCREAMING_SNAKE_CASE : Tuple = yaml.safe_load( '\\nname: ""\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: "Dataset Card for X" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: "Table of Contents"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Dataset Description"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: "Dataset Summary"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Supported Tasks and Leaderboards"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n' ) __SCREAMING_SNAKE_CASE : Any = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } __SCREAMING_SNAKE_CASE : Any = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Dict = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : List[str] = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Extra Ignored Subsection', 'text': '', 'is_empty_text': True, 'subsections': [], } ], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } __SCREAMING_SNAKE_CASE : List[Any] = '\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Union[str, Any] = ( 'The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.' ) __SCREAMING_SNAKE_CASE : int = '\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Tuple = ( 'The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.' ) __SCREAMING_SNAKE_CASE : int = '\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Tuple = 'The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.' __SCREAMING_SNAKE_CASE : List[str] = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : int = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).' __SCREAMING_SNAKE_CASE : int = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n' __SCREAMING_SNAKE_CASE : Any = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.' __SCREAMING_SNAKE_CASE : Any = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : List[str] = 'The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.' __SCREAMING_SNAKE_CASE : List[Any] = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n' __SCREAMING_SNAKE_CASE : Dict = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.' __SCREAMING_SNAKE_CASE : Tuple = '\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Dict = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.' __SCREAMING_SNAKE_CASE : Any = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n' __SCREAMING_SNAKE_CASE : Tuple = 'The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.' __SCREAMING_SNAKE_CASE : List[str] = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : List[Any] = 'The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.' __SCREAMING_SNAKE_CASE : Tuple = '' __SCREAMING_SNAKE_CASE : List[str] = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.' __SCREAMING_SNAKE_CASE : List[Any] = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Optional[int] = 'The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.' @pytest.mark.parametrize( """readme_md, expected_dict""" , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: assert ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to_dict() == expected_dict @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path="""root""" ) ) ): snake_case_ = ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path="""root""" ) ) ): ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """readme_md,""" , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , suppress_parsing_errors=_SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """readme_md, expected_dict""" , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = Path(_SCREAMING_SNAKE_CASE ) / """README.md""" with open(_SCREAMING_SNAKE_CASE , """w+""" ) as readme_file: readme_file.write(_SCREAMING_SNAKE_CASE ) snake_case_ = ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = Path(_SCREAMING_SNAKE_CASE ) / """README.md""" with open(_SCREAMING_SNAKE_CASE , """w+""" ) as readme_file: readme_file.write(_SCREAMING_SNAKE_CASE ) snake_case_ = expected_error.format(path=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ): snake_case_ = ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = Path(_SCREAMING_SNAKE_CASE ) / """README.md""" with open(_SCREAMING_SNAKE_CASE , """w+""" ) as readme_file: readme_file.write(_SCREAMING_SNAKE_CASE ) snake_case_ = expected_error.format(path=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ): ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """readme_md,""" , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def _a ( _SCREAMING_SNAKE_CASE ) -> int: with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = Path(_SCREAMING_SNAKE_CASE ) / """README.md""" with open(_SCREAMING_SNAKE_CASE , """w+""" ) as readme_file: readme_file.write(_SCREAMING_SNAKE_CASE ) ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , suppress_parsing_errors=_SCREAMING_SNAKE_CASE )
2
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : List[str] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __SCREAMING_SNAKE_CASE : List[str] = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __SCREAMING_SNAKE_CASE : int = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[Any] = VOCAB_FILES_NAMES __lowercase: Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowercase: Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]="[CLS]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : str="<unk>" , UpperCAmelCase_ : str="[SEP]" , UpperCAmelCase_ : Optional[Any]="<pad>" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : int="[MASK]" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->None: """simple docstring""" snake_case_ = ( AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ , normalized=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token ) snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = do_lower_case snake_case_ = remove_space snake_case_ = keep_accents snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return len(self.sp_model ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Any ) ->str: """simple docstring""" if self.remove_space: snake_case_ = """ """.join(inputs.strip().split() ) else: snake_case_ = inputs snake_case_ = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: snake_case_ = unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) snake_case_ = """""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: snake_case_ = outputs.lower() return outputs def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.preprocess_text(UpperCAmelCase_ ) snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) snake_case_ = [] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): snake_case_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case_ = cur_pieces[1:] else: snake_case_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" return self.sp_model.PieceToId(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" return self.sp_model.IdToPiece(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Dict ) ->Any: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
2
1
"""simple docstring""" import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore __SCREAMING_SNAKE_CASE : Union[str, Any] = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" __SCREAMING_SNAKE_CASE : Optional[Any] = [file for file in filepaths if file != file.lower()] if upper_files: print(f"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') __SCREAMING_SNAKE_CASE : List[str] = [file for file in filepaths if ' ' in file] if space_files: print(f"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') __SCREAMING_SNAKE_CASE : List[Any] = [file for file in filepaths if '-' in file] if hyphen_files: print(f"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') __SCREAMING_SNAKE_CASE : List[str] = [file for file in filepaths if os.sep not in file] if nodir_files: print(f"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') __SCREAMING_SNAKE_CASE : str = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
2
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Any=7 , UpperCAmelCase_ : int=3 , UpperCAmelCase_ : List[Any]=18 , UpperCAmelCase_ : str=30 , UpperCAmelCase_ : Tuple=400 , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : str=None , UpperCAmelCase_ : str=True , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : int=True , ) ->List[str]: """simple docstring""" snake_case_ = size if size is not None else {"""shortest_edge""": 20} snake_case_ = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_center_crop snake_case_ = crop_size snake_case_ = do_flip_channel_order def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Tuple = MobileViTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" snake_case_ = MobileViTImageProcessingTester(self ) @property def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_center_crop""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """center_crop""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_flip_channel_order""" ) ) def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 20} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , Image.Image ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , numpify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , np.ndarray ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase ( self : str ) ->str: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , torchify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
2
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : List[str] = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class __A (snake_case__): '''simple docstring''' __lowercase: Dict = """ctrl""" __lowercase: Optional[Any] = ["""past_key_values"""] __lowercase: Optional[Any] = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : List[str] , UpperCAmelCase_ : Dict=246_534 , UpperCAmelCase_ : List[Any]=256 , UpperCAmelCase_ : Dict=1_280 , UpperCAmelCase_ : List[str]=8_192 , UpperCAmelCase_ : str=48 , UpperCAmelCase_ : List[str]=16 , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : List[str]=1E-6 , UpperCAmelCase_ : List[Any]=0.02 , UpperCAmelCase_ : int=True , **UpperCAmelCase_ : int , ) ->Dict: """simple docstring""" snake_case_ = vocab_size snake_case_ = n_positions snake_case_ = n_embd snake_case_ = n_layer snake_case_ = n_head snake_case_ = dff snake_case_ = resid_pdrop snake_case_ = embd_pdrop snake_case_ = layer_norm_epsilon snake_case_ = initializer_range snake_case_ = use_cache super().__init__(**UpperCAmelCase_ )
2
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: snake_case_ = b.T snake_case_ = np.sum(np.square(_SCREAMING_SNAKE_CASE ) , axis=1 ) snake_case_ = np.sum(np.square(_SCREAMING_SNAKE_CASE ) , axis=0 ) snake_case_ = np.matmul(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = aa[:, None] - 2 * ab + ba[None, :] return d def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = x.reshape(-1 , 3 ) snake_case_ = squared_euclidean_distance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return np.argmin(_SCREAMING_SNAKE_CASE , axis=1 ) class __A (snake_case__): '''simple docstring''' __lowercase: str = ["""pixel_values"""] def __init__( self : Tuple , UpperCAmelCase_ : Optional[Union[List[List[int]], np.ndarray]] = None , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , **UpperCAmelCase_ : Optional[int] , ) ->None: """simple docstring""" super().__init__(**UpperCAmelCase_ ) snake_case_ = size if size is not None else {"""height""": 256, """width""": 256} snake_case_ = get_size_dict(UpperCAmelCase_ ) snake_case_ = np.array(UpperCAmelCase_ ) if clusters is not None else None snake_case_ = do_resize snake_case_ = size snake_case_ = resample snake_case_ = do_normalize snake_case_ = do_color_quantize def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Tuple , ) ->np.ndarray: """simple docstring""" snake_case_ = get_size_dict(UpperCAmelCase_ ) if "height" not in size or "width" not in size: raise ValueError(F"""Size dictionary must contain both height and width keys. Got {size.keys()}""" ) return resize( UpperCAmelCase_ , size=(size["""height"""], size["""width"""]) , resample=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , ) ->np.ndarray: """simple docstring""" snake_case_ = rescale(image=UpperCAmelCase_ , scale=1 / 127.5 , data_format=UpperCAmelCase_ ) snake_case_ = image - 1 return image def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : ImageInput , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[Union[List[List[int]], np.ndarray]] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **UpperCAmelCase_ : Any , ) ->PIL.Image.Image: """simple docstring""" snake_case_ = do_resize if do_resize is not None else self.do_resize snake_case_ = size if size is not None else self.size snake_case_ = get_size_dict(UpperCAmelCase_ ) snake_case_ = resample if resample is not None else self.resample snake_case_ = do_normalize if do_normalize is not None else self.do_normalize snake_case_ = do_color_quantize if do_color_quantize is not None else self.do_color_quantize snake_case_ = clusters if clusters is not None else self.clusters snake_case_ = np.array(UpperCAmelCase_ ) snake_case_ = make_list_of_images(UpperCAmelCase_ ) if not valid_images(UpperCAmelCase_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_color_quantize and clusters is None: raise ValueError("""Clusters must be specified if do_color_quantize is True.""" ) # All transformations expect numpy arrays. snake_case_ = [to_numpy_array(UpperCAmelCase_ ) for image in images] if do_resize: snake_case_ = [self.resize(image=UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ ) for image in images] if do_normalize: snake_case_ = [self.normalize(image=UpperCAmelCase_ ) for image in images] if do_color_quantize: snake_case_ = [to_channel_dimension_format(UpperCAmelCase_ , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) snake_case_ = np.array(UpperCAmelCase_ ) snake_case_ = color_quantize(UpperCAmelCase_ , UpperCAmelCase_ ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) snake_case_ = images.shape[0] snake_case_ = images.reshape(UpperCAmelCase_ , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. snake_case_ = list(UpperCAmelCase_ ) else: snake_case_ = [to_channel_dimension_format(UpperCAmelCase_ , UpperCAmelCase_ ) for image in images] snake_case_ = {"""input_ids""": images} return BatchFeature(data=UpperCAmelCase_ , tensor_type=UpperCAmelCase_ )
2
"""simple docstring""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): '''simple docstring''' @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
2
1
"""simple docstring""" import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> str: try: snake_case_ = os.environ[key] except KeyError: # KEY isn't set, default to `default`. snake_case_ = default else: # KEY is set, convert it to True or False. try: snake_case_ = strtobool(_SCREAMING_SNAKE_CASE ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f"""If set, {key} must be yes or no.""" ) return _value __SCREAMING_SNAKE_CASE : List[Any] = parse_flag_from_env('RUN_SLOW', default=False) def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: return unittest.skip("""Test was skipped""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: return unittest.skipUnless(_run_slow_tests , """test is slow""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> int: return unittest.skipUnless(not torch.cuda.is_available() , """test requires only a CPU""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: return unittest.skipUnless(torch.cuda.is_available() , """test requires a GPU""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: return unittest.skipUnless(is_xpu_available() , """test requires a XPU""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: return unittest.skipUnless(is_mps_available() , """test requires a `mps` backend support in `torch`""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: return unittest.skipUnless( is_transformers_available() and is_datasets_available() , """test requires the Hugging Face suite""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: return unittest.skipUnless(is_bnb_available() , """test requires the bitsandbytes library""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> str: return unittest.skipUnless(is_tpu_available() , """test requires TPU""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: return unittest.skipUnless(torch.cuda.device_count() == 1 , """test requires a GPU""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: return unittest.skipUnless(torch.xpu.device_count() == 1 , """test requires a XPU""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: return unittest.skipUnless(torch.cuda.device_count() > 1 , """test requires multiple GPUs""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> str: return unittest.skipUnless(torch.xpu.device_count() > 1 , """test requires multiple XPUs""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Tuple: return unittest.skipUnless(is_safetensors_available() , """test requires safetensors""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> str: return unittest.skipUnless(is_deepspeed_available() , """test requires DeepSpeed""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: return unittest.skipUnless(is_torch_version(""">=""" , """1.12.0""" ) , """test requires torch version >= 1.12.0""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: if test_case is None: return partial(_SCREAMING_SNAKE_CASE , version=_SCREAMING_SNAKE_CASE ) return unittest.skipUnless(is_torch_version(""">=""" , _SCREAMING_SNAKE_CASE ) , f"""test requires torch version >= {version}""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: return unittest.skipUnless(is_tensorboard_available() , """test requires Tensorboard""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Tuple: return unittest.skipUnless(is_wandb_available() , """test requires wandb""" )(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Dict: return unittest.skipUnless(is_comet_ml_available() , """test requires comet_ml""" )(_SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : Any = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def _a ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: return unittest.skipUnless( _atleast_one_tracker_available , """test requires at least one tracker to be available and for `comet_ml` to not be installed""" , )(_SCREAMING_SNAKE_CASE ) class __A (unittest.TestCase): '''simple docstring''' __lowercase: Tuple = True @classmethod def lowerCAmelCase ( cls : Tuple ) ->str: """simple docstring""" snake_case_ = tempfile.mkdtemp() @classmethod def lowerCAmelCase ( cls : Tuple ) ->Any: """simple docstring""" if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" if self.clear_on_setup: for path in Path(self.tmpdir ).glob("""**/*""" ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(UpperCAmelCase_ ) class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Union[mock.Mock, List[mock.Mock]] ) ->str: """simple docstring""" snake_case_ = mocks if isinstance(UpperCAmelCase_ , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: snake_case_ = AcceleratorState() snake_case_ = tensor[None].clone().to(state.device ) snake_case_ = gather(_SCREAMING_SNAKE_CASE ).cpu() snake_case_ = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i] , _SCREAMING_SNAKE_CASE ): return False return True class __A : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : int ) ->Any: """simple docstring""" snake_case_ = returncode snake_case_ = stdout snake_case_ = stderr async def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: while True: snake_case_ = await stream.readline() if line: callback(_SCREAMING_SNAKE_CASE ) else: break async def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False ) -> _RunOutput: if echo: print("""\nRunning: """ , """ """.join(_SCREAMING_SNAKE_CASE ) ) snake_case_ = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=_SCREAMING_SNAKE_CASE , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=_SCREAMING_SNAKE_CASE , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) snake_case_ = [] snake_case_ = [] def tee(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="" ): snake_case_ = line.decode("""utf-8""" ).rstrip() sink.append(_SCREAMING_SNAKE_CASE ) if not quiet: print(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , file=_SCREAMING_SNAKE_CASE ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout , lambda _SCREAMING_SNAKE_CASE : tee(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , sys.stdout , label="""stdout:""" ) ) ), asyncio.create_task(_read_stream(p.stderr , lambda _SCREAMING_SNAKE_CASE : tee(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , sys.stderr , label="""stderr:""" ) ) ), ] , timeout=_SCREAMING_SNAKE_CASE , ) return _RunOutput(await p.wait() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=180 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True ) -> _RunOutput: snake_case_ = asyncio.get_event_loop() snake_case_ = loop.run_until_complete( _stream_subprocess(_SCREAMING_SNAKE_CASE , env=_SCREAMING_SNAKE_CASE , stdin=_SCREAMING_SNAKE_CASE , timeout=_SCREAMING_SNAKE_CASE , quiet=_SCREAMING_SNAKE_CASE , echo=_SCREAMING_SNAKE_CASE ) ) snake_case_ = """ """.join(_SCREAMING_SNAKE_CASE ) if result.returncode > 0: snake_case_ = """\n""".join(result.stderr ) raise RuntimeError( f"""'{cmd_str}' failed with returncode {result.returncode}\n\n""" f"""The combined stderr from workers follows:\n{stderr}""" ) return result class __A (snake_case__): '''simple docstring''' pass def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> List[str]: try: snake_case_ = subprocess.check_output(_SCREAMING_SNAKE_CASE , stderr=subprocess.STDOUT ) if return_stdout: if hasattr(_SCREAMING_SNAKE_CASE , """decode""" ): snake_case_ = output.decode("""utf-8""" ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( f"""Command `{" ".join(_SCREAMING_SNAKE_CASE )}` failed with the following error:\n\n{e.output.decode()}""" ) from e
2
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=snake_case__) class __A (snake_case__): '''simple docstring''' __lowercase: str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True}) __lowercase: ClassVar[Features] = Features({"""audio""": Audio()}) __lowercase: ClassVar[Features] = Features({"""transcription""": Value("""string""")}) __lowercase: str = "audio" __lowercase: str = "transcription" def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , UpperCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) snake_case_ = copy.deepcopy(self ) snake_case_ = self.input_schema.copy() snake_case_ = features[self.audio_column] snake_case_ = input_schema return task_template @property def lowerCAmelCase ( self : List[str] ) ->Dict[str, str]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
2
1
"""simple docstring""" import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) __SCREAMING_SNAKE_CASE : Optional[Any] = '\\n Text data.\n Second line of data.' __SCREAMING_SNAKE_CASE : List[str] = 'file' @pytest.fixture(scope="""session""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") snake_case_ = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with zstd.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture def _a ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: with open(os.path.join(tmpfs.local_root_dir , _SCREAMING_SNAKE_CASE ) , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: snake_case_ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} snake_case_ = input_paths[compression_format] snake_case_ = tmp_path / """cache""" snake_case_ = DownloadConfig(cache_dir=_SCREAMING_SNAKE_CASE , extract_compressed_file=_SCREAMING_SNAKE_CASE ) snake_case_ = cached_path(_SCREAMING_SNAKE_CASE , download_config=_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE ) as f: snake_case_ = f.read() with open(_SCREAMING_SNAKE_CASE ) as f: snake_case_ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: snake_case_ = """custom_cache""" snake_case_ = """custom_extracted_dir""" snake_case_ = tmp_path / """custom_extracted_path""" if default_extracted: snake_case_ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , _SCREAMING_SNAKE_CASE ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(_SCREAMING_SNAKE_CASE ) ) snake_case_ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) snake_case_ = xz_file snake_case_ = ( DownloadConfig(extract_compressed_file=_SCREAMING_SNAKE_CASE ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_SCREAMING_SNAKE_CASE ) ) snake_case_ = cached_path(_SCREAMING_SNAKE_CASE , download_config=_SCREAMING_SNAKE_CASE ) assert Path(_SCREAMING_SNAKE_CASE ).parent.parts[-2:] == expected def _a ( _SCREAMING_SNAKE_CASE ) -> Any: # absolute path snake_case_ = str(Path(_SCREAMING_SNAKE_CASE ).resolve() ) assert cached_path(_SCREAMING_SNAKE_CASE ) == text_file # relative path snake_case_ = str(Path(_SCREAMING_SNAKE_CASE ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(_SCREAMING_SNAKE_CASE ) == text_file def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: # absolute path snake_case_ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(_SCREAMING_SNAKE_CASE ): cached_path(_SCREAMING_SNAKE_CASE ) # relative path snake_case_ = """./__missing_file__.txt""" with pytest.raises(_SCREAMING_SNAKE_CASE ): cached_path(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = get_from_cache(f"""tmp://{tmpfs_file}""" ) with open(_SCREAMING_SNAKE_CASE ) as f: snake_case_ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _SCREAMING_SNAKE_CASE ) def _a ( ) -> Tuple: with pytest.raises(_SCREAMING_SNAKE_CASE ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Dict: snake_case_ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(_SCREAMING_SNAKE_CASE ): http_get("""https://huggingface.co""" , temp_file=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Dict: snake_case_ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(_SCREAMING_SNAKE_CASE ): ftp_get("""ftp://huggingface.co""" , temp_file=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(_SCREAMING_SNAKE_CASE ): fsspec_get("""s3://huggingface.co""" , temp_file=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE ): fsspec_head("""s3://huggingface.co""" )
2
"""simple docstring""" from functools import reduce __SCREAMING_SNAKE_CASE : Tuple = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _a ( _SCREAMING_SNAKE_CASE = N ) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str(int(_SCREAMING_SNAKE_CASE ) * int(_SCREAMING_SNAKE_CASE ) ) , n[i : i + 13] ) ) for i in range(len(_SCREAMING_SNAKE_CASE ) - 12 ) ) if __name__ == "__main__": print(f"""{solution() = }""")
2
1
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=10 ) -> Optional[int]: snake_case_ = [] for _ in range(_SCREAMING_SNAKE_CASE ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=10 ) -> int: snake_case_ = [] for step in range(_SCREAMING_SNAKE_CASE ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(_SCREAMING_SNAKE_CASE , """schedule.bin""" ) torch.save(scheduler.state_dict() , _SCREAMING_SNAKE_CASE ) snake_case_ = torch.load(_SCREAMING_SNAKE_CASE ) scheduler.load_state_dict(_SCREAMING_SNAKE_CASE ) return lrs @require_torch class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str ) ->Optional[Any]: """simple docstring""" self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) ) for a, b in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assertAlmostEqual(UpperCAmelCase_ , UpperCAmelCase_ , delta=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = torch.tensor([0.1, -0.2, -0.1] , requires_grad=UpperCAmelCase_ ) snake_case_ = torch.tensor([0.4, 0.2, -0.5] ) snake_case_ = nn.MSELoss() # No warmup, constant schedule, no gradient clipping snake_case_ = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 ) for _ in range(100 ): snake_case_ = criterion(UpperCAmelCase_ , UpperCAmelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" snake_case_ = torch.tensor([0.1, -0.2, -0.1] , requires_grad=UpperCAmelCase_ ) snake_case_ = torch.tensor([0.4, 0.2, -0.5] ) snake_case_ = nn.MSELoss() # No warmup, constant schedule, no gradient clipping snake_case_ = Adafactor( params=[w] , lr=1E-2 , eps=(1E-30, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=UpperCAmelCase_ , weight_decay=0.0 , relative_step=UpperCAmelCase_ , scale_parameter=UpperCAmelCase_ , warmup_init=UpperCAmelCase_ , ) for _ in range(1_000 ): snake_case_ = criterion(UpperCAmelCase_ , UpperCAmelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) @require_torch class __A (unittest.TestCase): '''simple docstring''' __lowercase: int = nn.Linear(50 , 50) if is_torch_available() else None __lowercase: Tuple = AdamW(m.parameters() , lr=1_0.0) if is_torch_available() else None __lowercase: int = 10 def lowerCAmelCase ( self : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any=None ) ->Union[str, Any]: """simple docstring""" self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) ) for a, b in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assertAlmostEqual(UpperCAmelCase_ , UpperCAmelCase_ , delta=UpperCAmelCase_ , msg=UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" snake_case_ = {"""num_warmup_steps""": 2, """num_training_steps""": 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) snake_case_ = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {"""num_warmup_steps""": 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, """num_cycles""": 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, """power""": 2.0, """lr_end""": 1E-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {"""num_warmup_steps""": 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): snake_case_ , snake_case_ = data snake_case_ = scheduler_func(self.optimizer , **UpperCAmelCase_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) snake_case_ = unwrap_schedule(UpperCAmelCase_ , self.num_steps ) self.assertListAlmostEqual( UpperCAmelCase_ , UpperCAmelCase_ , tol=1E-2 , msg=F"""failed for {scheduler_func} in normal scheduler""" , ) snake_case_ = scheduler_func(self.optimizer , **UpperCAmelCase_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(UpperCAmelCase_ ) # wrap to test picklability of the schedule snake_case_ = unwrap_and_save_reload_schedule(UpperCAmelCase_ , self.num_steps ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ , msg=F"""failed for {scheduler_func} in save and reload""" ) class __A : '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : List[str] ) ->List[str]: """simple docstring""" snake_case_ = fn def __call__( self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->str: """simple docstring""" return self.fn(*UpperCAmelCase_ , **UpperCAmelCase_ ) @classmethod def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Dict ) ->List[Any]: """simple docstring""" snake_case_ = list(map(self , scheduler.lr_lambdas ) )
2
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str = { 'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json', # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class __A (snake_case__): '''simple docstring''' __lowercase: Any = """mctct""" def __init__( self : Dict , UpperCAmelCase_ : List[Any]=8_065 , UpperCAmelCase_ : Tuple=1_536 , UpperCAmelCase_ : Optional[Any]=36 , UpperCAmelCase_ : int=6_144 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Any=384 , UpperCAmelCase_ : List[str]=920 , UpperCAmelCase_ : Any=1E-5 , UpperCAmelCase_ : Any=0.3 , UpperCAmelCase_ : Tuple="relu" , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Dict=0.3 , UpperCAmelCase_ : str=0.3 , UpperCAmelCase_ : Any=1 , UpperCAmelCase_ : Any=0 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=0.3 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : Optional[Any]=(7,) , UpperCAmelCase_ : Optional[Any]=(3,) , UpperCAmelCase_ : List[str]=80 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[str]="sum" , UpperCAmelCase_ : Union[str, Any]=False , **UpperCAmelCase_ : Any , ) ->Dict: """simple docstring""" super().__init__(**UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = intermediate_size snake_case_ = num_attention_heads snake_case_ = attention_head_dim snake_case_ = max_position_embeddings snake_case_ = layer_norm_eps snake_case_ = layerdrop snake_case_ = hidden_act snake_case_ = initializer_range snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id snake_case_ = conv_glu_dim snake_case_ = conv_dropout snake_case_ = num_conv_layers snake_case_ = input_feat_per_channel snake_case_ = input_channels snake_case_ = conv_channels snake_case_ = ctc_loss_reduction snake_case_ = ctc_zero_infinity # prevents config testing fail with exporting to json snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """ F"""but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, """ F"""`config.num_conv_layers = {self.num_conv_layers}`.""" )
2
1
"""simple docstring""" import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def _a ( ) -> None: print("""Making key files...""" ) make_key_files("""rsa""" , 1_024 ) print("""Key files generation successful.""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> tuple[tuple[int, int], tuple[int, int]]: print("""Generating prime p...""" ) snake_case_ = rabinMiller.generate_large_prime(_SCREAMING_SNAKE_CASE ) print("""Generating prime q...""" ) snake_case_ = rabinMiller.generate_large_prime(_SCREAMING_SNAKE_CASE ) snake_case_ = p * q print("""Generating e that is relatively prime to (p - 1) * (q - 1)...""" ) while True: snake_case_ = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(_SCREAMING_SNAKE_CASE , (p - 1) * (q - 1) ) == 1: break print("""Calculating d that is mod inverse of e...""" ) snake_case_ = cryptoMath.find_mod_inverse(_SCREAMING_SNAKE_CASE , (p - 1) * (q - 1) ) snake_case_ = (n, e) snake_case_ = (n, d) return (public_key, private_key) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> None: if os.path.exists(f"""{name}_pubkey.txt""" ) or os.path.exists(f"""{name}_privkey.txt""" ): print("""\nWARNING:""" ) print( f"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n""" """Use a different name or delete these files and re-run this program.""" ) sys.exit() snake_case_ , snake_case_ = generate_key(_SCREAMING_SNAKE_CASE ) print(f"""\nWriting public key to file {name}_pubkey.txt...""" ) with open(f"""{name}_pubkey.txt""" , """w""" ) as out_file: out_file.write(f"""{key_size},{public_key[0]},{public_key[1]}""" ) print(f"""Writing private key to file {name}_privkey.txt...""" ) with open(f"""{name}_privkey.txt""" , """w""" ) as out_file: out_file.write(f"""{key_size},{private_key[0]},{private_key[1]}""" ) if __name__ == "__main__": main()
2
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 100 ) -> int: return sum(int(_SCREAMING_SNAKE_CASE ) for x in str(factorial(_SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
2
1
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ = tempfile.mkdtemp() snake_case_ = SamImageProcessor() snake_case_ = SamProcessor(UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : List[Any] , **UpperCAmelCase_ : Any ) ->Tuple: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).image_processor def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" snake_case_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case_ = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" snake_case_ = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case_ = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) snake_case_ = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=UpperCAmelCase_ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = self.prepare_image_inputs() snake_case_ = image_processor(UpperCAmelCase_ , return_tensors="""np""" ) snake_case_ = processor(images=UpperCAmelCase_ , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = [torch.ones((1, 3, 5, 5) )] snake_case_ = [[1_764, 2_646]] snake_case_ = [[683, 1_024]] snake_case_ = processor.post_process_masks(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) snake_case_ = processor.post_process_masks( UpperCAmelCase_ , torch.tensor(UpperCAmelCase_ ) , torch.tensor(UpperCAmelCase_ ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np snake_case_ = [np.ones((1, 3, 5, 5) )] snake_case_ = processor.post_process_masks(UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) snake_case_ = [[1, 0], [0, 1]] with self.assertRaises(UpperCAmelCase_ ): snake_case_ = processor.post_process_masks(UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) ) @require_vision @require_tf class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = tempfile.mkdtemp() snake_case_ = SamImageProcessor() snake_case_ = SamProcessor(UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : Optional[Any] , **UpperCAmelCase_ : Tuple ) ->Dict: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).image_processor def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : Dict ) ->List[Any]: """simple docstring""" snake_case_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case_ = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case_ = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) snake_case_ = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=UpperCAmelCase_ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = self.prepare_image_inputs() snake_case_ = image_processor(UpperCAmelCase_ , return_tensors="""np""" ) snake_case_ = processor(images=UpperCAmelCase_ , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def lowerCAmelCase ( self : List[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = [tf.ones((1, 3, 5, 5) )] snake_case_ = [[1_764, 2_646]] snake_case_ = [[683, 1_024]] snake_case_ = processor.post_process_masks(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) snake_case_ = processor.post_process_masks( UpperCAmelCase_ , tf.convert_to_tensor(UpperCAmelCase_ ) , tf.convert_to_tensor(UpperCAmelCase_ ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np snake_case_ = [np.ones((1, 3, 5, 5) )] snake_case_ = processor.post_process_masks( UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) snake_case_ = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): snake_case_ = processor.post_process_masks( UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" snake_case_ = tempfile.mkdtemp() snake_case_ = SamImageProcessor() snake_case_ = SamProcessor(UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : Dict , **UpperCAmelCase_ : List[Any] ) ->str: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).image_processor def lowerCAmelCase ( self : int ) ->Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" snake_case_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case_ = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) snake_case_ = [tf.convert_to_tensor(UpperCAmelCase_ )] snake_case_ = [torch.tensor(UpperCAmelCase_ )] snake_case_ = [[1_764, 2_646]] snake_case_ = [[683, 1_024]] snake_case_ = processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , return_tensors="""tf""" ) snake_case_ = processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = self.prepare_image_inputs() snake_case_ = image_processor(UpperCAmelCase_ , return_tensors="""pt""" )["""pixel_values"""].numpy() snake_case_ = processor(images=UpperCAmelCase_ , return_tensors="""pt""" )["""pixel_values"""].numpy() snake_case_ = image_processor(UpperCAmelCase_ , return_tensors="""tf""" )["""pixel_values"""].numpy() snake_case_ = processor(images=UpperCAmelCase_ , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ ) )
2
"""simple docstring""" import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: str = VQModel __lowercase: Union[str, Any] = """sample""" @property def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[str]=(32, 32) ) ->Tuple: """simple docstring""" snake_case_ = 4 snake_case_ = 3 snake_case_ = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase_ ) return {"sample": image} @property def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" return (3, 32, 32) @property def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" return (3, 32, 32) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } snake_case_ = self.dummy_input return init_dict, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(UpperCAmelCase_ ) snake_case_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(UpperCAmelCase_ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) snake_case_ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) snake_case_ = image.to(UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = model(UpperCAmelCase_ ).sample snake_case_ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off snake_case_ = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 ) )
2
1
"""simple docstring""" import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. if ( (cp >= 0X4e00 and cp <= 0X9fff) or (cp >= 0X3400 and cp <= 0X4dbf) # or (cp >= 0X20000 and cp <= 0X2a6df) # or (cp >= 0X2a700 and cp <= 0X2b73f) # or (cp >= 0X2b740 and cp <= 0X2b81f) # or (cp >= 0X2b820 and cp <= 0X2ceaf) # or (cp >= 0Xf900 and cp <= 0Xfaff) or (cp >= 0X2f800 and cp <= 0X2fa1f) # ): # return True return False def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: # word like '180' or '身高' or '神' for char in word: snake_case_ = ord(_SCREAMING_SNAKE_CASE ) if not _is_chinese_char(_SCREAMING_SNAKE_CASE ): return 0 return 1 def _a ( _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = set() for token in tokens: snake_case_ = len(_SCREAMING_SNAKE_CASE ) > 1 and is_chinese(_SCREAMING_SNAKE_CASE ) if chinese_word: word_set.add(_SCREAMING_SNAKE_CASE ) snake_case_ = list(_SCREAMING_SNAKE_CASE ) return word_list def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: if not chinese_word_set: return bert_tokens snake_case_ = max([len(_SCREAMING_SNAKE_CASE ) for w in chinese_word_set] ) snake_case_ = bert_tokens snake_case_ , snake_case_ = 0, len(_SCREAMING_SNAKE_CASE ) while start < end: snake_case_ = True if is_chinese(bert_word[start] ): snake_case_ = min(end - start , _SCREAMING_SNAKE_CASE ) for i in range(_SCREAMING_SNAKE_CASE , 1 , -1 ): snake_case_ = """""".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): snake_case_ = """##""" + bert_word[j] snake_case_ = start + i snake_case_ = False break if single_word: start += 1 return bert_word def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ = [] for i in range(0 , len(_SCREAMING_SNAKE_CASE ) , 100 ): snake_case_ = ltp_tokenizer.seg(lines[i : i + 100] )[0] snake_case_ = [get_chinese_word(_SCREAMING_SNAKE_CASE ) for r in res] ltp_res.extend(_SCREAMING_SNAKE_CASE ) assert len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) snake_case_ = [] for i in range(0 , len(_SCREAMING_SNAKE_CASE ) , 100 ): snake_case_ = bert_tokenizer(lines[i : i + 100] , add_special_tokens=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , max_length=512 ) bert_res.extend(res["""input_ids"""] ) assert len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) snake_case_ = [] for input_ids, chinese_word in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = [] for id in input_ids: snake_case_ = bert_tokenizer._convert_id_to_token(_SCREAMING_SNAKE_CASE ) input_tokens.append(_SCREAMING_SNAKE_CASE ) snake_case_ = add_sub_symbol(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(_SCREAMING_SNAKE_CASE ): if token[:2] == "##": snake_case_ = token[2:] # save chinese tokens' pos if len(_SCREAMING_SNAKE_CASE ) == 1 and _is_chinese_char(ord(_SCREAMING_SNAKE_CASE ) ): ref_id.append(_SCREAMING_SNAKE_CASE ) ref_ids.append(_SCREAMING_SNAKE_CASE ) assert len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) return ref_ids def _a ( _SCREAMING_SNAKE_CASE ) -> int: # For Chinese (Ro)Bert, the best result is from : RoBERTa-wwm-ext (https://github.com/ymcui/Chinese-BERT-wwm) # If we want to fine-tune these model, we have to use same tokenizer : LTP (https://github.com/HIT-SCIR/ltp) with open(args.file_name , """r""" , encoding="""utf-8""" ) as f: snake_case_ = f.readlines() snake_case_ = [line.strip() for line in data if len(_SCREAMING_SNAKE_CASE ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' snake_case_ = LTP(args.ltp ) # faster in GPU device snake_case_ = BertTokenizer.from_pretrained(args.bert ) snake_case_ = prepare_ref(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) with open(args.save_path , """w""" , encoding="""utf-8""" ) as f: snake_case_ = [json.dumps(_SCREAMING_SNAKE_CASE ) + """\n""" for ref in ref_ids] f.writelines(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Dict = argparse.ArgumentParser(description='prepare_chinese_ref') parser.add_argument( '--file_name', type=str, default='./resources/chinese-demo.txt', help='file need process, same as training data in lm', ) parser.add_argument( '--ltp', type=str, default='./resources/ltp', help='resources for LTP tokenizer, usually a path' ) parser.add_argument('--bert', type=str, default='./resources/robert', help='resources for Bert tokenizer') parser.add_argument('--save_path', type=str, default='./resources/ref.txt', help='path to save res') __SCREAMING_SNAKE_CASE : Optional[int] = parser.parse_args() main(args)
2
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = KandinskyVaaControlnetPipeline __lowercase: str = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: Union[str, Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowercase: Tuple = False @property def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return 100 @property def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) snake_case_ = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } snake_case_ = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=UpperCAmelCase_ , ) snake_case_ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]=0 ) ->List[str]: """simple docstring""" snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) # create hint snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("""mps""" ): snake_case_ = torch.manual_seed(UpperCAmelCase_ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) snake_case_ = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" snake_case_ = """cpu""" snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**UpperCAmelCase_ ) snake_case_ = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) snake_case_ = torch.from_numpy(np.array(UpperCAmelCase_ ) ).float() / 255.0 snake_case_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case_ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) snake_case_ = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = """A robot, 4k photo""" snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ , snake_case_ = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , hint=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
2
1
"""simple docstring""" from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .modules import *
2
"""simple docstring""" from __future__ import annotations from collections import deque class __A : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : list[str] ) ->List[Any]: """simple docstring""" snake_case_ = [] self.adlist.append( {"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} ) for keyword in keywords: self.add_keyword(UpperCAmelCase_ ) self.set_fail_transitions() def lowerCAmelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : str ) ->int | None: """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def lowerCAmelCase ( self : int , UpperCAmelCase_ : str ) ->None: """simple docstring""" snake_case_ = 0 for character in keyword: snake_case_ = self.find_next_state(UpperCAmelCase_ , UpperCAmelCase_ ) if next_state is None: self.adlist.append( { """value""": character, """next_states""": [], """fail_state""": 0, """output""": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) snake_case_ = len(self.adlist ) - 1 else: snake_case_ = next_state self.adlist[current_state]["output"].append(UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->None: """simple docstring""" snake_case_ = deque() for node in self.adlist[0]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = 0 while q: snake_case_ = q.popleft() for child in self.adlist[r]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = self.adlist[r]["""fail_state"""] while ( self.find_next_state(UpperCAmelCase_ , self.adlist[child]["""value"""] ) is None and state != 0 ): snake_case_ = self.adlist[state]["""fail_state"""] snake_case_ = self.find_next_state( UpperCAmelCase_ , self.adlist[child]["""value"""] ) if self.adlist[child]["fail_state"] is None: snake_case_ = 0 snake_case_ = ( self.adlist[child]["""output"""] + self.adlist[self.adlist[child]["""fail_state"""]]["""output"""] ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->dict[str, list[int]]: """simple docstring""" snake_case_ = {} # returns a dict with keywords and list of its occurrences snake_case_ = 0 for i in range(len(UpperCAmelCase_ ) ): while ( self.find_next_state(UpperCAmelCase_ , string[i] ) is None and current_state != 0 ): snake_case_ = self.adlist[current_state]["""fail_state"""] snake_case_ = self.find_next_state(UpperCAmelCase_ , string[i] ) if next_state is None: snake_case_ = 0 else: snake_case_ = next_state for key in self.adlist[current_state]["output"]: if key not in result: snake_case_ = [] result[key].append(i - len(UpperCAmelCase_ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline __SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_logger(__name__) @add_end_docstrings(snake_case__) class __A (snake_case__): '''simple docstring''' def __init__( self : Optional[int] , **UpperCAmelCase_ : Any ) ->Tuple: """simple docstring""" super().__init__(**UpperCAmelCase_ ) if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""" ) # No specific FOR_XXX available yet def __call__( self : str , UpperCAmelCase_ : Union[np.ndarray, bytes, str] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , **UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = {} if "candidate_labels" in kwargs: snake_case_ = kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: snake_case_ = kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Optional[int]="This is a sound of {}." ) ->str: """simple docstring""" if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png snake_case_ = requests.get(UpperCAmelCase_ ).content else: with open(UpperCAmelCase_ , """rb""" ) as f: snake_case_ = f.read() if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = ffmpeg_read(UpperCAmelCase_ , self.feature_extractor.sampling_rate ) if not isinstance(UpperCAmelCase_ , np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) snake_case_ = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="""pt""" ) snake_case_ = candidate_labels snake_case_ = [hypothesis_template.format(UpperCAmelCase_ ) for x in candidate_labels] snake_case_ = self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_ ) snake_case_ = [text_inputs] return inputs def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Tuple ) ->Optional[int]: """simple docstring""" snake_case_ = model_inputs.pop("""candidate_labels""" ) snake_case_ = model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] , UpperCAmelCase_ ): snake_case_ = text_inputs[0] else: # Batching case. snake_case_ = text_inputs[0][0] snake_case_ = self.model(**UpperCAmelCase_ , **UpperCAmelCase_ ) snake_case_ = { """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" snake_case_ = model_outputs.pop("""candidate_labels""" ) snake_case_ = model_outputs["""logits"""][0] if self.framework == "pt": snake_case_ = logits.softmax(dim=0 ) snake_case_ = probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) snake_case_ = [ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_ ) , key=lambda UpperCAmelCase_ : -x[0] ) ] return result
2
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=13 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=[10, 20, 30, 40] , UpperCAmelCase_ : List[Any]=[2, 2, 3, 2] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : int=["stage2", "stage3", "stage4"] , UpperCAmelCase_ : Optional[int]=[2, 3, 4] , UpperCAmelCase_ : List[str]=None , ) ->Union[str, Any]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = num_stages snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = out_features snake_case_ = out_indices snake_case_ = scope def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = ConvNextVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = ConvNextVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __lowercase: Union[str, Any] = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Optional[Any] = False __lowercase: Any = False __lowercase: Union[str, Any] = False __lowercase: Dict = False def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = True if model_class.__name__ in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ]: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = False snake_case_ = True if ( model_class.__name__ in [*get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ )] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ): snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ConvNextVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> str: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(UpperCAmelCase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = preprocessor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
2
1
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' @property def lowerCAmelCase ( self : str ) ->Any: """simple docstring""" return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" snake_case_ = ort.SessionOptions() snake_case_ = False return options def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default snake_case_ = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = """A red cat sitting on a park bench""" snake_case_ = np.random.RandomState(0 ) snake_case_ = pipe( prompt=UpperCAmelCase_ , image=UpperCAmelCase_ , mask_image=UpperCAmelCase_ , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=UpperCAmelCase_ , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
2
"""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() __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : int = ['model.decoder.embed_positions.weights'] def _a ( _SCREAMING_SNAKE_CASE ) -> str: if "emb" in name: snake_case_ = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: snake_case_ = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: snake_case_ = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: snake_case_ = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: snake_case_ = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: snake_case_ = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: snake_case_ = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: snake_case_ = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: snake_case_ = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: snake_case_ = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: snake_case_ = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple[Dict, Dict]: snake_case_ = list(state_dict.keys() ) snake_case_ = {} for key in keys: snake_case_ = state_dict.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = rename_keys(_SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj snake_case_ = val[:hidden_size, :] snake_case_ = val[hidden_size : 2 * hidden_size, :] snake_case_ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: snake_case_ = val else: snake_case_ = val return state_dict, enc_dec_proj_state_dict def _a ( _SCREAMING_SNAKE_CASE ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values snake_case_ = 1_024 snake_case_ = 24 snake_case_ = 16 elif checkpoint == "medium": snake_case_ = 1_536 snake_case_ = 48 snake_case_ = 24 elif checkpoint == "large": snake_case_ = 2_048 snake_case_ = 48 snake_case_ = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) snake_case_ = MusicgenDecoderConfig( hidden_size=_SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=_SCREAMING_SNAKE_CASE , num_attention_heads=_SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="cpu" ) -> Tuple: snake_case_ = MusicGen.get_pretrained(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) snake_case_ = decoder_config_from_checkpoint(_SCREAMING_SNAKE_CASE ) snake_case_ = fairseq_model.lm.state_dict() snake_case_ , snake_case_ = rename_state_dict( _SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) snake_case_ = TaEncoderModel.from_pretrained("""t5-base""" ) snake_case_ = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) snake_case_ = MusicgenForCausalLM(_SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection snake_case_ , snake_case_ = decoder.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model snake_case_ = MusicgenForConditionalGeneration(text_encoder=_SCREAMING_SNAKE_CASE , audio_encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_SCREAMING_SNAKE_CASE ) # check we can do a forward pass snake_case_ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) snake_case_ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): snake_case_ = model(input_ids=_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor snake_case_ = AutoTokenizer.from_pretrained("""t5-base""" ) snake_case_ = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) snake_case_ = MusicgenProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids snake_case_ = 2_048 snake_case_ = 2_048 # set other default generation config params snake_case_ = int(30 * audio_encoder.config.frame_rate ) snake_case_ = True snake_case_ = 3.0 if pytorch_dump_folder is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) processor.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = 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.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
2
1
"""simple docstring""" # We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('ignore', category=UserWarning, module='torch.optim.lr_scheduler') class __A : '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = False ) ->Dict: """simple docstring""" snake_case_ = scheduler snake_case_ = optimizers if isinstance(UpperCAmelCase_ , (list, tuple) ) else [optimizers] snake_case_ = split_batches snake_case_ = step_with_optimizer snake_case_ = GradientState() def lowerCAmelCase ( self : Dict , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Dict ) ->Union[str, Any]: """simple docstring""" if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*UpperCAmelCase_ , **UpperCAmelCase_ ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*UpperCAmelCase_ , **UpperCAmelCase_ ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step snake_case_ = AcceleratorState().num_processes for _ in range(UpperCAmelCase_ ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , """total_steps""" ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*UpperCAmelCase_ , **UpperCAmelCase_ ) else: self.scheduler.step(*UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple ) ->Optional[int]: """simple docstring""" return self.scheduler.get_last_lr() def lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" return self.scheduler.state_dict() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Any: """simple docstring""" self.scheduler.load_state_dict(UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" return self.scheduler.get_lr() def lowerCAmelCase ( self : str , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Optional[int] ) ->Any: """simple docstring""" return self.scheduler.print_lr(*UpperCAmelCase_ , **UpperCAmelCase_ )
2
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: if index == number_of_items: return 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 ) if weights[index] <= max_weight: snake_case_ = values[index] + knapsack( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 ) return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import os def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = len(grid[0] ) snake_case_ = len(_SCREAMING_SNAKE_CASE ) snake_case_ = 0 snake_case_ = 0 snake_case_ = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(_SCREAMING_SNAKE_CASE ): for j in range(n_rows - 3 ): snake_case_ = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] snake_case_ = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: snake_case_ = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: snake_case_ = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) snake_case_ = max( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if max_product > largest: snake_case_ = max_product return largest def _a ( ) -> Optional[Any]: snake_case_ = [] with open(os.path.dirname(_SCREAMING_SNAKE_CASE ) + """/grid.txt""" ) as file: for line in file: grid.append(line.strip("""\n""" ).split(""" """ ) ) snake_case_ = [[int(_SCREAMING_SNAKE_CASE ) for i in grid[j]] for j in range(len(_SCREAMING_SNAKE_CASE ) )] return largest_product(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(solution())
2
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 20 ) -> int: snake_case_ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... snake_case_ = n // 2 return int(factorial(_SCREAMING_SNAKE_CASE ) / (factorial(_SCREAMING_SNAKE_CASE ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: __SCREAMING_SNAKE_CASE : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
2
1
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = range(2, 20 + 1) __SCREAMING_SNAKE_CASE : Any = [10**k for k in range(ks[-1] + 1)] __SCREAMING_SNAKE_CASE : dict[int, dict[int, list[list[int]]]] = {} def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: snake_case_ = sum(a_i[j] for j in range(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ) ) snake_case_ = sum(a_i[j] * base[j] for j in range(min(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) ) ) snake_case_ , snake_case_ = 0, 0 snake_case_ = n - i snake_case_ = memo.get(_SCREAMING_SNAKE_CASE ) if sub_memo is not None: snake_case_ = sub_memo.get(_SCREAMING_SNAKE_CASE ) if jumps is not None and len(_SCREAMING_SNAKE_CASE ) > 0: # find and make the largest jump without going over snake_case_ = -1 for _k in range(len(_SCREAMING_SNAKE_CASE ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: snake_case_ = _k break if max_jump >= 0: snake_case_ , snake_case_ , snake_case_ = jumps[max_jump] # since the difference between jumps is cached, add c snake_case_ = diff + c for j in range(min(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ) ): snake_case_ , snake_case_ = divmod(_SCREAMING_SNAKE_CASE , 10 ) if new_c > 0: add(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: snake_case_ = [] else: snake_case_ = {c: []} snake_case_ = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps snake_case_ , snake_case_ = next_term(_SCREAMING_SNAKE_CASE , k - 1 , i + dn , _SCREAMING_SNAKE_CASE ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead snake_case_ , snake_case_ = compute(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , i + dn , _SCREAMING_SNAKE_CASE ) diff += _diff dn += terms_jumped snake_case_ = sub_memo[c] # keep jumps sorted by # of terms skipped snake_case_ = 0 while j < len(_SCREAMING_SNAKE_CASE ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(_SCREAMING_SNAKE_CASE , (diff, dn, k) ) return (diff, dn) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: if i >= n: return 0, i if k > len(_SCREAMING_SNAKE_CASE ): a_i.extend([0 for _ in range(k - len(_SCREAMING_SNAKE_CASE ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) snake_case_ = i snake_case_ , snake_case_ , snake_case_ = 0, 0, 0 for j in range(len(_SCREAMING_SNAKE_CASE ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 snake_case_ = ds_c + ds_b diff += addend snake_case_ = 0 for j in range(_SCREAMING_SNAKE_CASE ): snake_case_ = a_i[j] + addend snake_case_ , snake_case_ = divmod(_SCREAMING_SNAKE_CASE , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return diff, i - start_i def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: for j in range(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = digits[j] + addend if s >= 10: snake_case_ , snake_case_ = divmod(_SCREAMING_SNAKE_CASE , 10 ) snake_case_ = addend // 10 + quotient else: snake_case_ = s snake_case_ = addend // 10 if addend == 0: break while addend > 0: snake_case_ , snake_case_ = divmod(_SCREAMING_SNAKE_CASE , 10 ) digits.append(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE = 10**15 ) -> int: snake_case_ = [1] snake_case_ = 1 snake_case_ = 0 while True: snake_case_ , snake_case_ = next_term(_SCREAMING_SNAKE_CASE , 20 , i + dn , _SCREAMING_SNAKE_CASE ) dn += terms_jumped if dn == n - i: break snake_case_ = 0 for j in range(len(_SCREAMING_SNAKE_CASE ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f"""{solution() = }""")
2
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _a ( _SCREAMING_SNAKE_CASE = 8 ) -> str: snake_case_ = ascii_letters + digits + punctuation return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(_SCREAMING_SNAKE_CASE ) snake_case_ = i // 3 snake_case_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case_ = ( chars_incl + random(_SCREAMING_SNAKE_CASE , quotient + remainder ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) snake_case_ = list(_SCREAMING_SNAKE_CASE ) shuffle(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) # random is a generalised function for letters, characters and numbers def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 8 ) -> bool: if len(_SCREAMING_SNAKE_CASE ) < min_length: # Your Password must be at least 8 characters long return False snake_case_ = any(char in ascii_uppercase for char in password ) snake_case_ = any(char in ascii_lowercase for char in password ) snake_case_ = any(char in digits for char in password ) snake_case_ = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _a ( ) -> str: snake_case_ = int(input("""Please indicate the max length of your password: """ ).strip() ) snake_case_ = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(_SCREAMING_SNAKE_CASE ) ) print( """Alternative Password generated:""" , alternative_password_generator(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
2
1
"""simple docstring""" from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class __A (snake_case__): '''simple docstring''' __lowercase: Optional[Any] = """new-model""" if is_tf_available(): class __A (snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = NewModelConfig @require_tf class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = """bert-base-cased""" snake_case_ = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = TFAutoModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : int ) ->int: """simple docstring""" snake_case_ = """bert-base-cased""" snake_case_ = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = TFAutoModelForPreTraining.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->Union[str, Any]: """simple docstring""" for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = TFAutoModelForCausalLM.from_pretrained(UpperCAmelCase_ ) snake_case_ , snake_case_ = TFAutoModelForCausalLM.from_pretrained(UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : int ) ->str: """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Optional[Any] ) ->str: """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = TFAutoModelForMaskedLM.from_pretrained(UpperCAmelCase_ ) snake_case_ , snake_case_ = TFAutoModelForMaskedLM.from_pretrained(UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = TFAutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase_ ) snake_case_ , snake_case_ = TFAutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : List[Any] ) ->int: """simple docstring""" for model_name in ["bert-base-uncased"]: snake_case_ = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = TFAutoModelForSequenceClassification.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" for model_name in ["bert-base-uncased"]: snake_case_ = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = TFAutoModelForQuestionAnswering.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) @slow @require_tensorflow_probability def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: snake_case_ = AutoConfig.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = TFAutoModelForTableQuestionAnswering.from_pretrained(UpperCAmelCase_ ) snake_case_ , snake_case_ = TFAutoModelForTableQuestionAnswering.from_pretrained( UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(model.num_parameters() , 14_410 ) self.assertEqual(model.num_parameters(only_trainable=UpperCAmelCase_ ) , 14_410 ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(model.num_parameters() , 14_410 ) self.assertEqual(model.num_parameters(only_trainable=UpperCAmelCase_ ) , 14_410 ) def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" snake_case_ = TFAutoModel.from_pretrained("""sgugger/funnel-random-tiny""" ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = copy.deepcopy(model.config ) snake_case_ = ["""FunnelBaseModel"""] snake_case_ = TFAutoModel.from_config(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(UpperCAmelCase_ ) snake_case_ = TFAutoModel.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->List[Any]: """simple docstring""" try: AutoConfig.register("""new-model""" , UpperCAmelCase_ ) snake_case_ = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(UpperCAmelCase_ ): auto_class.register(UpperCAmelCase_ , UpperCAmelCase_ ) auto_class.register(UpperCAmelCase_ , UpperCAmelCase_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(UpperCAmelCase_ ): auto_class.register(UpperCAmelCase_ , UpperCAmelCase_ ) # Now that the config is registered, it can be used as any other config with the auto-API snake_case_ = BertModelTester(self ).get_config() snake_case_ = NewModelConfig(**tiny_config.to_dict() ) snake_case_ = auto_class.from_config(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(UpperCAmelCase_ ) snake_case_ = auto_class.from_pretrained(UpperCAmelCase_ ) self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" with self.assertRaisesRegex( UpperCAmelCase_ , """bert-base is not a local folder and is not a valid model identifier""" ): snake_case_ = TFAutoModel.from_pretrained("""bert-base""" ) def lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" with self.assertRaisesRegex( UpperCAmelCase_ , R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): snake_case_ = TFAutoModel.from_pretrained(UpperCAmelCase_ , revision="""aaaaaa""" ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" with self.assertRaisesRegex( UpperCAmelCase_ , """hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin""" , ): snake_case_ = TFAutoModel.from_pretrained("""hf-internal-testing/config-no-model""" ) def lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" with self.assertRaisesRegex(UpperCAmelCase_ , """Use `from_pt=True` to load this model""" ): snake_case_ = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-bert-pt-only""" ) def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" snake_case_ = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) with RequestCounter() as counter: snake_case_ = TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint snake_case_ = TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) with RequestCounter() as counter: snake_case_ = TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
2
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset 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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=18 , UpperCAmelCase_ : Optional[Any]=30 , UpperCAmelCase_ : str=400 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[Any]=True , ) ->Optional[Any]: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = ImageGPTImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """clusters""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) snake_case_ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key] ) ) else: self.assertEqual(obj[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(UpperCAmelCase_ , """image_processor.json""" ) image_processor_first.to_json_file(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_json_file(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_pretrained(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" pass def _a ( ) -> str: snake_case_ = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) snake_case_ = Image.open(dataset[4]["""file"""] ) snake_case_ = Image.open(dataset[5]["""file"""] ) snake_case_ = [imagea, imagea] return images @require_vision @require_torch class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) snake_case_ = prepare_images() # test non-batched snake_case_ = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_024) ) snake_case_ = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_ ) # test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_024) ) snake_case_ = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_ )
2
1
"""simple docstring""" import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def _a ( _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: snake_case_ = s_dict.pop(_SCREAMING_SNAKE_CASE ) elif "subsample" in key: snake_case_ = s_dict.pop(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ , snake_case_ = emb.weight.shape snake_case_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE ) snake_case_ = emb.weight.data return lin_layer def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) snake_case_ = mam_aaa["""args"""] snake_case_ = mam_aaa["""model"""] snake_case_ = state_dict["""decoder.output_projection.weight"""] remove_ignore_keys_(_SCREAMING_SNAKE_CASE ) rename_keys(_SCREAMING_SNAKE_CASE ) snake_case_ = state_dict["""decoder.embed_tokens.weight"""].shape[0] snake_case_ = args.share_decoder_input_output_embed snake_case_ = [int(_SCREAMING_SNAKE_CASE ) for i in args.conv_kernel_sizes.split(""",""" )] snake_case_ = SpeechaTextConfig( vocab_size=_SCREAMING_SNAKE_CASE , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , num_conv_layers=len(_SCREAMING_SNAKE_CASE ) , conv_channels=args.conv_channels , conv_kernel_sizes=_SCREAMING_SNAKE_CASE , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=_SCREAMING_SNAKE_CASE , num_beams=5 , max_length=200 , use_cache=_SCREAMING_SNAKE_CASE , decoder_start_token_id=2 , early_stopping=_SCREAMING_SNAKE_CASE , ) snake_case_ = SpeechaTextForConditionalGeneration(_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ = model.model.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0 and not set(_SCREAMING_SNAKE_CASE ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f""" but all the following weights are missing {missing}""" ) if tie_embeds: snake_case_ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: snake_case_ = lm_head_weights model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser() # Required parameters parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
2
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : Dict=24 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=1_000 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = scope snake_case_ = range_bbox def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = t if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = t snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->str: """simple docstring""" snake_case_ = LiltModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , ) ->Dict: """simple docstring""" snake_case_ = self.num_labels snake_case_ = LiltForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , ) ->Dict: """simple docstring""" snake_case_ = LiltForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowercase: Optional[Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: List[str] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ = LiltModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = LiltModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCAmelCase_ ) snake_case_ = torch.tensor([[1, 2]] , device=UpperCAmelCase_ ) snake_case_ = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ ) snake_case_ = torch.Size([1, 2, 768] ) snake_case_ = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=UpperCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase_ , atol=1E-3 ) )
2
1
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' __lowercase: Any = ["""pixel_values"""] def __init__( self : List[str] , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[int, float] = 1 / 255 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : bool = True , **UpperCAmelCase_ : Tuple , ) ->None: """simple docstring""" super().__init__(**UpperCAmelCase_ ) snake_case_ = size if size is not None else {"""shortest_edge""": 224} snake_case_ = get_size_dict(UpperCAmelCase_ , default_to_square=UpperCAmelCase_ ) snake_case_ = crop_size if crop_size is not None else {"""height""": 256, """width""": 256} snake_case_ = get_size_dict(UpperCAmelCase_ , param_name="""crop_size""" ) snake_case_ = do_resize snake_case_ = size snake_case_ = resample snake_case_ = do_rescale snake_case_ = rescale_factor snake_case_ = do_center_crop snake_case_ = crop_size snake_case_ = do_flip_channel_order def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : PILImageResampling = PIL.Image.BILINEAR , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->np.ndarray: """simple docstring""" snake_case_ = get_size_dict(UpperCAmelCase_ , default_to_square=UpperCAmelCase_ ) if "shortest_edge" not in size: raise ValueError(F"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}""" ) snake_case_ = get_resize_output_image_size(UpperCAmelCase_ , size=size["""shortest_edge"""] , default_to_square=UpperCAmelCase_ ) return resize(UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : List[str] , ) ->np.ndarray: """simple docstring""" snake_case_ = get_size_dict(UpperCAmelCase_ ) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""" ) return center_crop(UpperCAmelCase_ , size=(size["""height"""], size["""width"""]) , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[int, float] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : str , ) ->Optional[int]: """simple docstring""" return rescale(UpperCAmelCase_ , scale=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None ) ->np.ndarray: """simple docstring""" return flip_channel_order(UpperCAmelCase_ , data_format=UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : ImageInput , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : float = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase_ : Any , ) ->PIL.Image.Image: """simple docstring""" snake_case_ = do_resize if do_resize is not None else self.do_resize snake_case_ = resample if resample is not None else self.resample snake_case_ = do_rescale if do_rescale is not None else self.do_rescale snake_case_ = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case_ = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case_ = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) snake_case_ = size if size is not None else self.size snake_case_ = get_size_dict(UpperCAmelCase_ , default_to_square=UpperCAmelCase_ ) snake_case_ = crop_size if crop_size is not None else self.crop_size snake_case_ = get_size_dict(UpperCAmelCase_ , param_name="""crop_size""" ) snake_case_ = make_list_of_images(UpperCAmelCase_ ) if not valid_images(UpperCAmelCase_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) # All transformations expect numpy arrays. snake_case_ = [to_numpy_array(UpperCAmelCase_ ) for image in images] if do_resize: snake_case_ = [self.resize(image=UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ ) for image in images] if do_center_crop: snake_case_ = [self.center_crop(image=UpperCAmelCase_ , size=UpperCAmelCase_ ) for image in images] if do_rescale: snake_case_ = [self.rescale(image=UpperCAmelCase_ , scale=UpperCAmelCase_ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: snake_case_ = [self.flip_channel_order(image=UpperCAmelCase_ ) for image in images] snake_case_ = [to_channel_dimension_format(UpperCAmelCase_ , UpperCAmelCase_ ) for image in images] snake_case_ = {"""pixel_values""": images} return BatchFeature(data=UpperCAmelCase_ , tensor_type=UpperCAmelCase_ ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Tuple] = None ) ->Dict: """simple docstring""" snake_case_ = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCAmelCase_ ) != len(UpperCAmelCase_ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(UpperCAmelCase_ ): snake_case_ = target_sizes.numpy() snake_case_ = [] for idx in range(len(UpperCAmelCase_ ) ): snake_case_ = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=UpperCAmelCase_ ) snake_case_ = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase_ ) else: snake_case_ = logits.argmax(dim=1 ) snake_case_ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
2
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
2
1
"""simple docstring""" import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def _a ( *_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=2 ) -> List[str]: from .. import __version__ snake_case_ = take_from snake_case_ = () if not isinstance(args[0] , _SCREAMING_SNAKE_CASE ): snake_case_ = (args,) for attribute, version_name, message in args: if version.parse(version.parse(_SCREAMING_SNAKE_CASE ).base_version ) >= version.parse(_SCREAMING_SNAKE_CASE ): raise ValueError( f"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'""" f""" version {__version__} is >= {version_name}""" ) snake_case_ = None if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(_SCREAMING_SNAKE_CASE ),) snake_case_ = f"""The `{attribute}` argument is deprecated and will be removed in version {version_name}.""" elif hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): values += (getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ),) snake_case_ = f"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}.""" elif deprecated_kwargs is None: snake_case_ = f"""`{attribute}` is deprecated and will be removed in version {version_name}.""" if warning is not None: snake_case_ = warning + """ """ if standard_warn else """""" warnings.warn(warning + message , _SCREAMING_SNAKE_CASE , stacklevel=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) > 0: snake_case_ = inspect.getouterframes(inspect.currentframe() )[1] snake_case_ = call_frame.filename snake_case_ = call_frame.lineno snake_case_ = call_frame.function snake_case_ , snake_case_ = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""" ) if len(_SCREAMING_SNAKE_CASE ) == 0: return elif len(_SCREAMING_SNAKE_CASE ) == 1: return values[0] return values
2
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
"""simple docstring""" import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __A : '''simple docstring''' @staticmethod def lowerCAmelCase ( *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @is_pipeline_test @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = pipeline("""visual-question-answering""" , model="""hf-internal-testing/tiny-vilt-random-vqa""" ) snake_case_ = [ { """image""": Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """question""": """How many cats are there?""", }, { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """question""": """How many cats are there?""", }, ] return vqa_pipeline, examples def lowerCAmelCase ( self : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int ) ->Tuple: """simple docstring""" snake_case_ = vqa_pipeline(UpperCAmelCase_ , top_k=1 ) self.assertEqual( UpperCAmelCase_ , [ [{"""score""": ANY(UpperCAmelCase_ ), """answer""": ANY(UpperCAmelCase_ )}], [{"""score""": ANY(UpperCAmelCase_ ), """answer""": ANY(UpperCAmelCase_ )}], ] , ) @require_torch def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = pipeline("""visual-question-answering""" , model="""hf-internal-testing/tiny-vilt-random-vqa""" ) snake_case_ = """./tests/fixtures/tests_samples/COCO/000000039769.png""" snake_case_ = """How many cats are there?""" snake_case_ = vqa_pipeline(image=UpperCAmelCase_ , question="""How many cats are there?""" , top_k=2 ) self.assertEqual( UpperCAmelCase_ , [{"""score""": ANY(UpperCAmelCase_ ), """answer""": ANY(UpperCAmelCase_ )}, {"""score""": ANY(UpperCAmelCase_ ), """answer""": ANY(UpperCAmelCase_ )}] ) snake_case_ = vqa_pipeline({"""image""": image, """question""": question} , top_k=2 ) self.assertEqual( UpperCAmelCase_ , [{"""score""": ANY(UpperCAmelCase_ ), """answer""": ANY(UpperCAmelCase_ )}, {"""score""": ANY(UpperCAmelCase_ ), """answer""": ANY(UpperCAmelCase_ )}] ) @slow @require_torch def lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" snake_case_ = pipeline("""visual-question-answering""" , model="""dandelin/vilt-b32-finetuned-vqa""" ) snake_case_ = """./tests/fixtures/tests_samples/COCO/000000039769.png""" snake_case_ = """How many cats are there?""" snake_case_ = vqa_pipeline(image=UpperCAmelCase_ , question=UpperCAmelCase_ , top_k=2 ) self.assertEqual( nested_simplify(UpperCAmelCase_ , decimals=4 ) , [{"""score""": 0.8_799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}] ) snake_case_ = vqa_pipeline({"""image""": image, """question""": question} , top_k=2 ) self.assertEqual( nested_simplify(UpperCAmelCase_ , decimals=4 ) , [{"""score""": 0.8_799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}] ) snake_case_ = vqa_pipeline( [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}] , top_k=2 ) self.assertEqual( nested_simplify(UpperCAmelCase_ , decimals=4 ) , [[{"""score""": 0.8_799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}]] * 2 , ) @require_tf @unittest.skip("""Visual question answering not implemented in TF""" ) def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" pass
2
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = False, False, False @dataclass class __A : '''simple docstring''' __lowercase: Optional[int] = None __lowercase: bool = True __lowercase: bool = True __lowercase: Optional[str] = None # Automatically constructed __lowercase: ClassVar[str] = "dict" __lowercase: ClassVar[Any] = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()}) __lowercase: str = field(default="""Audio""" , init=snake_case__ , repr=snake_case__) def __call__( self : Optional[Any] ) ->Optional[int]: """simple docstring""" return self.pa_type def lowerCAmelCase ( self : int , UpperCAmelCase_ : Union[str, bytes, dict] ) ->dict: """simple docstring""" try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("""To support encoding audio data, please install 'soundfile'.""" ) from err if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): return {"bytes": None, "path": value} elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes snake_case_ = BytesIO() sf.write(UpperCAmelCase_ , value["""array"""] , value["""sampling_rate"""] , format="""wav""" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("""path""" ) is not None and os.path.isfile(value["""path"""] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("""pcm""" ): # "PCM" only has raw audio bytes if value.get("""sampling_rate""" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("""To use PCM files, please specify a 'sampling_rate' in Audio object""" ) if value.get("""bytes""" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) snake_case_ = np.frombuffer(value["""bytes"""] , dtype=np.intaa ).astype(np.floataa ) / 32_767 else: snake_case_ = np.memmap(value["""path"""] , dtype="""h""" , mode="""r""" ).astype(np.floataa ) / 32_767 snake_case_ = BytesIO(bytes() ) sf.write(UpperCAmelCase_ , UpperCAmelCase_ , value["""sampling_rate"""] , format="""wav""" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( F"""An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : dict , UpperCAmelCase_ : Optional[Dict[str, Union[str, bool, None]]] = None ) ->dict: """simple docstring""" if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Audio(decode=True) instead.""" ) snake_case_ , snake_case_ = (value["""path"""], BytesIO(value["""bytes"""] )) if value["""bytes"""] is not None else (value["""path"""], None) if path is None and file is None: raise ValueError(F"""An audio sample should have one of 'path' or 'bytes' but both are None in {value}.""" ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("""To support decoding audio files, please install 'librosa' and 'soundfile'.""" ) from err snake_case_ = xsplitext(UpperCAmelCase_ )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( """Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, """ """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """ ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( """Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, """ """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """ ) if file is None: snake_case_ = token_per_repo_id or {} snake_case_ = path.split("""::""" )[-1] try: snake_case_ = string_to_dict(UpperCAmelCase_ , config.HUB_DATASETS_URL )["""repo_id"""] snake_case_ = token_per_repo_id[repo_id] except (ValueError, KeyError): snake_case_ = None with xopen(UpperCAmelCase_ , """rb""" , use_auth_token=UpperCAmelCase_ ) as f: snake_case_ , snake_case_ = sf.read(UpperCAmelCase_ ) else: snake_case_ , snake_case_ = sf.read(UpperCAmelCase_ ) snake_case_ = array.T if self.mono: snake_case_ = librosa.to_mono(UpperCAmelCase_ ) if self.sampling_rate and self.sampling_rate != sampling_rate: snake_case_ = librosa.resample(UpperCAmelCase_ , orig_sr=UpperCAmelCase_ , target_sr=self.sampling_rate ) snake_case_ = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def lowerCAmelCase ( self : Dict ) ->Union["FeatureType", Dict[str, "FeatureType"]]: """simple docstring""" from .features import Value if self.decode: raise ValueError("""Cannot flatten a decoded Audio feature.""" ) return { "bytes": Value("""binary""" ), "path": Value("""string""" ), } def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Union[pa.StringArray, pa.StructArray] ) ->pa.StructArray: """simple docstring""" if pa.types.is_string(storage.type ): snake_case_ = pa.array([None] * len(UpperCAmelCase_ ) , type=pa.binary() ) snake_case_ = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): snake_case_ = pa.array([None] * len(UpperCAmelCase_ ) , type=pa.string() ) snake_case_ = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("""array""" ): snake_case_ = pa.array([Audio().encode_example(UpperCAmelCase_ ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: snake_case_ = storage.field("""bytes""" ) else: snake_case_ = pa.array([None] * len(UpperCAmelCase_ ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: snake_case_ = storage.field("""path""" ) else: snake_case_ = pa.array([None] * len(UpperCAmelCase_ ) , type=pa.string() ) snake_case_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) return array_cast(UpperCAmelCase_ , self.pa_type ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : pa.StructArray ) ->pa.StructArray: """simple docstring""" @no_op_if_value_is_null def path_to_bytes(UpperCAmelCase_ : Dict ): with xopen(UpperCAmelCase_ , """rb""" ) as f: snake_case_ = f.read() return bytes_ snake_case_ = pa.array( [ (path_to_bytes(x["""path"""] ) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) snake_case_ = pa.array( [os.path.basename(UpperCAmelCase_ ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) snake_case_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(UpperCAmelCase_ , self.pa_type )
2
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : List[str] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __SCREAMING_SNAKE_CASE : List[str] = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __SCREAMING_SNAKE_CASE : int = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[Any] = VOCAB_FILES_NAMES __lowercase: Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowercase: Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]="[CLS]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : str="<unk>" , UpperCAmelCase_ : str="[SEP]" , UpperCAmelCase_ : Optional[Any]="<pad>" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : int="[MASK]" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->None: """simple docstring""" snake_case_ = ( AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ , normalized=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token ) snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = do_lower_case snake_case_ = remove_space snake_case_ = keep_accents snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return len(self.sp_model ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Any ) ->str: """simple docstring""" if self.remove_space: snake_case_ = """ """.join(inputs.strip().split() ) else: snake_case_ = inputs snake_case_ = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: snake_case_ = unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) snake_case_ = """""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: snake_case_ = outputs.lower() return outputs def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.preprocess_text(UpperCAmelCase_ ) snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) snake_case_ = [] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): snake_case_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case_ = cur_pieces[1:] else: snake_case_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" return self.sp_model.PieceToId(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" return self.sp_model.IdToPiece(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Dict ) ->Any: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
2
1
"""simple docstring""" import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: str = VQModel __lowercase: Union[str, Any] = """sample""" @property def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[str]=(32, 32) ) ->Tuple: """simple docstring""" snake_case_ = 4 snake_case_ = 3 snake_case_ = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase_ ) return {"sample": image} @property def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" return (3, 32, 32) @property def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" return (3, 32, 32) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } snake_case_ = self.dummy_input return init_dict, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(UpperCAmelCase_ ) snake_case_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(UpperCAmelCase_ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) snake_case_ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) snake_case_ = image.to(UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = model(UpperCAmelCase_ ).sample snake_case_ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off snake_case_ = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 ) )
2
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers __SCREAMING_SNAKE_CASE : List[str] = [ 'python', 'tqdm', 'regex', 'requests', 'packaging', 'filelock', 'numpy', 'tokenizers', 'huggingface-hub', 'safetensors', 'accelerate', 'pyyaml', ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""") def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: require_version(deps[pkg] , _SCREAMING_SNAKE_CASE )
2
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
"""simple docstring""" import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline __SCREAMING_SNAKE_CASE : str = datasets.utils.logging.get_logger(__name__) @dataclass class __A (datasets.BuilderConfig): '''simple docstring''' __lowercase: Optional[datasets.Features] = None __lowercase: str = "utf-8" __lowercase: Optional[str] = None __lowercase: Optional[str] = None __lowercase: bool = True # deprecated __lowercase: Optional[int] = None # deprecated __lowercase: int = 10 << 20 # 10MB __lowercase: Optional[bool] = None class __A (datasets.ArrowBasedBuilder): '''simple docstring''' __lowercase: str = JsonConfig def lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) snake_case_ = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] ) ->List[Any]: """simple docstring""" if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) snake_case_ = dl_manager.download_and_extract(self.config.data_files ) if isinstance(UpperCAmelCase_ , (str, list, tuple) ): snake_case_ = data_files if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = [files] snake_case_ = [dl_manager.iter_files(UpperCAmelCase_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] snake_case_ = [] for split_name, files in data_files.items(): if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = [files] snake_case_ = [dl_manager.iter_files(UpperCAmelCase_ ) for file in files] splits.append(datasets.SplitGenerator(name=UpperCAmelCase_ , gen_kwargs={"""files""": files} ) ) return splits def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : pa.Table ) ->pa.Table: """simple docstring""" if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): snake_case_ = self.config.features.arrow_schema.field(UpperCAmelCase_ ).type snake_case_ = pa_table.append_column(UpperCAmelCase_ , pa.array([None] * len(UpperCAmelCase_ ) , type=UpperCAmelCase_ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example snake_case_ = table_cast(UpperCAmelCase_ , self.config.features.arrow_schema ) return pa_table def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCAmelCase_ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(UpperCAmelCase_ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: snake_case_ = json.load(UpperCAmelCase_ ) # We keep only the field we are interested in snake_case_ = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(UpperCAmelCase_ , (list, tuple) ): snake_case_ = set().union(*[row.keys() for row in dataset] ) snake_case_ = {col: [row.get(UpperCAmelCase_ ) for row in dataset] for col in keys} else: snake_case_ = dataset snake_case_ = pa.Table.from_pydict(UpperCAmelCase_ ) yield file_idx, self._cast_table(UpperCAmelCase_ ) # If the file has one json object per line else: with open(UpperCAmelCase_ , """rb""" ) as f: snake_case_ = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small snake_case_ = max(self.config.chunksize // 32 , 16 << 10 ) snake_case_ = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: snake_case_ = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(UpperCAmelCase_ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": snake_case_ = batch.decode(self.config.encoding , errors=UpperCAmelCase_ ).encode("""utf-8""" ) try: while True: try: snake_case_ = paj.read_json( io.BytesIO(UpperCAmelCase_ ) , read_options=paj.ReadOptions(block_size=UpperCAmelCase_ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(UpperCAmelCase_ , pa.ArrowInvalid ) and "straddling" not in str(UpperCAmelCase_ ) or block_size > len(UpperCAmelCase_ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"""Batch of {len(UpperCAmelCase_ )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""" ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( UpperCAmelCase_ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: snake_case_ = json.load(UpperCAmelCase_ ) except json.JSONDecodeError: logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase_ )}: {e}""" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # list is the only sequence type supported in JSON try: snake_case_ = set().union(*[row.keys() for row in dataset] ) snake_case_ = {col: [row.get(UpperCAmelCase_ ) for row in dataset] for col in keys} snake_case_ = pa.Table.from_pydict(UpperCAmelCase_ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase_ )}: {e}""" ) raise ValueError(F"""Not able to read records in the JSON file at {file}.""" ) from None yield file_idx, self._cast_table(UpperCAmelCase_ ) break else: logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase_ )}: {e}""" ) raise ValueError( F"""Not able to read records in the JSON file at {file}. """ F"""You should probably indicate the field of the JSON file containing your records. """ F"""This JSON file contain the following fields: {str(list(dataset.keys() ) )}. """ F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """ ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(UpperCAmelCase_ ) batch_idx += 1
2
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
"""simple docstring""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): '''simple docstring''' @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
2
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: str = ["""torch""", """transformers""", """onnx"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Tuple ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : Optional[int] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : Optional[int] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Union[str, Any] ) ->Optional[Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""torch""", """transformers""", """onnx"""] def __init__( self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : int ) ->int: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : str , *UpperCAmelCase_ : int , **UpperCAmelCase_ : int ) ->List[Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : Union[str, Any] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[Any] = ["""torch""", """transformers""", """onnx"""] def __init__( self : Tuple , *UpperCAmelCase_ : str , **UpperCAmelCase_ : str ) ->str: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : Union[str, Any] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Union[str, Any] ) ->List[str]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Tuple ) ->Union[str, Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""torch""", """transformers""", """onnx"""] def __init__( self : int , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[str] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[Any] , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : str ) ->Optional[Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""torch""", """transformers""", """onnx"""] def __init__( self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Union[str, Any] ) ->Dict: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[Any] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any ) ->List[Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""torch""", """transformers""", """onnx"""] def __init__( self : Any , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Tuple ) ->Any: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : int , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Tuple ) ->Tuple: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[str] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Tuple ) ->Any: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] )
2
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=snake_case__) class __A (snake_case__): '''simple docstring''' __lowercase: str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True}) __lowercase: ClassVar[Features] = Features({"""audio""": Audio()}) __lowercase: ClassVar[Features] = Features({"""transcription""": Value("""string""")}) __lowercase: str = "audio" __lowercase: str = "transcription" def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , UpperCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) snake_case_ = copy.deepcopy(self ) snake_case_ = self.input_schema.copy() snake_case_ = features[self.audio_column] snake_case_ = input_schema return task_template @property def lowerCAmelCase ( self : List[str] ) ->Dict[str, str]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
2
1
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __A (snake_case__): '''simple docstring''' __lowercase: Optional[int] = """""" __lowercase: Union[str, Any] = """hf-legacy""" # "hf://"" is reserved for hffs def __init__( self : Dict , UpperCAmelCase_ : Optional[DatasetInfo] = None , UpperCAmelCase_ : Optional[str] = None , **UpperCAmelCase_ : str , ) ->List[Any]: """simple docstring""" super().__init__(self , **UpperCAmelCase_ ) snake_case_ = repo_info snake_case_ = token snake_case_ = None def lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" if self.dir_cache is None: snake_case_ = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes snake_case_ = { """name""": hf_file.rfilename, """size""": None, """type""": """file""", } self.dir_cache.update( { str(UpperCAmelCase_ ): {"""name""": str(UpperCAmelCase_ ), """size""": None, """type""": """directory"""} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : str = "rb" , **UpperCAmelCase_ : List[Any] , ) ->Union[str, Any]: """simple docstring""" if not isinstance(self.repo_info , UpperCAmelCase_ ): raise NotImplementedError(F"""Open is only implemented for dataset repositories, but got {self.repo_info}""" ) snake_case_ = hf_hub_url(self.repo_info.id , UpperCAmelCase_ , revision=self.repo_info.sha ) return fsspec.open( UpperCAmelCase_ , mode=UpperCAmelCase_ , headers=get_authentication_headers_for_url(UpperCAmelCase_ , use_auth_token=self.token ) , client_kwargs={"""trust_env""": True} , ).open() def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" self._get_dirs() snake_case_ = self._strip_protocol(UpperCAmelCase_ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any]=False , **UpperCAmelCase_ : Dict ) ->List[str]: """simple docstring""" self._get_dirs() snake_case_ = PurePosixPath(path.strip("""/""" ) ) snake_case_ = {} for p, f in self.dir_cache.items(): snake_case_ = PurePosixPath(p.strip("""/""" ) ) snake_case_ = p.parent if root == path: snake_case_ = f snake_case_ = list(paths.values() ) if detail: return out else: return sorted(f["""name"""] for f in out )
2
"""simple docstring""" from functools import reduce __SCREAMING_SNAKE_CASE : Tuple = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _a ( _SCREAMING_SNAKE_CASE = N ) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str(int(_SCREAMING_SNAKE_CASE ) * int(_SCREAMING_SNAKE_CASE ) ) , n[i : i + 13] ) ) for i in range(len(_SCREAMING_SNAKE_CASE ) - 12 ) ) if __name__ == "__main__": print(f"""{solution() = }""")
2
1
"""simple docstring""" import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __A (unittest.TestCase): '''simple docstring''' __lowercase: Any = JukeboxTokenizer __lowercase: Union[str, Any] = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def lowerCAmelCase ( self : List[Any] ) ->int: """simple docstring""" import torch snake_case_ = JukeboxTokenizer.from_pretrained("""openai/jukebox-1b-lyrics""" ) snake_case_ = tokenizer(**self.metas )["""input_ids"""] # fmt: off snake_case_ = [ torch.tensor([[ 0, 0, 0, 7_169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1_069, 11]] ), torch.tensor([[0, 0, 0, 1_069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" import torch snake_case_ = JukeboxTokenizer.from_pretrained("""openai/jukebox-5b-lyrics""" ) snake_case_ = tokenizer(**self.metas )["""input_ids"""] # fmt: off snake_case_ = [ torch.tensor([[ 0, 0, 0, 1_069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
2
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str = { 'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json', # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class __A (snake_case__): '''simple docstring''' __lowercase: Any = """mctct""" def __init__( self : Dict , UpperCAmelCase_ : List[Any]=8_065 , UpperCAmelCase_ : Tuple=1_536 , UpperCAmelCase_ : Optional[Any]=36 , UpperCAmelCase_ : int=6_144 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Any=384 , UpperCAmelCase_ : List[str]=920 , UpperCAmelCase_ : Any=1E-5 , UpperCAmelCase_ : Any=0.3 , UpperCAmelCase_ : Tuple="relu" , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Dict=0.3 , UpperCAmelCase_ : str=0.3 , UpperCAmelCase_ : Any=1 , UpperCAmelCase_ : Any=0 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=0.3 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : Optional[Any]=(7,) , UpperCAmelCase_ : Optional[Any]=(3,) , UpperCAmelCase_ : List[str]=80 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[str]="sum" , UpperCAmelCase_ : Union[str, Any]=False , **UpperCAmelCase_ : Any , ) ->Dict: """simple docstring""" super().__init__(**UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = intermediate_size snake_case_ = num_attention_heads snake_case_ = attention_head_dim snake_case_ = max_position_embeddings snake_case_ = layer_norm_eps snake_case_ = layerdrop snake_case_ = hidden_act snake_case_ = initializer_range snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id snake_case_ = conv_glu_dim snake_case_ = conv_dropout snake_case_ = num_conv_layers snake_case_ = input_feat_per_channel snake_case_ = input_channels snake_case_ = conv_channels snake_case_ = ctc_loss_reduction snake_case_ = ctc_zero_infinity # prevents config testing fail with exporting to json snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """ F"""but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, """ F"""`config.num_conv_layers = {self.num_conv_layers}`.""" )
2
1
"""simple docstring""" # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib __SCREAMING_SNAKE_CASE : Optional[Any] = get_logger() __SCREAMING_SNAKE_CASE : Optional[dict] = None class __A (TensorFormatter[Mapping, """jax.Array""", Mapping]): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : Tuple ) ->Optional[Any]: """simple docstring""" super().__init__(features=UpperCAmelCase_ ) import jax from jaxlib.xla_client import Device if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): raise ValueError( F"""Expected {device} to be a `str` not {type(UpperCAmelCase_ )}, as `jaxlib.xla_extension.Device` """ """is not serializable neither with `pickle` nor with `dill`. Instead you can surround """ """the device with `str()` to get its string identifier that will be internally mapped """ """to the actual `jaxlib.xla_extension.Device`.""" ) snake_case_ = device if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: snake_case_ = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F"""Device with string identifier {self.device} not listed among the available """ F"""devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default """ F"""device: {str(jax.devices()[0] )}.""" ) snake_case_ = str(jax.devices()[0] ) snake_case_ = jnp_array_kwargs @staticmethod def lowerCAmelCase ( ) ->Dict[str, "jaxlib.xla_extension.Device"]: """simple docstring""" import jax return {str(UpperCAmelCase_ ): device for device in jax.devices()} def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] ) ->str: """simple docstring""" import jax import jax.numpy as jnp if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and column: if all( isinstance(UpperCAmelCase_ , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(UpperCAmelCase_ , axis=0 ) return column def lowerCAmelCase ( self : int , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" import jax import jax.numpy as jnp if isinstance(UpperCAmelCase_ , (str, bytes, type(UpperCAmelCase_ )) ): return value elif isinstance(UpperCAmelCase_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() snake_case_ = {} if isinstance(UpperCAmelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: snake_case_ = {"""dtype""": jnp.intaa} else: snake_case_ = {"""dtype""": jnp.intaa} elif isinstance(UpperCAmelCase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): snake_case_ = {"""dtype""": jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(UpperCAmelCase_ , PIL.Image.Image ): snake_case_ = np.asarray(UpperCAmelCase_ ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: snake_case_ = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(UpperCAmelCase_ , **{**default_dtype, **self.jnp_array_kwargs} ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(UpperCAmelCase_ , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(UpperCAmelCase_ , """__array__""" ) and not isinstance(UpperCAmelCase_ , jax.Array ): snake_case_ = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(UpperCAmelCase_ , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(UpperCAmelCase_ ) for substruct in data_struct] ) elif isinstance(UpperCAmelCase_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(UpperCAmelCase_ ) for substruct in data_struct] ) return self._tensorize(UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : dict ) ->int: """simple docstring""" return map_nested(self._recursive_tensorize , UpperCAmelCase_ , map_list=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : pa.Table ) ->Mapping: """simple docstring""" snake_case_ = self.numpy_arrow_extractor().extract_row(UpperCAmelCase_ ) snake_case_ = self.python_features_decoder.decode_row(UpperCAmelCase_ ) return self.recursive_tensorize(UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : pa.Table ) ->"jax.Array": """simple docstring""" snake_case_ = self.numpy_arrow_extractor().extract_column(UpperCAmelCase_ ) snake_case_ = self.python_features_decoder.decode_column(UpperCAmelCase_ , pa_table.column_names[0] ) snake_case_ = self.recursive_tensorize(UpperCAmelCase_ ) snake_case_ = self._consolidate(UpperCAmelCase_ ) return column def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : pa.Table ) ->Mapping: """simple docstring""" snake_case_ = self.numpy_arrow_extractor().extract_batch(UpperCAmelCase_ ) snake_case_ = self.python_features_decoder.decode_batch(UpperCAmelCase_ ) snake_case_ = self.recursive_tensorize(UpperCAmelCase_ ) for column_name in batch: snake_case_ = self._consolidate(batch[column_name] ) return batch
2
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 100 ) -> int: return sum(int(_SCREAMING_SNAKE_CASE ) for x in str(factorial(_SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
2
1
"""simple docstring""" import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" debug_launcher(test_script.main ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" debug_launcher(test_ops.main )
2
"""simple docstring""" import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: str = VQModel __lowercase: Union[str, Any] = """sample""" @property def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[str]=(32, 32) ) ->Tuple: """simple docstring""" snake_case_ = 4 snake_case_ = 3 snake_case_ = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase_ ) return {"sample": image} @property def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" return (3, 32, 32) @property def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" return (3, 32, 32) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } snake_case_ = self.dummy_input return init_dict, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(UpperCAmelCase_ ) snake_case_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(UpperCAmelCase_ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) snake_case_ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) snake_case_ = image.to(UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = model(UpperCAmelCase_ ).sample snake_case_ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off snake_case_ = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 ) )
2
1
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def _a ( _SCREAMING_SNAKE_CASE ) -> tuple: return (data["data"], data["target"]) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> np.ndarray: snake_case_ = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Predict target for test data snake_case_ = xgb.predict(_SCREAMING_SNAKE_CASE ) snake_case_ = predictions.reshape(len(_SCREAMING_SNAKE_CASE ) , 1 ) return predictions def _a ( ) -> None: snake_case_ = fetch_california_housing() snake_case_ , snake_case_ = data_handling(_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ , snake_case_ , snake_case_ = train_test_split( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , test_size=0.25 , random_state=1 ) snake_case_ = xgboost(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Error printing print(f"""Mean Absolute Error : {mean_absolute_error(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}""" ) print(f"""Mean Square Error : {mean_squared_error(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}""" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
2
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = KandinskyVaaControlnetPipeline __lowercase: str = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: Union[str, Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowercase: Tuple = False @property def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return 100 @property def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) snake_case_ = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } snake_case_ = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=UpperCAmelCase_ , ) snake_case_ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]=0 ) ->List[str]: """simple docstring""" snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) # create hint snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("""mps""" ): snake_case_ = torch.manual_seed(UpperCAmelCase_ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) snake_case_ = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" snake_case_ = """cpu""" snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**UpperCAmelCase_ ) snake_case_ = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) snake_case_ = torch.from_numpy(np.array(UpperCAmelCase_ ) ).float() / 255.0 snake_case_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case_ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) snake_case_ = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = """A robot, 4k photo""" snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ , snake_case_ = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , hint=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
2
1
"""simple docstring""" import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = UniSpeechSatForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE ) snake_case_ = downstream_dict["""projector.weight"""] snake_case_ = downstream_dict["""projector.bias"""] snake_case_ = downstream_dict["""model.post_net.linear.weight"""] snake_case_ = downstream_dict["""model.post_net.linear.bias"""] return model def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ = UniSpeechSatForAudioFrameClassification.from_pretrained(_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE ) snake_case_ = downstream_dict["""model.linear.weight"""] snake_case_ = downstream_dict["""model.linear.bias"""] return model def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = UniSpeechSatForXVector.from_pretrained(_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE ) snake_case_ = downstream_dict["""connector.weight"""] snake_case_ = downstream_dict["""connector.bias"""] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): snake_case_ = downstream_dict[ f"""model.framelevel_feature_extractor.module.{i}.kernel.weight""" ] snake_case_ = downstream_dict[f"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""] snake_case_ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""] snake_case_ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""] snake_case_ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""] snake_case_ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""] snake_case_ = downstream_dict["""objective.W"""] return model @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) snake_case_ = checkpoint["""Downstream"""] snake_case_ = UniSpeechSatConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaFeatureExtractor.from_pretrained( _SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , do_normalize=_SCREAMING_SNAKE_CASE ) snake_case_ = hf_config.architectures[0] if arch.endswith("""ForSequenceClassification""" ): snake_case_ = convert_classification(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif arch.endswith("""ForAudioFrameClassification""" ): snake_case_ = convert_diarization(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif arch.endswith("""ForXVector""" ): snake_case_ = convert_xvector(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: raise NotImplementedError(f"""S3PRL weights conversion is not supported for {arch}""" ) if hf_config.use_weighted_layer_sum: snake_case_ = checkpoint["""Featurizer"""]["""weights"""] hf_feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) hf_model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() parser.add_argument( '--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.' ) parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.') parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.') __SCREAMING_SNAKE_CASE : Any = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
2
"""simple docstring""" from __future__ import annotations from collections import deque class __A : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : list[str] ) ->List[Any]: """simple docstring""" snake_case_ = [] self.adlist.append( {"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} ) for keyword in keywords: self.add_keyword(UpperCAmelCase_ ) self.set_fail_transitions() def lowerCAmelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : str ) ->int | None: """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def lowerCAmelCase ( self : int , UpperCAmelCase_ : str ) ->None: """simple docstring""" snake_case_ = 0 for character in keyword: snake_case_ = self.find_next_state(UpperCAmelCase_ , UpperCAmelCase_ ) if next_state is None: self.adlist.append( { """value""": character, """next_states""": [], """fail_state""": 0, """output""": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) snake_case_ = len(self.adlist ) - 1 else: snake_case_ = next_state self.adlist[current_state]["output"].append(UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->None: """simple docstring""" snake_case_ = deque() for node in self.adlist[0]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = 0 while q: snake_case_ = q.popleft() for child in self.adlist[r]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = self.adlist[r]["""fail_state"""] while ( self.find_next_state(UpperCAmelCase_ , self.adlist[child]["""value"""] ) is None and state != 0 ): snake_case_ = self.adlist[state]["""fail_state"""] snake_case_ = self.find_next_state( UpperCAmelCase_ , self.adlist[child]["""value"""] ) if self.adlist[child]["fail_state"] is None: snake_case_ = 0 snake_case_ = ( self.adlist[child]["""output"""] + self.adlist[self.adlist[child]["""fail_state"""]]["""output"""] ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->dict[str, list[int]]: """simple docstring""" snake_case_ = {} # returns a dict with keywords and list of its occurrences snake_case_ = 0 for i in range(len(UpperCAmelCase_ ) ): while ( self.find_next_state(UpperCAmelCase_ , string[i] ) is None and current_state != 0 ): snake_case_ = self.adlist[current_state]["""fail_state"""] snake_case_ = self.find_next_state(UpperCAmelCase_ , string[i] ) if next_state is None: snake_case_ = 0 else: snake_case_ = next_state for key in self.adlist[current_state]["output"]: if key not in result: snake_case_ = [] result[key].append(i - len(UpperCAmelCase_ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" from functools import lru_cache @lru_cache def _a ( _SCREAMING_SNAKE_CASE ) -> int: if num < 0: raise ValueError("""Number should not be negative.""" ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
2
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=13 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=[10, 20, 30, 40] , UpperCAmelCase_ : List[Any]=[2, 2, 3, 2] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : int=["stage2", "stage3", "stage4"] , UpperCAmelCase_ : Optional[int]=[2, 3, 4] , UpperCAmelCase_ : List[str]=None , ) ->Union[str, Any]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = num_stages snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = out_features snake_case_ = out_indices snake_case_ = scope def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = ConvNextVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = ConvNextVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __lowercase: Union[str, Any] = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Optional[Any] = False __lowercase: Any = False __lowercase: Union[str, Any] = False __lowercase: Dict = False def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = True if model_class.__name__ in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ]: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = False snake_case_ = True if ( model_class.__name__ in [*get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ )] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ): snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ConvNextVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> str: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(UpperCAmelCase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = preprocessor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
2
1
"""simple docstring""" import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = IFPipeline __lowercase: Optional[Any] = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} __lowercase: List[Any] = TEXT_TO_IMAGE_BATCH_PARAMS __lowercase: Optional[int] = PipelineTesterMixin.required_optional_params - {"""latents"""} def lowerCAmelCase ( self : List[str] ) ->Any: """simple docstring""" return self._get_dummy_components() def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int]=0 ) ->str: """simple docstring""" if str(UpperCAmelCase_ ).startswith("""mps""" ): snake_case_ = torch.manual_seed(UpperCAmelCase_ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) snake_case_ = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1E-1 ) def lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def lowerCAmelCase ( self : Union[str, Any] ) ->str: """simple docstring""" self._test_save_load_local() def lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def lowerCAmelCase ( self : Union[str, Any] ) ->Any: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" snake_case_ = IFPipeline.from_pretrained("""DeepFloyd/IF-I-XL-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa ) snake_case_ = IFSuperResolutionPipeline.from_pretrained( """DeepFloyd/IF-II-L-v1.0""" , variant="""fp16""" , torch_dtype=torch.floataa , text_encoder=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to("""cuda""" ) snake_case_ , snake_case_ = pipe_a.encode_prompt("""anime turtle""" , device="""cuda""" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() snake_case_ = None snake_case_ = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img snake_case_ = IFImgaImgPipeline(**pipe_a.components ) snake_case_ = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting snake_case_ = IFInpaintingPipeline(**pipe_a.components ) snake_case_ = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple ) ->str: """simple docstring""" _start_torch_memory_measurement() snake_case_ = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ = pipe_a( prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , num_inference_steps=2 , generator=UpperCAmelCase_ , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (64, 64, 3) snake_case_ = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy""" ) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ ) # pipeline 2 _start_torch_memory_measurement() snake_case_ = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) snake_case_ = pipe_a( prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , image=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=2 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (256, 256, 3) snake_case_ = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] ) ->List[Any]: """simple docstring""" _start_torch_memory_measurement() snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) snake_case_ = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ = pipe_a( prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , image=UpperCAmelCase_ , num_inference_steps=2 , generator=UpperCAmelCase_ , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (64, 64, 3) snake_case_ = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy""" ) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ ) # pipeline 2 _start_torch_memory_measurement() snake_case_ = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) snake_case_ = pipe_a( prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , image=UpperCAmelCase_ , original_image=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=2 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (256, 256, 3) snake_case_ = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" _start_torch_memory_measurement() snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(UpperCAmelCase_ ) snake_case_ = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ = pipe_a( prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , image=UpperCAmelCase_ , mask_image=UpperCAmelCase_ , num_inference_steps=2 , generator=UpperCAmelCase_ , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (64, 64, 3) snake_case_ = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy""" ) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ ) # pipeline 2 _start_torch_memory_measurement() snake_case_ = torch.Generator(device="""cpu""" ).manual_seed(0 ) snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(UpperCAmelCase_ ) snake_case_ = pipe_a( prompt_embeds=UpperCAmelCase_ , negative_prompt_embeds=UpperCAmelCase_ , image=UpperCAmelCase_ , mask_image=UpperCAmelCase_ , original_image=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=2 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (256, 256, 3) snake_case_ = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy""" ) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ ) def _a ( ) -> Optional[Any]: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
2
"""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() __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : int = ['model.decoder.embed_positions.weights'] def _a ( _SCREAMING_SNAKE_CASE ) -> str: if "emb" in name: snake_case_ = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: snake_case_ = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: snake_case_ = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: snake_case_ = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: snake_case_ = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: snake_case_ = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: snake_case_ = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: snake_case_ = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: snake_case_ = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: snake_case_ = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: snake_case_ = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple[Dict, Dict]: snake_case_ = list(state_dict.keys() ) snake_case_ = {} for key in keys: snake_case_ = state_dict.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = rename_keys(_SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj snake_case_ = val[:hidden_size, :] snake_case_ = val[hidden_size : 2 * hidden_size, :] snake_case_ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: snake_case_ = val else: snake_case_ = val return state_dict, enc_dec_proj_state_dict def _a ( _SCREAMING_SNAKE_CASE ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values snake_case_ = 1_024 snake_case_ = 24 snake_case_ = 16 elif checkpoint == "medium": snake_case_ = 1_536 snake_case_ = 48 snake_case_ = 24 elif checkpoint == "large": snake_case_ = 2_048 snake_case_ = 48 snake_case_ = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) snake_case_ = MusicgenDecoderConfig( hidden_size=_SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=_SCREAMING_SNAKE_CASE , num_attention_heads=_SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="cpu" ) -> Tuple: snake_case_ = MusicGen.get_pretrained(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) snake_case_ = decoder_config_from_checkpoint(_SCREAMING_SNAKE_CASE ) snake_case_ = fairseq_model.lm.state_dict() snake_case_ , snake_case_ = rename_state_dict( _SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) snake_case_ = TaEncoderModel.from_pretrained("""t5-base""" ) snake_case_ = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) snake_case_ = MusicgenForCausalLM(_SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection snake_case_ , snake_case_ = decoder.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model snake_case_ = MusicgenForConditionalGeneration(text_encoder=_SCREAMING_SNAKE_CASE , audio_encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_SCREAMING_SNAKE_CASE ) # check we can do a forward pass snake_case_ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) snake_case_ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): snake_case_ = model(input_ids=_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor snake_case_ = AutoTokenizer.from_pretrained("""t5-base""" ) snake_case_ = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) snake_case_ = MusicgenProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids snake_case_ = 2_048 snake_case_ = 2_048 # set other default generation config params snake_case_ = int(30 * audio_encoder.config.frame_rate ) snake_case_ = True snake_case_ = 3.0 if pytorch_dump_folder is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) processor.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = 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.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
2
1
"""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 __A (snake_case__): '''simple docstring''' __lowercase: int = (DPMSolverSDEScheduler,) __lowercase: Optional[Any] = 10 def lowerCAmelCase ( self : Any , **UpperCAmelCase_ : List[Any] ) ->int: """simple docstring""" snake_case_ = { """num_train_timesteps""": 1_100, """beta_start""": 0.0_001, """beta_end""": 0.02, """beta_schedule""": """linear""", """noise_sampler_seed""": 0, } config.update(**UpperCAmelCase_ ) return config def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=UpperCAmelCase_ , beta_end=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.scheduler_classes[0] snake_case_ = self.get_scheduler_config() snake_case_ = scheduler_class(**UpperCAmelCase_ ) scheduler.set_timesteps(self.num_inference_steps ) snake_case_ = self.dummy_model() snake_case_ = self.dummy_sample_deter * scheduler.init_noise_sigma snake_case_ = sample.to(UpperCAmelCase_ ) for i, t in enumerate(scheduler.timesteps ): snake_case_ = scheduler.scale_model_input(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = output.prev_sample snake_case_ = torch.sum(torch.abs(UpperCAmelCase_ ) ) snake_case_ = torch.mean(torch.abs(UpperCAmelCase_ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_821_044_921_875 ) < 1E-2 assert abs(result_mean.item() - 0.2_178_705_964_565_277 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_352_111_816_406 ) < 1E-2 assert abs(result_mean.item() - 0.22_342_906_892_299_652 ) < 1E-3 else: assert abs(result_sum.item() - 162.52_383_422_851_562 ) < 1E-2 assert abs(result_mean.item() - 0.211_619_570_851_326 ) < 1E-3 def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.scheduler_classes[0] snake_case_ = self.get_scheduler_config(prediction_type="""v_prediction""" ) snake_case_ = scheduler_class(**UpperCAmelCase_ ) scheduler.set_timesteps(self.num_inference_steps ) snake_case_ = self.dummy_model() snake_case_ = self.dummy_sample_deter * scheduler.init_noise_sigma snake_case_ = sample.to(UpperCAmelCase_ ) for i, t in enumerate(scheduler.timesteps ): snake_case_ = scheduler.scale_model_input(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = output.prev_sample snake_case_ = torch.sum(torch.abs(UpperCAmelCase_ ) ) snake_case_ = torch.mean(torch.abs(UpperCAmelCase_ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_149_200_439_453 ) < 1E-2 assert abs(result_mean.item() - 0.16_226_289_014_816_284 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_663_360_595_703 ) < 1E-2 assert abs(result_mean.item() - 0.16_688_326_001_167_297 ) < 1E-3 else: assert abs(result_sum.item() - 119.8_487_548_828_125 ) < 1E-2 assert abs(result_mean.item() - 0.1_560_530_662_536_621 ) < 1E-3 def lowerCAmelCase ( self : str ) ->str: """simple docstring""" snake_case_ = self.scheduler_classes[0] snake_case_ = self.get_scheduler_config() snake_case_ = scheduler_class(**UpperCAmelCase_ ) scheduler.set_timesteps(self.num_inference_steps , device=UpperCAmelCase_ ) snake_case_ = self.dummy_model() snake_case_ = self.dummy_sample_deter.to(UpperCAmelCase_ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: snake_case_ = scheduler.scale_model_input(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = output.prev_sample snake_case_ = torch.sum(torch.abs(UpperCAmelCase_ ) ) snake_case_ = torch.mean(torch.abs(UpperCAmelCase_ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_957_397_460_938 ) < 1E-2 assert abs(result_mean.item() - 0.21_805_934_607_982_635 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_353_637_695_312 ) < 1E-2 assert abs(result_mean.item() - 0.22_342_908_382_415_771 ) < 1E-3 else: assert abs(result_sum.item() - 162.52_383_422_851_562 ) < 1E-2 assert abs(result_mean.item() - 0.211_619_570_851_326 ) < 1E-3 def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.scheduler_classes[0] snake_case_ = self.get_scheduler_config() snake_case_ = scheduler_class(**UpperCAmelCase_ , use_karras_sigmas=UpperCAmelCase_ ) scheduler.set_timesteps(self.num_inference_steps , device=UpperCAmelCase_ ) snake_case_ = self.dummy_model() snake_case_ = self.dummy_sample_deter.to(UpperCAmelCase_ ) * scheduler.init_noise_sigma snake_case_ = sample.to(UpperCAmelCase_ ) for t in scheduler.timesteps: snake_case_ = scheduler.scale_model_input(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = output.prev_sample snake_case_ = torch.sum(torch.abs(UpperCAmelCase_ ) ) snake_case_ = torch.mean(torch.abs(UpperCAmelCase_ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_974_135_742_188 ) < 1E-2 assert abs(result_mean.item() - 0.23_003_872_730_981_811 ) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_653_564_453_125 ) < 1E-2 assert abs(result_mean.item() - 0.23_003_872_730_981_811 ) < 1E-2 else: assert abs(result_sum.item() - 170.3_135_223_388_672 ) < 1E-2 assert abs(result_mean.item() - 0.23_003_872_730_981_811 ) < 1E-2
2
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: if index == number_of_items: return 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 ) if weights[index] <= max_weight: snake_case_ = values[index] + knapsack( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 ) return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) __SCREAMING_SNAKE_CASE : Dict = pytest.mark.integration @pytest.mark.parametrize("""path""" , ["""paws""", """csv"""] ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: inspect_dataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = path + """.py""" assert script_name in os.listdir(_SCREAMING_SNAKE_CASE ) assert "__pycache__" not in os.listdir(_SCREAMING_SNAKE_CASE ) @pytest.mark.filterwarnings("""ignore:inspect_metric is deprecated:FutureWarning""" ) @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""" ) @pytest.mark.parametrize("""path""" , ["""accuracy"""] ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: inspect_metric(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = path + """.py""" assert script_name in os.listdir(_SCREAMING_SNAKE_CASE ) assert "__pycache__" not in os.listdir(_SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """path, config_name, expected_splits""" , [ ("""squad""", """plain_text""", ["""train""", """validation"""]), ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]), ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ = get_dataset_config_info(_SCREAMING_SNAKE_CASE , config_name=_SCREAMING_SNAKE_CASE ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( """path, config_name, expected_exception""" , [ ("""paws""", None, ValueError), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: with pytest.raises(_SCREAMING_SNAKE_CASE ): get_dataset_config_info(_SCREAMING_SNAKE_CASE , config_name=_SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """path, expected""" , [ ("""squad""", """plain_text"""), ("""acronym_identification""", """default"""), ("""lhoestq/squad""", """plain_text"""), ("""lhoestq/test""", """default"""), ("""lhoestq/demo1""", """lhoestq--demo1"""), ("""dalle-mini/wit""", """dalle-mini--wit"""), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: snake_case_ = get_dataset_config_names(_SCREAMING_SNAKE_CASE ) assert expected in config_names @pytest.mark.parametrize( """path, expected_configs, expected_splits_in_first_config""" , [ ("""squad""", ["""plain_text"""], ["""train""", """validation"""]), ("""dalle-mini/wit""", ["""dalle-mini--wit"""], ["""train"""]), ("""paws""", ["""labeled_final""", """labeled_swap""", """unlabeled_final"""], ["""train""", """test""", """validation"""]), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = get_dataset_infos(_SCREAMING_SNAKE_CASE ) assert list(infos.keys() ) == expected_configs snake_case_ = expected_configs[0] assert expected_config in infos snake_case_ = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( """path, expected_config, expected_splits""" , [ ("""squad""", """plain_text""", ["""train""", """validation"""]), ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]), ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: snake_case_ = get_dataset_infos(_SCREAMING_SNAKE_CASE ) assert expected_config in infos snake_case_ = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( """path, config_name, expected_exception""" , [ ("""paws""", None, ValueError), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: with pytest.raises(_SCREAMING_SNAKE_CASE ): get_dataset_split_names(_SCREAMING_SNAKE_CASE , config_name=_SCREAMING_SNAKE_CASE )
2
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 20 ) -> int: snake_case_ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... snake_case_ = n // 2 return int(factorial(_SCREAMING_SNAKE_CASE ) / (factorial(_SCREAMING_SNAKE_CASE ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: __SCREAMING_SNAKE_CASE : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
2
1
"""simple docstring""" import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger __SCREAMING_SNAKE_CASE : Optional[int] = get_logger(__name__) __SCREAMING_SNAKE_CASE : Union[str, Any] = R'\n Args:\n input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n search or log softmax for each vocabulary token when using beam search\n kwargs (`Dict[str, Any]`, *optional*):\n Additional logits processor specific kwargs.\n\n Return:\n `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n' class __A : '''simple docstring''' @add_start_docstrings(UpperCAmelCase_ ) def __call__( self : int , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : jnp.ndarray ) ->jnp.ndarray: """simple docstring""" raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class __A : '''simple docstring''' @add_start_docstrings(UpperCAmelCase_ ) def __call__( self : Dict , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : jnp.ndarray ) ->jnp.ndarray: """simple docstring""" raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class __A (snake_case__): '''simple docstring''' @add_start_docstrings(UpperCAmelCase_ ) def __call__( self : int , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : int , **UpperCAmelCase_ : List[Any] ) ->jnp.ndarray: """simple docstring""" for processor in self: snake_case_ = inspect.signature(processor.__call__ ).parameters if len(UpperCAmelCase_ ) > 3: if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ): raise ValueError( F"""Make sure that all the required parameters: {list(function_args.keys() )} for """ F"""{processor.__class__} are passed to the logits processor.""" ) snake_case_ = processor(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ ) else: snake_case_ = processor(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) return scores class __A (snake_case__): '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : float ) ->Optional[int]: """simple docstring""" if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or not (temperature > 0): raise ValueError(F"""`temperature` has to be a strictly positive float, but is {temperature}""" ) snake_case_ = temperature def __call__( self : Dict , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : int ) ->jnp.ndarray: """simple docstring""" snake_case_ = scores / self.temperature return scores class __A (snake_case__): '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : float , UpperCAmelCase_ : float = -float("""Inf""" ) , UpperCAmelCase_ : int = 1 ) ->str: """simple docstring""" if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or (top_p < 0 or top_p > 1.0): raise ValueError(F"""`top_p` has to be a float > 0 and < 1, but is {top_p}""" ) if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or (min_tokens_to_keep < 1): raise ValueError(F"""`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}""" ) snake_case_ = top_p snake_case_ = filter_value snake_case_ = min_tokens_to_keep def __call__( self : Union[str, Any] , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : int ) ->jnp.ndarray: """simple docstring""" snake_case_ , snake_case_ = lax.top_k(UpperCAmelCase_ , scores.shape[-1] ) snake_case_ = jnp.full_like(UpperCAmelCase_ , self.filter_value ) snake_case_ = jax.nn.softmax(UpperCAmelCase_ , axis=-1 ).cumsum(axis=-1 ) snake_case_ = cumulative_probs < self.top_p # include the token that is higher than top_p as well snake_case_ = jnp.roll(UpperCAmelCase_ , 1 ) score_mask |= score_mask.at[:, 0].set(UpperCAmelCase_ ) # min tokens to keep snake_case_ = score_mask.at[:, : self.min_tokens_to_keep].set(UpperCAmelCase_ ) snake_case_ = jnp.where(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = jax.lax.sort_key_val(UpperCAmelCase_ , UpperCAmelCase_ )[-1] return next_scores class __A (snake_case__): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : float = -float("""Inf""" ) , UpperCAmelCase_ : int = 1 ) ->Dict: """simple docstring""" if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or top_k <= 0: raise ValueError(F"""`top_k` has to be a strictly positive integer, but is {top_k}""" ) snake_case_ = max(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = filter_value def __call__( self : Tuple , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : int ) ->jnp.ndarray: """simple docstring""" snake_case_ , snake_case_ = scores.shape snake_case_ = jnp.full(batch_size * vocab_size , self.filter_value ) snake_case_ = min(self.top_k , scores.shape[-1] ) # Safety check snake_case_ , snake_case_ = lax.top_k(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = jnp.broadcast_to((jnp.arange(UpperCAmelCase_ ) * vocab_size)[:, None] , (batch_size, topk) ).flatten() snake_case_ = topk_scores.flatten() snake_case_ = topk_indices.flatten() + shift snake_case_ = next_scores_flat.at[topk_indices_flat].set(UpperCAmelCase_ ) snake_case_ = next_scores_flat.reshape(UpperCAmelCase_ , UpperCAmelCase_ ) return next_scores class __A (snake_case__): '''simple docstring''' def __init__( self : Any , UpperCAmelCase_ : int ) ->Optional[Any]: """simple docstring""" snake_case_ = bos_token_id def __call__( self : Tuple , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : int ) ->jnp.ndarray: """simple docstring""" snake_case_ = jnp.full(scores.shape , -float("""inf""" ) ) snake_case_ = 1 - jnp.bool_(cur_len - 1 ) snake_case_ = jnp.where(UpperCAmelCase_ , new_scores.at[:, self.bos_token_id].set(0 ) , UpperCAmelCase_ ) return scores class __A (snake_case__): '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) ->Tuple: """simple docstring""" snake_case_ = max_length snake_case_ = eos_token_id def __call__( self : List[Any] , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : int ) ->jnp.ndarray: """simple docstring""" snake_case_ = jnp.full(scores.shape , -float("""inf""" ) ) snake_case_ = 1 - jnp.bool_(cur_len - self.max_length + 1 ) snake_case_ = jnp.where(UpperCAmelCase_ , new_scores.at[:, self.eos_token_id].set(0 ) , UpperCAmelCase_ ) return scores class __A (snake_case__): '''simple docstring''' def __init__( self : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) ->List[str]: """simple docstring""" if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or min_length < 0: raise ValueError(F"""`min_length` has to be a positive integer, but is {min_length}""" ) if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or eos_token_id < 0: raise ValueError(F"""`eos_token_id` has to be a positive integer, but is {eos_token_id}""" ) snake_case_ = min_length snake_case_ = eos_token_id def __call__( self : Union[str, Any] , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : int ) ->jnp.ndarray: """simple docstring""" snake_case_ = 1 - jnp.clip(cur_len - self.min_length , 0 , 1 ) snake_case_ = jnp.where(UpperCAmelCase_ , scores.at[:, self.eos_token_id].set(-float("""inf""" ) ) , UpperCAmelCase_ ) return scores class __A (snake_case__): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = list(UpperCAmelCase_ ) snake_case_ = begin_index def __call__( self : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int ) ->List[str]: """simple docstring""" snake_case_ = 1 - jnp.bool_(cur_len - self.begin_index ) snake_case_ = jnp.where(UpperCAmelCase_ , scores.at[:, self.begin_suppress_tokens].set(-float("""inf""" ) ) , UpperCAmelCase_ ) return scores class __A (snake_case__): '''simple docstring''' def __init__( self : Any , UpperCAmelCase_ : list ) ->List[str]: """simple docstring""" snake_case_ = list(UpperCAmelCase_ ) def __call__( self : int , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : int ) ->jnp.ndarray: """simple docstring""" snake_case_ = scores.at[..., self.suppress_tokens].set(-float("""inf""" ) ) return scores class __A (snake_case__): '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Tuple ) ->Optional[Any]: """simple docstring""" snake_case_ = dict(UpperCAmelCase_ ) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. snake_case_ = jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1 for index, token in force_token_map.items(): if token is not None: snake_case_ = force_token_array.at[index].set(UpperCAmelCase_ ) snake_case_ = jnp.intaa(UpperCAmelCase_ ) def __call__( self : Optional[Any] , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : jnp.ndarray , UpperCAmelCase_ : int ) ->jnp.ndarray: """simple docstring""" def _force_token(UpperCAmelCase_ : List[Any] ): snake_case_ = scores.shape[0] snake_case_ = self.force_token_array[generation_idx] snake_case_ = jnp.ones_like(UpperCAmelCase_ , dtype=scores.dtype ) * -float("""inf""" ) snake_case_ = jnp.zeros((batch_size, 1) , dtype=scores.dtype ) snake_case_ = lax.dynamic_update_slice(UpperCAmelCase_ , UpperCAmelCase_ , (0, current_token) ) return new_scores snake_case_ = lax.cond( cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond( self.force_token_array[cur_len] >= 0 , lambda: _force_token(UpperCAmelCase_ ) , lambda: scores , ) , ) return scores class __A (snake_case__): '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str ) ->int: """simple docstring""" snake_case_ = generate_config.eos_token_id snake_case_ = generate_config.no_timestamps_token_id snake_case_ = generate_config.no_timestamps_token_id + 1 snake_case_ = decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(UpperCAmelCase_ , """max_initial_timestamp_index""" ): snake_case_ = generate_config.max_initial_timestamp_index else: snake_case_ = model_config.vocab_size if self.max_initial_timestamp_index is None: snake_case_ = model_config.vocab_size def __call__( self : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = scores.at[:, self.no_timestamps_token_id].set(-float("""inf""" ) ) def handle_pairs(UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] ): snake_case_ = jnp.where((cur_len - self.begin_index) >= 1 , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , UpperCAmelCase_ , ) snake_case_ = jnp.where((cur_len - self.begin_index) < 2 , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin , UpperCAmelCase_ , UpperCAmelCase_ , ) return jnp.where( UpperCAmelCase_ , jnp.where( penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float("""inf""" ) ) , scores_k.at[: self.eos_token_id].set(-float("""inf""" ) ) , ) , UpperCAmelCase_ , ) snake_case_ = jax.vmap(UpperCAmelCase_ )(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = jnp.where(cur_len == self.begin_index , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = jnp.where( self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , UpperCAmelCase_ , ) snake_case_ = self.timestamp_begin + self.max_initial_timestamp_index snake_case_ = jnp.where( UpperCAmelCase_ , scores.at[:, last_allowed + 1 :].set(-float("""inf""" ) ) , UpperCAmelCase_ , ) # if sum of probability over timestamps is above any other token, sample timestamp snake_case_ = jax.nn.log_softmax(UpperCAmelCase_ , axis=-1 ) def handle_cumulative_probs(UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ): snake_case_ = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 ) snake_case_ = jnp.max(logprobs_k[: self.timestamp_begin] ) return jnp.where( timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float("""inf""" ) ) , UpperCAmelCase_ , ) snake_case_ = jax.vmap(UpperCAmelCase_ )(UpperCAmelCase_ , UpperCAmelCase_ ) return scores
2
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _a ( _SCREAMING_SNAKE_CASE = 8 ) -> str: snake_case_ = ascii_letters + digits + punctuation return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(_SCREAMING_SNAKE_CASE ) snake_case_ = i // 3 snake_case_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case_ = ( chars_incl + random(_SCREAMING_SNAKE_CASE , quotient + remainder ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) snake_case_ = list(_SCREAMING_SNAKE_CASE ) shuffle(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) # random is a generalised function for letters, characters and numbers def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 8 ) -> bool: if len(_SCREAMING_SNAKE_CASE ) < min_length: # Your Password must be at least 8 characters long return False snake_case_ = any(char in ascii_uppercase for char in password ) snake_case_ = any(char in ascii_lowercase for char in password ) snake_case_ = any(char in digits for char in password ) snake_case_ = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _a ( ) -> str: snake_case_ = int(input("""Please indicate the max length of your password: """ ).strip() ) snake_case_ = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(_SCREAMING_SNAKE_CASE ) ) print( """Alternative Password generated:""" , alternative_password_generator(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
2
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Union[str, Any] = '▁' __SCREAMING_SNAKE_CASE : int = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} __SCREAMING_SNAKE_CASE : Any = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } __SCREAMING_SNAKE_CASE : Any = {'vinai/bartpho-syllable': 1_024} class __A (snake_case__): '''simple docstring''' __lowercase: Dict = VOCAB_FILES_NAMES __lowercase: str = PRETRAINED_VOCAB_FILES_MAP __lowercase: Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase: Tuple = ["""input_ids""", """attention_mask"""] def __init__( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str="<s>" , UpperCAmelCase_ : str="</s>" , UpperCAmelCase_ : Dict="</s>" , UpperCAmelCase_ : int="<s>" , UpperCAmelCase_ : Tuple="<unk>" , UpperCAmelCase_ : Union[str, Any]="<pad>" , UpperCAmelCase_ : Optional[int]="<mask>" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : List[Any] , ) ->None: """simple docstring""" snake_case_ = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = vocab_file snake_case_ = monolingual_vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(UpperCAmelCase_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility snake_case_ = {} snake_case_ = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(UpperCAmelCase_ ) not in self.fairseq_tokens_to_ids: snake_case_ = cnt cnt += 1 with open(UpperCAmelCase_ , """r""" , encoding="""utf-8""" ) as f: for line in f.readlines(): snake_case_ = line.strip().split()[0] snake_case_ = len(self.fairseq_tokens_to_ids ) if str(UpperCAmelCase_ ) not in self.fairseq_tokens_to_ids: snake_case_ = len(self.fairseq_tokens_to_ids ) snake_case_ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : List[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None snake_case_ = self.sp_model.serialized_model_proto() return state def __setstate__( self : int , UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case_ = [self.cls_token_id] snake_case_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1, 1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" return len(self.fairseq_ids_to_tokens ) def lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" return self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" return self.fairseq_ids_to_tokens[index] def lowerCAmelCase ( self : str , UpperCAmelCase_ : List[Any] ) ->List[str]: """simple docstring""" snake_case_ = """""".join(UpperCAmelCase_ ).replace(UpperCAmelCase_ , """ """ ).strip() return out_string def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""monolingual_vocab_file"""] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( UpperCAmelCase_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(UpperCAmelCase_ , """w""" , encoding="""utf-8""" ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"""{str(UpperCAmelCase_ )} \n""" ) return out_vocab_file, out_monolingual_vocab_file
2
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset 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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=18 , UpperCAmelCase_ : Optional[Any]=30 , UpperCAmelCase_ : str=400 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[Any]=True , ) ->Optional[Any]: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = ImageGPTImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """clusters""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) snake_case_ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key] ) ) else: self.assertEqual(obj[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(UpperCAmelCase_ , """image_processor.json""" ) image_processor_first.to_json_file(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_json_file(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_pretrained(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" pass def _a ( ) -> str: snake_case_ = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) snake_case_ = Image.open(dataset[4]["""file"""] ) snake_case_ = Image.open(dataset[5]["""file"""] ) snake_case_ = [imagea, imagea] return images @require_vision @require_torch class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) snake_case_ = prepare_images() # test non-batched snake_case_ = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_024) ) snake_case_ = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_ ) # test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_024) ) snake_case_ = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_ )
2
1
"""simple docstring""" from pathlib import Path import fire def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: snake_case_ = Path(_SCREAMING_SNAKE_CASE ) snake_case_ = Path(_SCREAMING_SNAKE_CASE ) dest_dir.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) for path in src_dir.iterdir(): snake_case_ = [x.rstrip() for x in list(path.open().readlines() )][:n] snake_case_ = dest_dir.joinpath(path.name ) print(_SCREAMING_SNAKE_CASE ) dest_path.open("""w""" ).write("""\n""".join(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": fire.Fire(minify)
2
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : Dict=24 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=1_000 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = scope snake_case_ = range_bbox def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = t if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = t snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->str: """simple docstring""" snake_case_ = LiltModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , ) ->Dict: """simple docstring""" snake_case_ = self.num_labels snake_case_ = LiltForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , ) ->Dict: """simple docstring""" snake_case_ = LiltForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowercase: Optional[Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: List[str] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ = LiltModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = LiltModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCAmelCase_ ) snake_case_ = torch.tensor([[1, 2]] , device=UpperCAmelCase_ ) snake_case_ = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ ) snake_case_ = torch.Size([1, 2, 768] ) snake_case_ = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=UpperCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase_ , atol=1E-3 ) )
2
1
"""simple docstring""" import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class __A (snake_case__): '''simple docstring''' __lowercase: List[str] = """char""" __lowercase: Any = """bpe""" __lowercase: Dict = """wp""" __SCREAMING_SNAKE_CASE : Any = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class __A (snake_case__): '''simple docstring''' __lowercase: str = ["""image_processor""", """char_tokenizer"""] __lowercase: Union[str, Any] = """ViTImageProcessor""" __lowercase: Any = """MgpstrTokenizer""" def __init__( self : Optional[Any] , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Dict ) ->Dict: """simple docstring""" snake_case_ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , UpperCAmelCase_ , ) snake_case_ = kwargs.pop("""feature_extractor""" ) snake_case_ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) snake_case_ = tokenizer snake_case_ = AutoTokenizer.from_pretrained("""gpt2""" ) snake_case_ = AutoTokenizer.from_pretrained("""bert-base-uncased""" ) super().__init__(UpperCAmelCase_ , UpperCAmelCase_ ) def __call__( self : Optional[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : Any ) ->Any: """simple docstring""" if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: snake_case_ = self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ ) if text is not None: snake_case_ = self.char_tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ ) if text is None: return inputs elif images is None: return encodings else: snake_case_ = encodings["""input_ids"""] return inputs def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] ) ->List[str]: """simple docstring""" snake_case_ , snake_case_ , snake_case_ = sequences snake_case_ = char_preds.size(0 ) snake_case_ , snake_case_ = self._decode_helper(UpperCAmelCase_ , """char""" ) snake_case_ , snake_case_ = self._decode_helper(UpperCAmelCase_ , """bpe""" ) snake_case_ , snake_case_ = self._decode_helper(UpperCAmelCase_ , """wp""" ) snake_case_ = [] snake_case_ = [] for i in range(UpperCAmelCase_ ): snake_case_ = [char_scores[i], bpe_scores[i], wp_scores[i]] snake_case_ = [char_strs[i], bpe_strs[i], wp_strs[i]] snake_case_ = scores.index(max(UpperCAmelCase_ ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) snake_case_ = {} snake_case_ = final_strs snake_case_ = final_scores snake_case_ = char_strs snake_case_ = bpe_strs snake_case_ = wp_strs return out def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" if format == DecodeType.CHARACTER: snake_case_ = self.char_decode snake_case_ = 1 snake_case_ = """[s]""" elif format == DecodeType.BPE: snake_case_ = self.bpe_decode snake_case_ = 2 snake_case_ = """#""" elif format == DecodeType.WORDPIECE: snake_case_ = self.wp_decode snake_case_ = 102 snake_case_ = """[SEP]""" else: raise ValueError(F"""Format {format} is not supported.""" ) snake_case_ , snake_case_ = [], [] snake_case_ = pred_logits.size(0 ) snake_case_ = pred_logits.size(1 ) snake_case_ , snake_case_ = pred_logits.topk(1 , dim=-1 , largest=UpperCAmelCase_ , sorted=UpperCAmelCase_ ) snake_case_ = preds_index.view(-1 , UpperCAmelCase_ )[:, 1:] snake_case_ = decoder(UpperCAmelCase_ ) snake_case_ , snake_case_ = torch.nn.functional.softmax(UpperCAmelCase_ , dim=2 ).max(dim=2 ) snake_case_ = preds_max_prob[:, 1:] for index in range(UpperCAmelCase_ ): snake_case_ = preds_str[index].find(UpperCAmelCase_ ) snake_case_ = preds_str[index][:pred_eos] snake_case_ = preds_index[index].cpu().tolist() snake_case_ = pred_index.index(UpperCAmelCase_ ) if eos_token in pred_index else -1 snake_case_ = preds_max_prob[index][: pred_eos_index + 1] snake_case_ = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(UpperCAmelCase_ ) conf_scores.append(UpperCAmelCase_ ) return dec_strs, conf_scores def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->Dict: """simple docstring""" snake_case_ = [seq.replace(""" """ , """""" ) for seq in self.char_tokenizer.batch_decode(UpperCAmelCase_ )] return decode_strs def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Optional[Any] ) ->str: """simple docstring""" return self.bpe_tokenizer.batch_decode(UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] ) ->str: """simple docstring""" snake_case_ = [seq.replace(""" """ , """""" ) for seq in self.wp_tokenizer.batch_decode(UpperCAmelCase_ )] return decode_strs
2
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
2
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class __A : '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : Optional[int] , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = 13 snake_case_ = 7 snake_case_ = True snake_case_ = True snake_case_ = False snake_case_ = True snake_case_ = 99 snake_case_ = 32 snake_case_ = 2 snake_case_ = 4 snake_case_ = 37 snake_case_ = """gelu""" snake_case_ = 0.1 snake_case_ = 0.1 snake_case_ = 512 snake_case_ = 16 snake_case_ = 2 snake_case_ = 0.02 snake_case_ = 3 snake_case_ = 4 snake_case_ = None def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = None snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int ) ->str: """simple docstring""" snake_case_ = TFDistilBertModel(config=UpperCAmelCase_ ) snake_case_ = {"""input_ids""": input_ids, """attention_mask""": input_mask} snake_case_ = model(UpperCAmelCase_ ) snake_case_ = [input_ids, input_mask] snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any] ) ->int: """simple docstring""" snake_case_ = TFDistilBertForMaskedLM(config=UpperCAmelCase_ ) snake_case_ = {"""input_ids""": input_ids, """attention_mask""": input_mask} snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str ) ->Optional[int]: """simple docstring""" snake_case_ = TFDistilBertForQuestionAnswering(config=UpperCAmelCase_ ) snake_case_ = { """input_ids""": input_ids, """attention_mask""": input_mask, } snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->int: """simple docstring""" snake_case_ = self.num_labels snake_case_ = TFDistilBertForSequenceClassification(UpperCAmelCase_ ) snake_case_ = {"""input_ids""": input_ids, """attention_mask""": input_mask} snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict ) ->int: """simple docstring""" snake_case_ = self.num_choices snake_case_ = TFDistilBertForMultipleChoice(UpperCAmelCase_ ) snake_case_ = tf.tile(tf.expand_dims(UpperCAmelCase_ , 1 ) , (1, self.num_choices, 1) ) snake_case_ = tf.tile(tf.expand_dims(UpperCAmelCase_ , 1 ) , (1, self.num_choices, 1) ) snake_case_ = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.num_labels snake_case_ = TFDistilBertForTokenClassification(UpperCAmelCase_ ) snake_case_ = {"""input_ids""": input_ids, """attention_mask""": input_mask} snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ((snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_)) = config_and_inputs snake_case_ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: str = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __lowercase: int = ( { """feature-extraction""": TFDistilBertModel, """fill-mask""": TFDistilBertForMaskedLM, """question-answering""": TFDistilBertForQuestionAnswering, """text-classification""": TFDistilBertForSequenceClassification, """token-classification""": TFDistilBertForTokenClassification, """zero-shot""": TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __lowercase: Any = False __lowercase: Optional[int] = False def lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" snake_case_ = TFDistilBertModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , dim=37 ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : List[Any] ) ->Optional[int]: """simple docstring""" for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): snake_case_ = TFDistilBertModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_tf class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) snake_case_ = tf.constant([[0, 1, 2, 3, 4, 5]] ) snake_case_ = model(UpperCAmelCase_ )[0] snake_case_ = [1, 6, 768] self.assertEqual(output.shape , UpperCAmelCase_ ) snake_case_ = tf.constant( [ [ [0.19_261_885, -0.13_732_955, 0.4_119_799], [0.22_150_156, -0.07_422_661, 0.39_037_204], [0.22_756_018, -0.0_896_414, 0.3_701_467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-4 )
2
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> set[str]: snake_case_ , snake_case_ = set(_SCREAMING_SNAKE_CASE ), [start] while stack: snake_case_ = stack.pop() explored.add(_SCREAMING_SNAKE_CASE ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(_SCREAMING_SNAKE_CASE ) return explored __SCREAMING_SNAKE_CASE : List[str] = { 'A': ['B', 'C', 'D'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B', 'D'], 'E': ['B', 'F'], 'F': ['C', 'E', 'G'], 'G': ['F'], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, 'A'))
2
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name class __A (snake_case__): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase_ : WhisperForConditionalGeneration , UpperCAmelCase_ : WhisperProcessor , UpperCAmelCase_ : AutoencoderKL , UpperCAmelCase_ : CLIPTextModel , UpperCAmelCase_ : CLIPTokenizer , UpperCAmelCase_ : UNetaDConditionModel , UpperCAmelCase_ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , UpperCAmelCase_ : StableDiffusionSafetyChecker , UpperCAmelCase_ : CLIPImageProcessor , ) ->Any: """simple docstring""" super().__init__() if safety_checker is None: logger.warning( F"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered""" """ results in services or applications open to the public. Both the diffusers team and Hugging Face""" """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling""" """ it only for use-cases that involve analyzing network behavior or auditing its results. For more""" """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 .""" ) self.register_modules( speech_model=UpperCAmelCase_ , speech_processor=UpperCAmelCase_ , vae=UpperCAmelCase_ , text_encoder=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Optional[Union[str, int]] = "auto" ) ->Dict: """simple docstring""" if slice_size == "auto": snake_case_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(UpperCAmelCase_ ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.enable_attention_slicing(UpperCAmelCase_ ) @torch.no_grad() def __call__( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Any=16_000 , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : float = 7.5 , UpperCAmelCase_ : Optional[Union[str, List[str]]] = None , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : Optional[torch.Generator] = None , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase_ : int = 1 , **UpperCAmelCase_ : int , ) ->Optional[int]: """simple docstring""" snake_case_ = self.speech_processor.feature_extractor( UpperCAmelCase_ , return_tensors="""pt""" , sampling_rate=UpperCAmelCase_ ).input_features.to(self.device ) snake_case_ = self.speech_model.generate(UpperCAmelCase_ , max_length=480_000 ) snake_case_ = self.speech_processor.tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ , normalize=UpperCAmelCase_ )[ 0 ] if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = 1 elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = len(UpperCAmelCase_ ) else: raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase_ )}""" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""" ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or callback_steps <= 0) ): raise ValueError( F"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" F""" {type(UpperCAmelCase_ )}.""" ) # get prompt text embeddings snake_case_ = self.tokenizer( UpperCAmelCase_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) snake_case_ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: snake_case_ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F""" {self.tokenizer.model_max_length} tokens: {removed_text}""" ) snake_case_ = text_input_ids[:, : self.tokenizer.model_max_length] snake_case_ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method snake_case_ , snake_case_ , snake_case_ = text_embeddings.shape snake_case_ = text_embeddings.repeat(1 , UpperCAmelCase_ , 1 ) snake_case_ = text_embeddings.view(bs_embed * num_images_per_prompt , UpperCAmelCase_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. snake_case_ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: snake_case_ = 42 if negative_prompt is None: snake_case_ = [""""""] * batch_size elif type(UpperCAmelCase_ ) is not type(UpperCAmelCase_ ): raise TypeError( F"""`negative_prompt` should be the same type to `prompt`, but got {type(UpperCAmelCase_ )} !=""" F""" {type(UpperCAmelCase_ )}.""" ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = [negative_prompt] elif batch_size != len(UpperCAmelCase_ ): raise ValueError( F"""`negative_prompt`: {negative_prompt} has batch size {len(UpperCAmelCase_ )}, but `prompt`:""" F""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches""" """ the batch size of `prompt`.""" ) else: snake_case_ = negative_prompt snake_case_ = text_input_ids.shape[-1] snake_case_ = self.tokenizer( UpperCAmelCase_ , padding="""max_length""" , max_length=UpperCAmelCase_ , truncation=UpperCAmelCase_ , return_tensors="""pt""" , ) snake_case_ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method snake_case_ = uncond_embeddings.shape[1] snake_case_ = uncond_embeddings.repeat(1 , UpperCAmelCase_ , 1 ) snake_case_ = uncond_embeddings.view(batch_size * num_images_per_prompt , UpperCAmelCase_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes snake_case_ = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. snake_case_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) snake_case_ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps snake_case_ = torch.randn(UpperCAmelCase_ , generator=UpperCAmelCase_ , device="""cpu""" , dtype=UpperCAmelCase_ ).to( self.device ) else: snake_case_ = torch.randn(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=self.device , dtype=UpperCAmelCase_ ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) snake_case_ = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand snake_case_ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler snake_case_ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] snake_case_ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case_ = {} if accepts_eta: snake_case_ = eta for i, t in enumerate(self.progress_bar(UpperCAmelCase_ ) ): # expand the latents if we are doing classifier free guidance snake_case_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case_ = self.scheduler.scale_model_input(UpperCAmelCase_ , UpperCAmelCase_ ) # predict the noise residual snake_case_ = self.unet(UpperCAmelCase_ , UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ ).sample # perform guidance if do_classifier_free_guidance: snake_case_ , snake_case_ = noise_pred.chunk(2 ) snake_case_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 snake_case_ = self.scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = 1 / 0.18_215 * latents snake_case_ = self.vae.decode(UpperCAmelCase_ ).sample snake_case_ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 snake_case_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": snake_case_ = self.numpy_to_pil(UpperCAmelCase_ ) if not return_dict: return image return StableDiffusionPipelineOutput(images=UpperCAmelCase_ , nsfw_content_detected=UpperCAmelCase_ )
2
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : List[str] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __SCREAMING_SNAKE_CASE : List[str] = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __SCREAMING_SNAKE_CASE : int = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[Any] = VOCAB_FILES_NAMES __lowercase: Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowercase: Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]="[CLS]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : str="<unk>" , UpperCAmelCase_ : str="[SEP]" , UpperCAmelCase_ : Optional[Any]="<pad>" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : int="[MASK]" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->None: """simple docstring""" snake_case_ = ( AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ , normalized=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token ) snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = do_lower_case snake_case_ = remove_space snake_case_ = keep_accents snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return len(self.sp_model ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Any ) ->str: """simple docstring""" if self.remove_space: snake_case_ = """ """.join(inputs.strip().split() ) else: snake_case_ = inputs snake_case_ = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: snake_case_ = unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) snake_case_ = """""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: snake_case_ = outputs.lower() return outputs def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.preprocess_text(UpperCAmelCase_ ) snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) snake_case_ = [] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): snake_case_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case_ = cur_pieces[1:] else: snake_case_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" return self.sp_model.PieceToId(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" return self.sp_model.IdToPiece(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Dict ) ->Any: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [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 lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
2
1
"""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 __SCREAMING_SNAKE_CASE : Union[str, Any] = pytest.mark.integration __SCREAMING_SNAKE_CASE : Optional[int] = {'comet'} __SCREAMING_SNAKE_CASE : Union[str, Any] = importlib.util.find_spec('fairseq') is not None __SCREAMING_SNAKE_CASE : Dict = {'code_eval'} __SCREAMING_SNAKE_CASE : str = os.name == 'nt' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'bertscore', 'frugalscore', 'perplexity'} __SCREAMING_SNAKE_CASE : Any = importlib.util.find_spec('transformers') is not None def _a ( _SCREAMING_SNAKE_CASE ) -> str: @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self , _SCREAMING_SNAKE_CASE ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("""\"test requires Fairseq\"""" ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self , _SCREAMING_SNAKE_CASE ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("""\"test requires transformers\"""" ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def _a ( _SCREAMING_SNAKE_CASE ) -> str: @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self , _SCREAMING_SNAKE_CASE ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("""\"test not supported on Windows\"""" ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def _a ( ) -> List[str]: snake_case_ = [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 __A (parameterized.TestCase): '''simple docstring''' __lowercase: Tuple = {} __lowercase: Tuple = None @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""" ) @pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning""" ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" snake_case_ = """[...]""" snake_case_ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("""metrics""" , UpperCAmelCase_ ) ).module_path ) snake_case_ = datasets.load.import_main_class(metric_module.__name__ , dataset=UpperCAmelCase_ ) # check parameters snake_case_ = 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(UpperCAmelCase_ , metric_module.__name__ ): with self.use_local_metrics(): try: snake_case_ = doctest.testmod(UpperCAmelCase_ , verbose=UpperCAmelCase_ , raise_on_error=UpperCAmelCase_ ) 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 lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[str] ) ->Any: """simple docstring""" snake_case_ = """[...]""" snake_case_ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("""metrics""" , UpperCAmelCase_ ) ).module_path ) # run doctest with self.use_local_metrics(): snake_case_ = doctest.testmod(UpperCAmelCase_ , verbose=UpperCAmelCase_ , raise_on_error=UpperCAmelCase_ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] ) ->int: """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](UpperCAmelCase_ ): yield else: yield @contextmanager def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" def load_local_metric(UpperCAmelCase_ : Optional[Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : str ): return load_metric(os.path.join("""metrics""" , UpperCAmelCase_ ) , *UpperCAmelCase_ , **UpperCAmelCase_ ) with patch("""datasets.load_metric""" ) as mock_load_metric: snake_case_ = load_local_metric yield @classmethod def lowerCAmelCase ( cls : Any , UpperCAmelCase_ : Dict ) ->List[Any]: """simple docstring""" def wrapper(UpperCAmelCase_ : Optional[int] ): snake_case_ = contextmanager(UpperCAmelCase_ ) snake_case_ = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("""bleurt""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> str: import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("""sv""" , """""" , """""" ) # handle pytest cli flags class __A (snake_case__): '''simple docstring''' def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" 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: snake_case_ = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("""bertscore""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: import torch def bert_cos_score_idf(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return torch.tensor([[1.0, 1.0, 1.0]] * len(_SCREAMING_SNAKE_CASE ) ) # 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: snake_case_ = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("""comet""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: def load_from_checkpoint(_SCREAMING_SNAKE_CASE ): class __A : '''simple docstring''' def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : str ) ->Any: """simple docstring""" assert len(UpperCAmelCase_ ) == 2 snake_case_ = [0.19, 0.92] return scores, sum(UpperCAmelCase_ ) / len(UpperCAmelCase_ ) 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: snake_case_ = None with patch("""comet.load_from_checkpoint""" ) as mock_load_from_checkpoint: snake_case_ = load_from_checkpoint yield def _a ( ) -> List[str]: snake_case_ = load_metric(os.path.join("""metrics""" , """seqeval""" ) ) snake_case_ = """ERROR""" snake_case_ = f"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ): metric.compute(predictions=[] , references=[] , scheme=_SCREAMING_SNAKE_CASE )
2
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
2
1
"""simple docstring""" import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class __A (snake_case__): '''simple docstring''' def __init__( self : Any , UpperCAmelCase_ : List[Any]=0.01 , UpperCAmelCase_ : Optional[int]=1_000 ) ->Tuple: """simple docstring""" snake_case_ = p_stop snake_case_ = max_length def __iter__( self : List[Any] ) ->int: """simple docstring""" snake_case_ = 0 snake_case_ = False while not stop and count < self.max_length: yield count count += 1 snake_case_ = random.random() < self.p_stop class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=True ) ->List[Any]: """simple docstring""" snake_case_ = [ BatchSamplerShard(UpperCAmelCase_ , 2 , UpperCAmelCase_ , split_batches=UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) for i in range(2 ) ] snake_case_ = [list(UpperCAmelCase_ ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(UpperCAmelCase_ ) for shard in batch_sampler_shards] , [len(UpperCAmelCase_ ) for e in expected] ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->Tuple: """simple docstring""" snake_case_ = BatchSampler(range(24 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = BatchSampler(range(24 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. snake_case_ = BatchSampler(range(21 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = BatchSampler(range(21 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. snake_case_ = BatchSampler(range(22 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = BatchSampler(range(22 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. snake_case_ = BatchSampler(range(20 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = BatchSampler(range(20 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ ) # Check the shards when the dataset is very small. snake_case_ = BatchSampler(range(2 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = BatchSampler(range(2 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [[], []] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" snake_case_ = BatchSampler(range(24 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(24 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size. snake_case_ = BatchSampler(range(22 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(22 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. snake_case_ = BatchSampler(range(21 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(21 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) # Check the shards when the dataset is very small. snake_case_ = BatchSampler(range(2 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(2 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [[], []] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = BatchSampler(range(24 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(24 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. snake_case_ = BatchSampler(range(21 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(21 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. snake_case_ = BatchSampler(range(22 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(22 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. snake_case_ = BatchSampler(range(20 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(20 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) # Check the shards when the dataset is very small. snake_case_ = BatchSampler(range(2 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [[[0, 1]], []] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(2 ) , batch_size=3 , drop_last=UpperCAmelCase_ ) snake_case_ = [[], []] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" snake_case_ = BatchSampler(range(24 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(24 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size. snake_case_ = BatchSampler(range(22 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(22 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. snake_case_ = BatchSampler(range(21 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(21 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) # Check the shards when the dataset is very small. snake_case_ = BatchSampler(range(2 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [[[0, 1]], []] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) snake_case_ = BatchSampler(range(2 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = [[], []] self.check_batch_sampler_shards(UpperCAmelCase_ , UpperCAmelCase_ , split_batches=UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" snake_case_ = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]] snake_case_ = [BatchSamplerShard(UpperCAmelCase_ , 2 , UpperCAmelCase_ , even_batches=UpperCAmelCase_ ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) , 3 ) self.assertEqual(len(batch_sampler_shards[1] ) , 2 ) self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [12, 13]] ) self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 10, 11]] ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]=2 , UpperCAmelCase_ : Tuple=False ) ->Tuple: """simple docstring""" random.seed(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) snake_case_ = [ IterableDatasetShard( UpperCAmelCase_ , batch_size=UpperCAmelCase_ , drop_last=UpperCAmelCase_ , num_processes=UpperCAmelCase_ , process_index=UpperCAmelCase_ , split_batches=UpperCAmelCase_ , ) for i in range(UpperCAmelCase_ ) ] snake_case_ = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(UpperCAmelCase_ ) iterable_dataset_lists.append(list(UpperCAmelCase_ ) ) snake_case_ = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size snake_case_ = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) ) self.assertTrue(len(UpperCAmelCase_ ) % shard_batch_size == 0 ) snake_case_ = [] for idx in range(0 , len(UpperCAmelCase_ ) , UpperCAmelCase_ ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(UpperCAmelCase_ ) < len(UpperCAmelCase_ ): reference += reference self.assertListEqual(UpperCAmelCase_ , reference[: len(UpperCAmelCase_ )] ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ = 42 snake_case_ = RandomIterableDataset() self.check_iterable_dataset_shards(UpperCAmelCase_ , UpperCAmelCase_ , batch_size=4 , drop_last=UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) self.check_iterable_dataset_shards(UpperCAmelCase_ , UpperCAmelCase_ , batch_size=4 , drop_last=UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) self.check_iterable_dataset_shards(UpperCAmelCase_ , UpperCAmelCase_ , batch_size=4 , drop_last=UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) self.check_iterable_dataset_shards(UpperCAmelCase_ , UpperCAmelCase_ , batch_size=4 , drop_last=UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) # Edge case with a very small dataset snake_case_ = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(UpperCAmelCase_ , UpperCAmelCase_ , batch_size=4 , drop_last=UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) self.check_iterable_dataset_shards(UpperCAmelCase_ , UpperCAmelCase_ , batch_size=4 , drop_last=UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) self.check_iterable_dataset_shards(UpperCAmelCase_ , UpperCAmelCase_ , batch_size=4 , drop_last=UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) self.check_iterable_dataset_shards(UpperCAmelCase_ , UpperCAmelCase_ , batch_size=4 , drop_last=UpperCAmelCase_ , split_batches=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = BatchSampler(range(16 ) , batch_size=4 , drop_last=UpperCAmelCase_ ) snake_case_ = SkipBatchSampler(UpperCAmelCase_ , 2 ) self.assertListEqual(list(UpperCAmelCase_ ) , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = SkipDataLoader(list(range(16 ) ) , batch_size=4 , skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" snake_case_ = DataLoader(list(range(16 ) ) , batch_size=4 ) snake_case_ = skip_first_batches(UpperCAmelCase_ , num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" snake_case_ = DataLoaderShard(list(range(16 ) ) , batch_size=4 ) for idx, _ in enumerate(UpperCAmelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(UpperCAmelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) def lowerCAmelCase ( self : str ) ->List[str]: """simple docstring""" Accelerator() snake_case_ = DataLoaderDispatcher(range(16 ) , batch_size=4 ) for idx, _ in enumerate(UpperCAmelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(UpperCAmelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
2
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
2
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
1
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html __SCREAMING_SNAKE_CASE : List[str] = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class __A : '''simple docstring''' __lowercase: List[str] = PegasusConfig __lowercase: Dict = {} __lowercase: Optional[Any] = """gelu""" def __init__( self : List[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str=13 , UpperCAmelCase_ : Dict=7 , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]=99 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : List[str]=5 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : Union[str, Any]=20 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : Tuple=0 , ) ->Optional[int]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = eos_token_id snake_case_ = pad_token_id snake_case_ = bos_token_id def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) snake_case_ = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) snake_case_ = np.concatenate([input_ids, eos_tensor] , axis=1 ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) snake_case_ = prepare_pegasus_inputs_dict(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) return config, inputs_dict def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : str ) ->str: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = model.encode(inputs_dict["""input_ids"""] ) snake_case_ , snake_case_ = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) snake_case_ = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) snake_case_ = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) snake_case_ = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase_ , decoder_attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , decoder_position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase_ , decoder_attention_mask=UpperCAmelCase_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCAmelCase_ , ) snake_case_ = model.decode(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = model.encode(inputs_dict["""input_ids"""] ) snake_case_ , snake_case_ = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) snake_case_ = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) snake_case_ = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) snake_case_ = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase_ , decoder_attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , decoder_position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCAmelCase_ , decoder_position_ids=UpperCAmelCase_ , ) snake_case_ = model.decode(UpperCAmelCase_ , UpperCAmelCase_ , decoder_attention_mask=UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , ) -> Dict: if attention_mask is None: snake_case_ = np.not_equal(_SCREAMING_SNAKE_CASE , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: snake_case_ = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __lowercase: Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __lowercase: List[str] = True __lowercase: str = False __lowercase: Optional[int] = False __lowercase: List[str] = False def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = FlaxPegasusModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = model_class(UpperCAmelCase_ ) @jax.jit def encode_jitted(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Optional[Any] ): return model.encode(input_ids=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) with self.subTest("""JIT Enabled""" ): snake_case_ = encode_jitted(**UpperCAmelCase_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): snake_case_ = encode_jitted(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) ) for jitted_output, output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) snake_case_ = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] ): return model.decode( decoder_input_ids=UpperCAmelCase_ , decoder_attention_mask=UpperCAmelCase_ , encoder_outputs=UpperCAmelCase_ , ) with self.subTest("""JIT Enabled""" ): snake_case_ = decode_jitted(**UpperCAmelCase_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): snake_case_ = decode_jitted(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) ) for jitted_output, output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=UpperCAmelCase_ ) snake_case_ = np.ones((1, 1) ) snake_case_ = model(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""" ) snake_case_ = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""" ) snake_case_ = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] snake_case_ = [ """California's largest electricity provider has turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] snake_case_ = tokenizer(UpperCAmelCase_ , return_tensors="""np""" , truncation=UpperCAmelCase_ , max_length=512 , padding=UpperCAmelCase_ ) snake_case_ = model.generate(**UpperCAmelCase_ , num_beams=2 ).sequences snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) assert tgt_text == decoded
2
"""simple docstring""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): '''simple docstring''' @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
2
1