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
def _SCREAMING_SNAKE_CASE ( a = 1_00 ) -> Optional[int]: __A : Union[str, Any] = 0 __A : Optional[Any] = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(F"""{solution() = }""")
701
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : str = { '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''', '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''', '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''', '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''', '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''', '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''', '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''', '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''', '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''', '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''', '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''', '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = '''codegen''' UpperCamelCase : List[str] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ): __A : Any = vocab_size __A : Tuple = n_ctx __A : Union[str, Any] = n_positions __A : Optional[Any] = n_embd __A : Any = n_layer __A : Dict = n_head __A : Union[str, Any] = n_inner __A : List[Any] = rotary_dim __A : str = activation_function __A : Any = resid_pdrop __A : Tuple = embd_pdrop __A : Tuple = attn_pdrop __A : Union[str, Any] = layer_norm_epsilon __A : str = initializer_range __A : Optional[Any] = use_cache __A : Union[str, Any] = bos_token_id __A : Tuple = eos_token_id super().__init__( bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A ) class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A = "default" , _A = None , _A = False , ): super().__init__(_A , task=_A , patching_specs=_A , use_past=_A ) if not getattr(self._config , 'pad_token_id' , _A ): # TODO: how to do that better? __A : Dict = 0 @property def UpperCAmelCase_ ( self ): __A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) __A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'} else: __A : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase_ ( self ): return self._config.n_layer @property def UpperCAmelCase_ ( self ): return self._config.n_head def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Any = super(_A , self ).generate_dummy_inputs( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) # We need to order the input in the way they appears in the forward() __A : str = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __A , __A : Any = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Any = seqlen + 2 __A : List[str] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __A : Optional[Any] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] __A : Tuple = common_inputs['attention_mask'] if self.use_past: __A : str = ordered_inputs['attention_mask'].dtype __A : List[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self ): return 13
77
0
from collections.abc import Sequence def _SCREAMING_SNAKE_CASE ( a = None ) -> int: if nums is None or not nums: raise ValueError('Input sequence should not be empty' ) __A : Dict = nums[0] for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): __A : Any = nums[i] __A : Dict = max(_SCREAMING_SNAKE_CASE , ans + num , _SCREAMING_SNAKE_CASE ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user UpperCAmelCase : Any = int(input('''Enter number of elements : ''').strip()) UpperCAmelCase : Optional[int] = list(map(int, input('''\nEnter the numbers : ''').strip().split()))[:n] print(max_subsequence_sum(array))
702
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase : List[Any] = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _A , ) super().__init__(*_A , **_A )
77
0
def _SCREAMING_SNAKE_CASE ( a ) -> list: __A : Optional[int] = [0] * len(a ) for i in range(1 , len(a ) ): # use last results for better performance - dynamic programming __A : Optional[int] = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: __A : Union[str, Any] = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 __A : Optional[int] = j return prefix_result def _SCREAMING_SNAKE_CASE ( a ) -> int: return max(prefix_function(a ) ) if __name__ == "__main__": import doctest doctest.testmod()
703
import glob import os import random from string import ascii_lowercase, digits import cva UpperCAmelCase : Dict = '''''' UpperCAmelCase : Union[str, Any] = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal) def _SCREAMING_SNAKE_CASE ( ) -> None: __A , __A : List[Any] = get_dataset(a , a ) print('Processing...' ) __A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a ) for index, image in enumerate(a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __A : Optional[int] = random_chars(32 ) __A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] __A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Success {index+1}/{len(a )} with {file_name}""" ) __A : int = [] for anno in new_annos[index]: __A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(a ) with open(F"""/{file_root}.txt""" , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]: __A : int = [] __A : List[Any] = [] for label_file in glob.glob(os.path.join(a , '*.txt' ) ): __A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(a ) as in_file: __A : Tuple = in_file.readlines() __A : Dict = os.path.join(a , F"""{label_name}.jpg""" ) __A : Dict = [] for obj_list in obj_lists: __A : int = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(a ) labels.append(a ) return img_paths, labels def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]: __A : int = [] __A : Optional[Any] = [] __A : Dict = [] for idx in range(len(a ) ): __A : Dict = [] __A : Optional[Any] = img_list[idx] path_list.append(a ) __A : Union[str, Any] = anno_list[idx] __A : Optional[Any] = cva.imread(a ) if flip_type == 1: __A : Any = cva.flip(a , a ) for bbox in img_annos: __A : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __A : Union[str, Any] = cva.flip(a , a ) for bbox in img_annos: __A : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(a ) new_imgs_list.append(a ) return new_imgs_list, new_annos_lists, path_list def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __A : List[Any] = ascii_lowercase + digits return "".join(random.choice(a ) for _ in range(a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
77
0
import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' , UpperCamelCase_ , ) super().__init__(*UpperCamelCase_ , **UpperCamelCase_ )
704
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A: """simple docstring""" def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=True , _A=False , _A=True , _A=99 , _A=32 , _A=5 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=16 , _A=2 , _A=0.0_2 , _A=3 , _A=4 , _A=None , ): __A : Union[str, Any] = parent __A : List[str] = batch_size __A : Optional[int] = seq_length __A : List[Any] = is_training __A : Optional[Any] = use_input_mask __A : List[Any] = use_token_type_ids __A : Optional[Any] = use_labels __A : List[str] = vocab_size __A : Optional[int] = hidden_size __A : List[Any] = num_hidden_layers __A : int = num_attention_heads __A : Dict = intermediate_size __A : Any = hidden_act __A : Union[str, Any] = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : Optional[int] = max_position_embeddings __A : Dict = type_vocab_size __A : Any = type_sequence_label_size __A : Dict = initializer_range __A : str = num_labels __A : Union[str, Any] = num_choices __A : str = scope def UpperCAmelCase_ ( self ): __A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : Optional[Any] = None if self.use_input_mask: __A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __A : Dict = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = None __A : List[Any] = None __A : List[Any] = None if self.use_labels: __A : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __A : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[str] = LlamaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A , attention_mask=_A ) __A : Any = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Dict = True __A : int = LlamaModel(_A ) model.to(_A ) model.eval() __A : str = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __A : int = model( _A , attention_mask=_A , encoder_hidden_states=_A , ) __A : List[Any] = model(_A , attention_mask=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Optional[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : int = True __A : List[Any] = True __A : List[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() # first forward pass __A : Optional[Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , ) __A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __A : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) __A : str = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __A : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : str = torch.cat([input_mask, next_mask] , dim=-1 ) __A : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['hidden_states'][0] __A : Union[str, Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , past_key_values=_A , output_hidden_states=_A , )['hidden_states'][0] # select random slice __A : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() __A : Tuple = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_A , _A , atol=1e-3 ) ) def UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Tuple = config_and_inputs __A : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () UpperCamelCase : Optional[Any] = (LlamaForCausalLM,) if is_torch_available() else () UpperCamelCase : Optional[Any] = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False def UpperCAmelCase_ ( self ): __A : List[Any] = LlamaModelTester(self ) __A : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : int = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() __A : str = 3 __A : Optional[int] = input_dict['input_ids'] __A : int = input_ids.ne(1 ).to(_A ) __A : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Union[str, Any] = 3 __A : Tuple = 'single_label_classification' __A : Union[str, Any] = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[int] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Any = 3 __A : int = 'multi_label_classification' __A : int = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __A : List[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def UpperCAmelCase_ ( self ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def UpperCAmelCase_ ( self , _A ): __A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Dict = ids_tensor([1, 10] , config.vocab_size ) __A : Union[str, Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : List[Any] = LlamaModel(_A ) original_model.to(_A ) original_model.eval() __A : Dict = original_model(_A ).last_hidden_state __A : int = original_model(_A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : int = {'type': scaling_type, 'factor': 1_0.0} __A : str = LlamaModel(_A ) scaled_model.to(_A ) scaled_model.eval() __A : Dict = scaled_model(_A ).last_hidden_state __A : str = scaled_model(_A ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(_A , _A , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) __A : Union[str, Any] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __A : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[str] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) __A : int = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) __A : Optional[int] = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : Optional[Any] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) __A : List[Any] = model(torch.tensor(_A ) ) __A : Tuple = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # fmt: off __A : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' __A : List[str] = 'Simply put, the theory of relativity states that ' __A : Union[str, Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) __A : List[str] = tokenizer.encode(_A , return_tensors='pt' ) __A : Tuple = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=_A ) # greedy generation outputs __A : Union[str, Any] = model.generate(_A , max_new_tokens=64 , top_p=_A , temperature=1 , do_sample=_A ) __A : List[str] = tokenizer.decode(generated_ids[0] , skip_special_tokens=_A ) self.assertEqual(_A , _A )
77
0
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 UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(lowercase__ ) class _A( lowercase__ ): """simple docstring""" def __init__( self , **_A ): super().__init__(**__lowerCamelCase ) if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""" ) # No specific FOR_XXX available yet def __call__( self , _A , **_A ): return super().__call__(__lowerCamelCase , **__lowerCamelCase ) def UpperCAmelCase_ ( self , **_A ): __A : Optional[Any] = {} if "candidate_labels" in kwargs: __A : Union[str, Any] = kwargs["candidate_labels"] if "hypothesis_template" in kwargs: __A : List[Any] = kwargs["hypothesis_template"] return preprocess_params, {}, {} def UpperCAmelCase_ ( self , _A , _A=None , _A="This is a sound of {}." ): if isinstance(__lowerCamelCase , __lowerCamelCase ): 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 __A : Union[str, Any] = requests.get(__lowerCamelCase ).content else: with open(__lowerCamelCase , 'rb' ) as f: __A : List[Any] = f.read() if isinstance(__lowerCamelCase , __lowerCamelCase ): __A : Tuple = ffmpeg_read(__lowerCamelCase , self.feature_extractor.sampling_rate ) if not isinstance(__lowerCamelCase , 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' ) __A : List[str] = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='pt' ) __A : Dict = candidate_labels __A : List[Any] = [hypothesis_template.format(__lowerCamelCase ) for x in candidate_labels] __A : List[str] = self.tokenizer(__lowerCamelCase , return_tensors=self.framework , padding=__lowerCamelCase ) __A : Union[str, Any] = [text_inputs] return inputs def UpperCAmelCase_ ( self , _A ): __A : Union[str, Any] = model_inputs.pop('candidate_labels' ) __A : str = model_inputs.pop('text_inputs' ) if isinstance(text_inputs[0] , __lowerCamelCase ): __A : int = text_inputs[0] else: # Batching case. __A : List[str] = text_inputs[0][0] __A : List[Any] = self.model(**__lowerCamelCase , **__lowerCamelCase ) __A : Union[str, Any] = { "candidate_labels": candidate_labels, "logits": outputs.logits_per_audio, } return model_outputs def UpperCAmelCase_ ( self , _A ): __A : List[Any] = model_outputs.pop('candidate_labels' ) __A : int = model_outputs["logits"][0] if self.framework == "pt": __A : Dict = logits.softmax(dim=0 ) __A : str = probs.tolist() else: raise ValueError('`tf` framework not supported.' ) __A : Optional[Any] = [ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(__lowerCamelCase , __lowerCamelCase ) , key=lambda _A : -x[0] ) ] return result
705
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
0
import math def _SCREAMING_SNAKE_CASE ( a , a ) -> Union[str, Any]: if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(lowerCamelCase_ ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError('This should never happen' ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. UpperCAmelCase : str = '''Enter the base and the power separated by a comma: ''' UpperCAmelCase , UpperCAmelCase : Optional[Any] = map(int, input(prompt).split(''',''')) UpperCAmelCase , UpperCAmelCase : Tuple = map(int, input(prompt).split(''',''')) # We find the log of each number, using the function res(), which takes two # arguments. UpperCAmelCase : str = res(xa, ya) UpperCAmelCase : int = res(xa, ya) # We check for the largest number if resa > resa: print('''Largest number is''', xa, '''^''', ya) elif resa > resa: print('''Largest number is''', xa, '''^''', ya) else: print('''Both are equal''')
706
import numpy as np from PIL import Image def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : Union[str, Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : List[Any] = 0 __A : Optional[Any] = 0 __A : List[Any] = 0 __A : Dict = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __A : Tuple = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : List[str] = 0 __A : Union[str, Any] = 0 return updated_arr def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : List[Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : Dict = 0 __A : str = 0 __A : Tuple = 0 __A : Optional[int] = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __A : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : Dict = 0 __A : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image UpperCAmelCase : int = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
77
0
import math import os import sys def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : str = '' try: with open(a , 'rb' ) as binary_file: __A : Union[str, Any] = binary_file.read() for dat in data: __A : str = F"""{dat:08b}""" result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> None: lexicon.pop(a ) __A : Dict = last_match_id if math.loga(a ).is_integer(): for curr_key in lexicon: __A : Dict = '0' + lexicon[curr_key] __A : str = bin(a )[2:] def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : Optional[Any] = {'0': '0', '1': '1'} __A : Union[str, Any] = '', '' __A : List[str] = len(a ) for i in range(len(a ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __A : List[Any] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(a , a , a , a ) index += 1 __A : Any = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": __A : Optional[int] = lexicon[curr_string] result += last_match_id return result def _SCREAMING_SNAKE_CASE ( a , a ) -> str: __A : Union[str, Any] = os.path.getsize(a ) __A : Dict = bin(a )[2:] __A : int = len(a ) return "0" * (length_length - 1) + file_length_binary + compressed def _SCREAMING_SNAKE_CASE ( a , a ) -> None: __A : List[str] = 8 try: with open(a , 'wb' ) as opened_file: __A : str = [ to_write[i : i + byte_length] for i in range(0 , len(a ) , a ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(a , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _SCREAMING_SNAKE_CASE ( a , a ) -> None: __A : Tuple = read_file_binary(a ) __A : List[str] = compress_data(a ) __A : Any = add_file_length(a , a ) write_file_binary(a , a ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
707
from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float: __A : Any = x_start __A : List[str] = fnc(a ) __A : Optional[Any] = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area __A : Any = (x_end - x_start) / steps + xa __A : List[str] = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __A : Any = xa __A : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( a ) -> int: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') UpperCAmelCase : Tuple = 10 while i <= 10_00_00: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
77
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase : str = logging.get_logger(__name__) UpperCAmelCase : str = { '''facebook/xmod-base''': '''https://huggingface.co/facebook/xmod-base/resolve/main/config.json''', '''facebook/xmod-large-prenorm''': '''https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json''', '''facebook/xmod-base-13-125k''': '''https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json''', '''facebook/xmod-base-30-125k''': '''https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json''', '''facebook/xmod-base-30-195k''': '''https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json''', '''facebook/xmod-base-60-125k''': '''https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json''', '''facebook/xmod-base-60-265k''': '''https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json''', '''facebook/xmod-base-75-125k''': '''https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json''', '''facebook/xmod-base-75-269k''': '''https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json''', } class _A( __A ): """simple docstring""" UpperCamelCase : Union[str, Any] = '''xmod''' def __init__( self , _A=30522 , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=2 , _A=0.0_2 , _A=1e-1_2 , _A=1 , _A=0 , _A=2 , _A="absolute" , _A=True , _A=None , _A=False , _A=2 , _A=False , _A=True , _A=True , _A=("en_XX",) , _A=None , **_A , ): super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A ) __A : Optional[int] = vocab_size __A : str = hidden_size __A : Optional[int] = num_hidden_layers __A : List[Any] = num_attention_heads __A : Optional[int] = hidden_act __A : Dict = intermediate_size __A : Dict = hidden_dropout_prob __A : Tuple = attention_probs_dropout_prob __A : str = max_position_embeddings __A : Union[str, Any] = type_vocab_size __A : List[Any] = initializer_range __A : Dict = layer_norm_eps __A : Any = position_embedding_type __A : List[Any] = use_cache __A : List[str] = classifier_dropout __A : Dict = pre_norm __A : List[Any] = adapter_reduction_factor __A : List[str] = adapter_layer_norm __A : Tuple = adapter_reuse_layer_norm __A : Dict = ln_before_adapter __A : Optional[Any] = list(_A ) __A : Union[str, Any] = default_language class _A( __A ): """simple docstring""" @property def UpperCAmelCase_ ( self ): if self.task == "multiple-choice": __A : Any = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __A : Optional[Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
708
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def _SCREAMING_SNAKE_CASE ( ) -> None: print('Making key files...' ) make_key_files('rsa' , 10_24 ) print('Key files generation successful.' ) def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]: print('Generating prime p...' ) __A : Optional[Any] = rabinMiller.generate_large_prime(a ) print('Generating prime q...' ) __A : Union[str, Any] = rabinMiller.generate_large_prime(a ) __A : Tuple = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...' ) while True: __A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1: break print('Calculating d that is mod inverse of e...' ) __A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) ) __A : Dict = (n, e) __A : Dict = (n, d) return (public_key, private_key) def _SCREAMING_SNAKE_CASE ( a , a ) -> 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() __A , __A : Optional[int] = generate_key(a ) 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()
77
0
from math import factorial, radians def _SCREAMING_SNAKE_CASE ( a , a = 18 , a = 10 ) -> List[str]: __A : Optional[int] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians __A : str = radians(__lowerCAmelCase ) __A : Dict = angle_in_radians __A : int = 3 __A : Dict = -1 for _ in range(__lowerCAmelCase ): result += (b * (angle_in_radians**a)) / factorial(__lowerCAmelCase ) __A : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": __import__('''doctest''').testmod()
709
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ProphetNetTokenizer UpperCamelCase : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() __A : Any = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = 'UNwant\u00E9d,running' __A : List[str] = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class(self.vocab_file ) __A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase_ ( self ): __A : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCAmelCase_ ( self ): __A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __A : Optional[int] = {} for i, token in enumerate(_A ): __A : Tuple = i __A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __A : str = tokenizer(_A , padding=_A , return_tensors='pt' ) self.assertIsInstance(_A , _A ) __A : List[str] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A ) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A ) __A : str = tokenizer.build_inputs_with_special_tokens(_A ) __A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
77
0
import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings UpperCAmelCase__ : Optional[Any] = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__ ) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : bool = field(default=snake_case__ , metadata={'''help''': '''Whether to use SortishSampler or not.'''} ) UpperCamelCase : bool = field( default=snake_case__ , metadata={'''help''': '''Whether to use generate to calculate generative metrics (ROUGE, BLEU).'''} ) UpperCamelCase : Optional[int] = field( default=snake_case__ , metadata={ '''help''': ( '''The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default ''' '''to the `max_length` value of the model configuration.''' ) } , ) UpperCamelCase : Optional[int] = field( default=snake_case__ , metadata={ '''help''': ( '''The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default ''' '''to the `num_beams` value of the model configuration.''' ) } , ) UpperCamelCase : Optional[Union[str, Path, GenerationConfig]] = field( default=snake_case__ , metadata={ '''help''': '''Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.''' } , ) def UpperCAmelCase_ ( self ): __A : Any = super().to_dict() for k, v in d.items(): if isinstance(UpperCamelCase_ , UpperCamelCase_ ): __A : Tuple = v.to_dict() return d
710
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Optional[int] = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } UpperCAmelCase : List[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = BertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : Any = getattr(_A , normalizer_state.pop('type' ) ) __A : Union[str, Any] = do_lower_case __A : Optional[int] = strip_accents __A : List[Any] = tokenize_chinese_chars __A : int = normalizer_class(**_A ) __A : Union[str, Any] = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : Tuple = [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 UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[Any] = [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : int = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
0
from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Optional[Any] = DistilBertTokenizer UpperCamelCase : Optional[int] = DistilBertTokenizerFast UpperCamelCase : Dict = True @slow def UpperCAmelCase_ ( self ): __A : int = DistilBertTokenizer.from_pretrained('distilbert-base-uncased' ) __A : str = tokenizer.encode('sequence builders' , add_special_tokens=__A ) __A : Union[str, Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=__A ) __A : List[str] = tokenizer.build_inputs_with_special_tokens(__A ) __A : Any = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
711
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 UpperCAmelCase_ ( self ): debug_launcher(test_script.main ) def UpperCAmelCase_ ( self ): debug_launcher(test_ops.main )
77
0
from math import sqrt def _SCREAMING_SNAKE_CASE ( a ) -> 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(sqrt(__lowerCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _SCREAMING_SNAKE_CASE ( a = 1_00_01 ) -> int: __A : Dict = 0 __A : Tuple = 1 while count != nth and number < 3: number += 1 if is_prime(__lowerCAmelCase ): count += 1 while count != nth: number += 2 if is_prime(__lowerCAmelCase ): count += 1 return number if __name__ == "__main__": print(F"""{solution() = }""")
712
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Tuple = tempfile.mkdtemp() # fmt: off __A : Union[str, Any] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Dict = dict(zip(_A , range(len(_A ) ) ) ) __A : int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : Optional[Any] = {'unk_token': '<unk>'} __A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : Union[str, Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : List[str] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[str] = self.get_tokenizer() __A : Dict = self.get_rust_tokenizer() __A : Optional[Any] = self.get_image_processor() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Any = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : int = self.get_image_processor(do_normalize=_A ) __A : int = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : List[Any] = self.prepare_image_inputs() __A : Any = image_processor(_A , return_tensors='np' ) __A : Tuple = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_image_processor() __A : int = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = 'lower newer' __A : Any = processor(text=_A , return_tensors='np' ) __A : Dict = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Tuple = 'lower newer' __A : Union[str, Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[int] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Any = ['cat', 'nasa badge'] __A : List[Any] = processor(text=_A ) __A : Dict = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : int = [['cat', 'nasa badge'], ['person']] __A : str = processor(text=_A ) __A : int = 16 __A : Optional[int] = len(_A ) __A : int = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : int = 'google/owlvit-base-patch32' __A : List[str] = OwlViTProcessor.from_pretrained(_A ) __A : Tuple = ['cat', 'nasa badge'] __A : Dict = processor(text=_A ) __A : Tuple = 16 __A : str = inputs['input_ids'] __A : str = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Dict = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = self.prepare_image_inputs() __A : Tuple = self.prepare_image_inputs() __A : Any = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Union[str, Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
77
0
from collections import defaultdict from math import gcd def _SCREAMING_SNAKE_CASE ( a = 1_50_00_00 ) -> int: __A : Union[str, Any] = defaultdict(__UpperCAmelCase ) __A : Union[str, Any] = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1 , __UpperCAmelCase , 2 ): if gcd(__UpperCAmelCase , __UpperCAmelCase ) > 1: continue __A : int = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(__UpperCAmelCase , limit + 1 , __UpperCAmelCase ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F"""{solution() = }""")
713
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase : Union[str, Any] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Tuple: for attribute in key.split('.' ): __A : Dict = getattr(a , a ) if weight_type is not None: __A : Any = getattr(a , a ).shape else: __A : Any = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __A : Union[str, Any] = value elif weight_type == "weight_g": __A : Dict = value elif weight_type == "weight_v": __A : Optional[int] = value elif weight_type == "bias": __A : int = value elif weight_type == "running_mean": __A : Union[str, Any] = value elif weight_type == "running_var": __A : Union[str, Any] = value elif weight_type == "num_batches_tracked": __A : Any = value elif weight_type == "inv_freq": __A : Optional[Any] = value else: __A : int = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]: __A : Any = [] __A : Optional[int] = fairseq_model.state_dict() __A : Union[str, Any] = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __A : int = False if "conv_layers" in name: load_conv_layer( a , a , a , a , hf_model.config.feat_extract_norm == 'group' , ) __A : Optional[int] = True else: for key, mapped_key in MAPPING.items(): __A : Any = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __A : Optional[Any] = True if "*" in mapped_key: __A : str = name.split(a )[0].split('.' )[-2] __A : int = mapped_key.replace('*' , a ) if "pos_bias_u" in name: __A : Optional[int] = None elif "pos_bias_v" in name: __A : Dict = None elif "weight_g" in name: __A : Optional[Any] = 'weight_g' elif "weight_v" in name: __A : Dict = 'weight_v' elif "bias" in name: __A : Tuple = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __A : int = 'weight' elif "running_mean" in name: __A : str = 'running_mean' elif "inv_freq" in name: __A : List[Any] = 'inv_freq' elif "running_var" in name: __A : Union[str, Any] = 'running_var' elif "num_batches_tracked" in name: __A : Optional[Any] = 'num_batches_tracked' else: __A : List[str] = None set_recursively(a , a , a , a , a ) continue if not is_used: unused_weights.append(a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Any: __A : str = full_name.split('conv_layers.' )[-1] __A : str = name.split('.' ) __A : Dict = int(items[0] ) __A : Any = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) __A : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) __A : List[str] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a ) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a=None , a=None , a=True ) -> Any: if config_path is not None: __A : Tuple = WavaVecaConformerConfig.from_pretrained(a , hidden_act='swish' ) else: __A : Optional[Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: __A : Dict = 'rotary' if is_finetuned: if dict_path: __A : Dict = Dictionary.load(a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __A : int = target_dict.pad_index __A : List[Any] = target_dict.bos_index __A : Any = target_dict.eos_index __A : Dict = len(target_dict.symbols ) __A : Optional[Any] = os.path.join(a , 'vocab.json' ) if not os.path.isdir(a ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(a ) ) return os.makedirs(a , exist_ok=a ) __A : List[str] = target_dict.indices # fairseq has the <pad> and <s> switched __A : int = 0 __A : Optional[Any] = 1 with open(a , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(a , a ) __A : Optional[Any] = WavaVecaCTCTokenizer( a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=a , ) __A : Tuple = True if config.feat_extract_norm == 'layer' else False __A : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=a , return_attention_mask=a , ) __A : Optional[int] = WavaVecaProcessor(feature_extractor=a , tokenizer=a ) processor.save_pretrained(a ) __A : List[Any] = WavaVecaConformerForCTC(a ) else: __A : List[Any] = WavaVecaConformerForPreTraining(a ) if is_finetuned: __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: __A : Optional[Any] = argparse.Namespace(task='audio_pretraining' ) __A : str = fairseq.tasks.setup_task(a ) __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=a ) __A : Tuple = model[0].eval() recursively_load_weights(a , a , not is_finetuned ) hf_wavavec.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) UpperCAmelCase : List[str] = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
77
0
class _A: """simple docstring""" def __init__( self , _A , _A=None , _A=None ): __A : str = data __A : Any = previous __A : Optional[int] = next_node def __str__( self ): return F"""{self.data}""" def UpperCAmelCase_ ( self ): return self.data def UpperCAmelCase_ ( self ): return self.next def UpperCAmelCase_ ( self ): return self.previous class _A: """simple docstring""" def __init__( self , _A ): __A : List[str] = head def __iter__( self ): return self def UpperCAmelCase_ ( self ): if not self.current: raise StopIteration else: __A : Union[str, Any] = self.current.get_data() __A : Tuple = self.current.get_next() return value class _A: """simple docstring""" def __init__( self ): __A : int = None # First node in list __A : Optional[int] = None # Last node in list def __str__( self ): __A : Union[str, Any] = self.head __A : Dict = [] while current is not None: nodes.append(current.get_data() ) __A : List[str] = current.get_next() return " ".join(str(_UpperCAmelCase ) for node in nodes ) def __contains__( self , _A ): __A : Dict = self.head while current: if current.get_data() == value: return True __A : str = current.get_next() return False def __iter__( self ): return LinkedListIterator(self.head ) def UpperCAmelCase_ ( self ): if self.head: return self.head.get_data() return None def UpperCAmelCase_ ( self ): if self.tail: return self.tail.get_data() return None def UpperCAmelCase_ ( self , _A ): if self.head is None: __A : int = node __A : Union[str, Any] = node else: self.insert_before_node(self.head , _UpperCAmelCase ) def UpperCAmelCase_ ( self , _A ): if self.head is None: self.set_head(_UpperCAmelCase ) else: self.insert_after_node(self.tail , _UpperCAmelCase ) def UpperCAmelCase_ ( self , _A ): __A : Optional[int] = Node(_UpperCAmelCase ) if self.head is None: self.set_head(_UpperCAmelCase ) else: self.set_tail(_UpperCAmelCase ) def UpperCAmelCase_ ( self , _A , _A ): __A : str = node __A : List[Any] = node.previous if node.get_previous() is None: __A : List[str] = node_to_insert else: __A : Optional[int] = node_to_insert __A : List[Any] = node_to_insert def UpperCAmelCase_ ( self , _A , _A ): __A : Union[str, Any] = node __A : Optional[int] = node.next if node.get_next() is None: __A : str = node_to_insert else: __A : Tuple = node_to_insert __A : Optional[int] = node_to_insert def UpperCAmelCase_ ( self , _A , _A ): __A : Optional[Any] = 1 __A : Any = Node(_UpperCAmelCase ) __A : Tuple = self.head while node: if current_position == position: self.insert_before_node(_UpperCAmelCase , _UpperCAmelCase ) return current_position += 1 __A : Optional[Any] = node.next self.insert_after_node(self.tail , _UpperCAmelCase ) def UpperCAmelCase_ ( self , _A ): __A : Tuple = self.head while node: if node.get_data() == item: return node __A : Tuple = node.get_next() raise Exception('Node not found' ) def UpperCAmelCase_ ( self , _A ): if (node := self.get_node(_UpperCAmelCase )) is not None: if node == self.head: __A : int = self.head.get_next() if node == self.tail: __A : Union[str, Any] = self.tail.get_previous() self.remove_node_pointers(_UpperCAmelCase ) @staticmethod def UpperCAmelCase_ ( _A ): if node.get_next(): __A : Any = node.previous if node.get_previous(): __A : str = node.next __A : List[Any] = None __A : Any = None def UpperCAmelCase_ ( self ): return self.head is None def _SCREAMING_SNAKE_CASE ( ) -> Dict: pass if __name__ == "__main__": import doctest doctest.testmod()
714
from abc import ABC, abstractmethod from argparse import ArgumentParser class _A( snake_case__ ): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( _A ): raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self ): raise NotImplementedError()
77
0
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[Any] = get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model''') @require_sentencepiece @require_tokenizers class _A( __lowerCAmelCase , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[Any] = GPTSwaTokenizer UpperCamelCase : Tuple = False UpperCamelCase : Any = True UpperCamelCase : str = False def UpperCAmelCase_ ( self ): super().setUp() # We have a SentencePiece fixture for testing __A : Dict = GPTSwaTokenizer(_UpperCamelCase , eos_token='<unk>' , bos_token='<unk>' , pad_token='<unk>' ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self , _A ): __A : Optional[int] = """This is a test""" __A : Any = """This is a test""" return input_text, output_text def UpperCAmelCase_ ( self ): __A : List[str] = """<s>""" __A : str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCamelCase ) , _UpperCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCamelCase ) , _UpperCamelCase ) def UpperCAmelCase_ ( self ): __A : Tuple = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , 'j' ) self.assertEqual(len(_UpperCamelCase ) , 2000 ) def UpperCAmelCase_ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 2000 ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = GPTSwaTokenizer(_UpperCamelCase ) __A : Optional[int] = tokenizer.tokenize('This is a test' ) self.assertListEqual(_UpperCamelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCamelCase ) , [465, 287, 265, 631, 842] ) __A : Union[str, Any] = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) # fmt: off self.assertListEqual( _UpperCamelCase , ['▁I', '▁was', '▁bor', 'n', '▁in', '▁', '<0x39>', '2', '0', '0', '0', ',', '▁and', '▁this', '▁is', '▁f', 'al', 's', '<0xC3>', '<0xA9>', '.'] , ) # fmt: on __A : Any = tokenizer.convert_tokens_to_ids(_UpperCamelCase ) self.assertListEqual( _UpperCamelCase , [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , ) __A : List[Any] = tokenizer.convert_ids_to_tokens(_UpperCamelCase ) # fmt: off self.assertListEqual( _UpperCamelCase , ['▁I', '▁was', '▁bor', 'n', '▁in', '▁', '<0x39>', '2', '0', '0', '0', ',', '▁and', '▁this', '▁is', '▁f', 'al', 's', '<0xC3>', '<0xA9>', '.'] ) # fmt: on def UpperCAmelCase_ ( self ): __A : List[str] = GPTSwaTokenizer(_UpperCamelCase ) __A : Optional[int] = ["""This is a test""", """I was born in 92000, and this is falsé."""] __A : Optional[Any] = [ [465, 287, 265, 631, 842], [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(_UpperCamelCase , _UpperCamelCase ): self.assertListEqual(tokenizer.encode_fast(_UpperCamelCase ) , _UpperCamelCase ) # Test that decode_fast returns the input text for text, token_ids in zip(_UpperCamelCase , _UpperCamelCase ): self.assertEqual(tokenizer.decode_fast(_UpperCamelCase ) , _UpperCamelCase ) @slow def UpperCAmelCase_ ( self ): __A : Dict = [ """<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')""", """Hey there, how are you doing this fine day?""", """This is a text with a trailing spaces followed by a dot .""", """Häj sväjs lillebrör! =)""", """Det är inget fel på Mr. Cool""", ] # fmt: off __A : List[str] = {"""input_ids""": [[63423, 5, 6811, 14954, 282, 816, 3821, 63466, 63425, 63462, 18, 63978, 678, 301, 1320, 63423, 63455, 63458, 18, 63982, 4246, 3940, 1901, 47789, 5547, 18994], [19630, 1100, 63446, 1342, 633, 544, 4488, 593, 5102, 2416, 63495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 58593, 22413, 9106, 546, 268, 33213, 63979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55130, 63450, 924, 63449, 2249, 4062, 1558, 318, 63504, 21498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 63443, 26801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """token_type_ids""": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [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], [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]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=_UpperCamelCase , model_name='AI-Sweden/gpt-sw3-126m' , sequences=_UpperCamelCase , )
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
0
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Dict: __A : Optional[Any] = [] __A : Tuple = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) __A : str = result + left + right return input_list def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: if len(_lowerCamelCase ) <= 1: return input_list __A : Dict = list(_lowerCamelCase ) # iteration for two-way merging __A : str = 2 while p <= len(_lowerCamelCase ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(_lowerCamelCase ) , _lowerCamelCase ): __A : Any = i __A : Optional[int] = i + p - 1 __A : Optional[Any] = (low + high + 1) // 2 __A : int = merge(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # final merge of last two parts if p * 2 >= len(_lowerCamelCase ): __A : List[Any] = i __A : int = merge(_lowerCamelCase , 0 , _lowerCamelCase , len(_lowerCamelCase ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCAmelCase : int = input('''Enter numbers separated by a comma:\n''').strip() if user_input == "": UpperCAmelCase : List[str] = [] else: UpperCAmelCase : Tuple = [int(item.strip()) for item in user_input.split(''',''')] print(iter_merge_sort(unsorted))
716
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = ShapEPipeline UpperCamelCase : str = ['''prompt'''] UpperCamelCase : Tuple = ['''prompt'''] UpperCamelCase : Optional[int] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] UpperCamelCase : int = False @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self ): return 8 @property def UpperCAmelCase_ ( self ): __A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_A ) @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : int = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __A : Optional[Any] = PriorTransformer(**_A ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : List[str] = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __A : List[Any] = ShapERenderer(**_A ) return model def UpperCAmelCase_ ( self ): __A : List[str] = self.dummy_prior __A : Optional[int] = self.dummy_text_encoder __A : List[Any] = self.dummy_tokenizer __A : str = self.dummy_renderer __A : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=_A , clip_sample=_A , clip_sample_range=1.0 , ) __A : Any = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): if str(_A ).startswith('mps' ): __A : List[Any] = torch.manual_seed(_A ) else: __A : Dict = torch.Generator(device=_A ).manual_seed(_A ) __A : int = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def UpperCAmelCase_ ( self ): __A : Tuple = 'cpu' __A : Any = self.get_dummy_components() __A : Tuple = self.pipeline_class(**_A ) __A : List[str] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Tuple = pipe(**self.get_dummy_inputs(_A ) ) __A : int = output.images[0] __A : str = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __A : Any = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCAmelCase_ ( self ): __A : List[str] = torch_device == 'cpu' __A : Any = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_A , relax_max_difference=_A , ) def UpperCAmelCase_ ( self ): __A : Any = self.get_dummy_components() __A : Any = self.pipeline_class(**_A ) __A : Dict = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Any = 1 __A : Dict = 2 __A : Tuple = self.get_dummy_inputs(_A ) for key in inputs.keys(): if key in self.batch_params: __A : Optional[int] = batch_size * [inputs[key]] __A : Optional[int] = pipe(**_A , num_images_per_prompt=_A )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __A : Dict = ShapEPipeline.from_pretrained('openai/shap-e' ) __A : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : str = torch.Generator(device=_A ).manual_seed(0 ) __A : Tuple = pipe( 'a shark' , generator=_A , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_A , _A )
77
0
'''simple docstring''' import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class _A: """simple docstring""" def __init__( self , _A=2 , _A=3 , _A=64 , _A=None ): __A : List[Any] = np.random.default_rng(__lowerCamelCase ) __A : str = length __A : List[Any] = rng.normal(size=(length,) ).astype(np.floataa ) __A : Tuple = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ): return self.length def __getitem__( self , _A ): return {"x": self.x[i], "y": self.y[i]} class _A( torch.nn.Module ): """simple docstring""" def __init__( self , _A=0 , _A=0 , _A=False ): super().__init__() __A : Union[str, Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A : List[Any] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A : int = True def UpperCAmelCase_ ( self , _A=None ): if self.first_batch: print(F"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}""" ) __A : Tuple = False return x * self.a[0] + self.b[0] class _A( torch.nn.Module ): """simple docstring""" def __init__( self , _A=0 , _A=0 , _A=False ): super().__init__() __A : Tuple = torch.nn.Parameter(torch.tensor(__lowerCamelCase ).float() ) __A : Optional[int] = torch.nn.Parameter(torch.tensor(__lowerCamelCase ).float() ) __A : Union[str, Any] = True def UpperCAmelCase_ ( self , _A=None ): if self.first_batch: print(F"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}""" ) __A : List[str] = False return x * self.a + self.b def _SCREAMING_SNAKE_CASE ( a , a = 16 ) -> Any: from datasets import load_dataset from transformers import AutoTokenizer __A : int = AutoTokenizer.from_pretrained('bert-base-cased' ) __A : Any = {"train": "tests/test_samples/MRPC/train.csv", "validation": "tests/test_samples/MRPC/dev.csv"} __A : Tuple = load_dataset('csv' , data_files=_lowerCamelCase ) __A : Any = datasets["train"].unique('label' ) __A : List[str] = {v: i for i, v in enumerate(_lowerCamelCase )} def tokenize_function(a ): # max_length=None => use the model max length (it's actually the default) __A : Optional[Any] = tokenizer( examples['sentence1'] , examples['sentence2'] , truncation=_lowerCamelCase , max_length=_lowerCamelCase , padding='max_length' ) if "label" in examples: __A : int = [label_to_id[l] for l in examples["label"]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __A : List[str] = datasets.map( _lowerCamelCase , batched=_lowerCamelCase , remove_columns=['sentence1', 'sentence2', 'label'] , ) def collate_fn(a ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(_lowerCamelCase , padding='max_length' , max_length=1_28 , return_tensors='pt' ) return tokenizer.pad(_lowerCamelCase , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. __A : Tuple = DataLoader(tokenized_datasets['train'] , shuffle=_lowerCamelCase , collate_fn=_lowerCamelCase , batch_size=2 ) __A : Tuple = DataLoader(tokenized_datasets['validation'] , shuffle=_lowerCamelCase , collate_fn=_lowerCamelCase , batch_size=1 ) return train_dataloader, eval_dataloader
717
from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if len(a ) != 2 or len(a[0] ) != 2 or len(a ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __A : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> str: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a ) -> tuple[list, list, list, list]: if len(a ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __A : str = len(a ) __A : List[Any] = matrix_length // 2 __A : List[str] = [[a[i][j] for j in range(a , a )] for i in range(a )] __A : Dict = [ [a[i][j] for j in range(a , a )] for i in range(a , a ) ] __A : int = [[a[i][j] for j in range(a )] for i in range(a )] __A : Any = [[a[i][j] for j in range(a )] for i in range(a , a )] return top_left, top_right, bot_left, bot_right def _SCREAMING_SNAKE_CASE ( a ) -> tuple[int, int]: return len(a ), len(matrix[0] ) def _SCREAMING_SNAKE_CASE ( a ) -> None: print('\n'.join(str(a ) for line in matrix ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a ) == (2, 2): return default_matrix_multiplication(a , a ) __A , __A , __A , __A : str = split_matrix(a ) __A , __A , __A , __A : List[Any] = split_matrix(a ) __A : Any = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Tuple = actual_strassen(matrix_addition(a , a ) , a ) __A : List[str] = actual_strassen(matrix_addition(a , a ) , a ) __A : Optional[int] = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Any = actual_strassen(matrix_addition(a , a ) , matrix_addition(a , a ) ) __A : Any = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = matrix_addition(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) __A : Union[str, Any] = matrix_addition(a , a ) __A : str = matrix_addition(a , a ) __A : Dict = matrix_subtraction(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) # construct the new matrix from our 4 quadrants __A : List[Any] = [] for i in range(len(a ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(a ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a )[1] != matrix_dimensions(a )[0]: __A : Dict = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"""Matrix A: {matrixa}\n""" F"""Matrix B: {matrixa}""" ) raise Exception(a ) __A : int = matrix_dimensions(a ) __A : Any = matrix_dimensions(a ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __A : List[Any] = max(*a , *a ) __A : Optional[Any] = int(math.pow(2 , math.ceil(math.loga(a ) ) ) ) __A : Union[str, Any] = matrixa __A : Optional[int] = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __A : str = actual_strassen(a , a ) # Removing the additional zeros for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] UpperCAmelCase : Optional[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
77
0
from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) UpperCAmelCase : int = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class _A( _UpperCAmelCase ): """simple docstring""" @staticmethod def UpperCAmelCase_ ( _A ): __A : str = parser.add_parser( 'convert' , help='CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.' , ) train_parser.add_argument('--model_type' , type=lowerCamelCase_ , required=lowerCamelCase_ , help='Model\'s type.' ) train_parser.add_argument( '--tf_checkpoint' , type=lowerCamelCase_ , required=lowerCamelCase_ , help='TensorFlow checkpoint path or folder.' ) train_parser.add_argument( '--pytorch_dump_output' , type=lowerCamelCase_ , required=lowerCamelCase_ , help='Path to the PyTorch saved model output.' ) train_parser.add_argument('--config' , type=lowerCamelCase_ , default='' , help='Configuration file path or folder.' ) train_parser.add_argument( '--finetuning_task_name' , type=lowerCamelCase_ , default=lowerCamelCase_ , help='Optional fine-tuning task name if the TF model was a finetuned model.' , ) train_parser.set_defaults(func=lowerCamelCase_ ) def __init__( self , _A , _A , _A , _A , _A , *_A , ): __A : Optional[Any] = logging.get_logger('transformers-cli/converting' ) self._logger.info(F"""Loading model {model_type}""" ) __A : Optional[Any] = model_type __A : List[Any] = tf_checkpoint __A : List[str] = pytorch_dump_output __A : Optional[int] = config __A : str = finetuning_task_name def UpperCAmelCase_ ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase_ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase_ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase_ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(lowerCamelCase_ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase_ ) if "ckpt" in self._tf_checkpoint.lower(): __A : Dict = self._tf_checkpoint __A : Tuple = '''''' else: __A : List[Any] = self._tf_checkpoint __A : Optional[int] = '''''' convert_transfo_xl_checkpoint_to_pytorch( lowerCamelCase_ , self._config , self._pytorch_dump_output , lowerCamelCase_ ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase_ ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase_ ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]' )
718
def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : List[str] = [] __A : Tuple = [] __A : Union[str, Any] = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, } # Priority of each operator __A : List[str] = len(a ) if (len(a ) > 7) else 7 # Print table header for output print( 'Symbol'.center(8 ) , 'Stack'.center(a ) , 'Postfix'.center(a ) , sep=' | ' , ) print('-' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(a ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(a ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(a ) == 0: stack.append(a ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(a ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(a ) # push x to stack print( x.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format while len(a ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ' '.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format return "".join(a ) # return Postfix as str def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : List[Any] = list(infix[::-1] ) # reverse the infix equation for i in range(len(a ) ): if infix[i] == "(": __A : List[str] = ')' # change "(" to ")" elif infix[i] == ")": __A : Any = '(' # change ")" to "(" return (infix_2_postfix(''.join(a ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": UpperCAmelCase : List[str] = input('''\nEnter an Infix Equation = ''') # Input an Infix equation UpperCAmelCase : Union[str, Any] = ''''''.join(Infix.split()) # Remove spaces from the input print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
77
0
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class _A: """simple docstring""" UpperCamelCase : torch.Tensor # [batch_size x 3] UpperCamelCase : torch.Tensor # [batch_size x 3] UpperCamelCase : torch.Tensor # [batch_size x 3] UpperCamelCase : torch.Tensor # [batch_size x 3] UpperCamelCase : int UpperCamelCase : int UpperCamelCase : float UpperCamelCase : float UpperCamelCase : Tuple[int] def UpperCAmelCase_ ( self ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def UpperCAmelCase_ ( self ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def UpperCAmelCase_ ( self ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def UpperCAmelCase_ ( self ): __A : int = torch.arange(self.height * self.width ) __A : Union[str, Any] = torch.stack( [ pixel_indices % self.width, torch.div(__UpperCamelCase , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def UpperCAmelCase_ ( self ): __A , *__A : Optional[int] = self.shape __A : List[str] = int(np.prod(__UpperCamelCase ) ) __A : str = self.get_image_coords() __A : Optional[Any] = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) __A : str = self.get_camera_rays(__UpperCamelCase ) __A : Union[str, Any] = rays.view(__UpperCamelCase , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def UpperCAmelCase_ ( self , _A ): __A , *__A , __A : Any = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] __A : Tuple = coords.view(__UpperCamelCase , -1 , 2 ) __A : Union[str, Any] = self.resolution() __A : Any = self.fov() __A : List[str] = (flat.float() / (res - 1)) * 2 - 1 __A : Optional[int] = fracs * torch.tan(fov / 2 ) __A : List[str] = fracs.view(__UpperCamelCase , -1 , 2 ) __A : Dict = ( self.z.view(__UpperCamelCase , 1 , 3 ) + self.x.view(__UpperCamelCase , 1 , 3 ) * fracs[:, :, :1] + self.y.view(__UpperCamelCase , 1 , 3 ) * fracs[:, :, 1:] ) __A : Tuple = directions / directions.norm(dim=-1 , keepdim=__UpperCamelCase ) __A : Union[str, Any] = torch.stack( [ torch.broadcast_to(self.origin.view(__UpperCamelCase , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(__UpperCamelCase , *__UpperCamelCase , 2 , 3 ) def UpperCAmelCase_ ( self , _A , _A ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=__UpperCamelCase , height=__UpperCamelCase , x_fov=self.x_fov , y_fov=self.y_fov , ) def _SCREAMING_SNAKE_CASE ( a ) -> DifferentiableProjectiveCamera: __A : Optional[int] = [] __A : Union[str, Any] = [] __A : Optional[Any] = [] __A : List[str] = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): __A : Union[str, Any] = np.array([np.sin(_A ), np.cos(_A ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) __A : int = -z * 4 __A : Union[str, Any] = np.array([np.cos(_A ), -np.sin(_A ), 0.0] ) __A : int = np.cross(_A , _A ) origins.append(_A ) xs.append(_A ) ys.append(_A ) zs.append(_A ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(_A , axis=0 ) ).float() , x=torch.from_numpy(np.stack(_A , axis=0 ) ).float() , y=torch.from_numpy(np.stack(_A , axis=0 ) ).float() , z=torch.from_numpy(np.stack(_A , axis=0 ) ).float() , width=_A , height=_A , x_fov=0.7 , y_fov=0.7 , shape=(1, len(_A )) , )
719
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : Tuple = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json''' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase : int = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = '''mask2former''' UpperCamelCase : Any = ['''swin'''] UpperCamelCase : Union[str, Any] = {'''hidden_size''': '''hidden_dim'''} def __init__( self , _A = None , _A = 256 , _A = 256 , _A = 256 , _A = 1024 , _A = "relu" , _A = 6 , _A = 10 , _A = 8 , _A = 0.0 , _A = 2048 , _A = False , _A = False , _A = 4 , _A = 255 , _A = 100 , _A = 0.1 , _A = 2.0 , _A = 5.0 , _A = 5.0 , _A = 12544 , _A = 3.0 , _A = 0.7_5 , _A = 0.0_2 , _A = 1.0 , _A = True , _A = [4, 8, 16, 32] , _A = None , **_A , ): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) __A : Optional[int] = CONFIG_MAPPING['swin']( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=_A , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(_A , _A ): __A : Dict = backbone_config.pop('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[str] = config_class.from_dict(_A ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) __A : Optional[int] = backbone_config __A : Optional[Any] = feature_size __A : Any = mask_feature_size __A : Optional[Any] = hidden_dim __A : Union[str, Any] = encoder_feedforward_dim __A : Optional[Any] = activation_function __A : List[Any] = encoder_layers __A : Union[str, Any] = decoder_layers __A : Dict = num_attention_heads __A : Tuple = dropout __A : Dict = dim_feedforward __A : Tuple = pre_norm __A : Dict = enforce_input_projection __A : Optional[int] = common_stride __A : Optional[Any] = ignore_value __A : str = num_queries __A : List[Any] = no_object_weight __A : List[str] = class_weight __A : List[Any] = mask_weight __A : List[Any] = dice_weight __A : Tuple = train_num_points __A : Optional[Any] = oversample_ratio __A : Union[str, Any] = importance_sample_ratio __A : Union[str, Any] = init_std __A : int = init_xavier_std __A : Union[str, Any] = use_auxiliary_loss __A : Union[str, Any] = feature_strides __A : List[Any] = output_auxiliary_logits __A : Optional[Any] = decoder_layers super().__init__(**_A ) @classmethod def UpperCAmelCase_ ( cls , _A , **_A ): return cls( backbone_config=_A , **_A , ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = copy.deepcopy(self.__dict__ ) __A : List[Any] = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output
77
0
import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets UpperCAmelCase : List[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase : str = """\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } """ UpperCAmelCase : int = """\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project's README at https://github.com/google-research/bleurt#readme for more information. """ UpperCAmelCase : Dict = """ BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: 'scores': List of scores. Examples: >>> predictions = [\"hello there\", \"general kenobi\"] >>> references = [\"hello there\", \"general kenobi\"] >>> bleurt = datasets.load_metric(\"bleurt\") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results[\"scores\"]]) [1.03, 1.04] """ UpperCAmelCase : Optional[Any] = { """bleurt-tiny-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip""", """bleurt-tiny-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip""", """bleurt-base-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip""", """bleurt-base-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip""", """bleurt-large-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip""", """bleurt-large-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip""", """BLEURT-20-D3""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip""", """BLEURT-20-D6""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip""", """BLEURT-20-D12""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip""", """BLEURT-20""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip""", } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='https://github.com/google-research/bleurt' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/google-research/bleurt'] , reference_urls=['https://github.com/google-research/bleurt', 'https://arxiv.org/abs/2004.04696'] , ) def UpperCAmelCase_ ( self , _A ): # check that config name specifies a valid BLEURT model if self.config_name == "default": logger.warning( 'Using default BLEURT-Base checkpoint for sequence maximum length 128. ' 'You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').' ) __A : Any = 'bleurt-base-128' if self.config_name.lower() in CHECKPOINT_URLS: __A : Union[str, Any] = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: __A : Tuple = self.config_name.upper() else: raise KeyError( F"""{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}""" ) # download the model checkpoint specified by self.config_name and set up the scorer __A : Dict = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) __A : int = score.BleurtScorer(os.path.join(snake_case_ , snake_case_ ) ) def UpperCAmelCase_ ( self , _A , _A ): __A : int = self.scorer.score(references=snake_case_ , candidates=snake_case_ ) return {"scores": scores}
720
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : str = '''conditional_detr''' UpperCamelCase : int = ['''past_key_values'''] UpperCamelCase : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , _A=True , _A=None , _A=3 , _A=300 , _A=6 , _A=2048 , _A=8 , _A=6 , _A=2048 , _A=8 , _A=0.0 , _A=0.0 , _A=True , _A="relu" , _A=256 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1.0 , _A=False , _A="sine" , _A="resnet50" , _A=True , _A=False , _A=2 , _A=5 , _A=2 , _A=1 , _A=1 , _A=2 , _A=5 , _A=2 , _A=0.2_5 , **_A , ): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __A : List[str] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_A , _A ): __A : Tuple = backbone_config.get('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[Any] = config_class.from_dict(_A ) __A : Tuple = use_timm_backbone __A : List[str] = backbone_config __A : Dict = num_channels __A : int = num_queries __A : int = d_model __A : str = encoder_ffn_dim __A : List[str] = encoder_layers __A : Optional[Any] = encoder_attention_heads __A : Union[str, Any] = decoder_ffn_dim __A : List[Any] = decoder_layers __A : Optional[Any] = decoder_attention_heads __A : Any = dropout __A : Any = attention_dropout __A : int = activation_dropout __A : Optional[int] = activation_function __A : Union[str, Any] = init_std __A : Union[str, Any] = init_xavier_std __A : Optional[Any] = encoder_layerdrop __A : int = decoder_layerdrop __A : List[str] = encoder_layers __A : str = auxiliary_loss __A : Union[str, Any] = position_embedding_type __A : Optional[int] = backbone __A : List[str] = use_pretrained_backbone __A : List[Any] = dilation # Hungarian matcher __A : List[str] = class_cost __A : Optional[int] = bbox_cost __A : Dict = giou_cost # Loss coefficients __A : Optional[int] = mask_loss_coefficient __A : Union[str, Any] = dice_loss_coefficient __A : List[Any] = cls_loss_coefficient __A : Dict = bbox_loss_coefficient __A : Tuple = giou_loss_coefficient __A : Tuple = focal_alpha super().__init__(is_encoder_decoder=_A , **_A ) @property def UpperCAmelCase_ ( self ): return self.encoder_attention_heads @property def UpperCAmelCase_ ( self ): return self.d_model def UpperCAmelCase_ ( self ): __A : str = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __A : Dict = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = version.parse('''1.11''' ) @property def UpperCAmelCase_ ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def UpperCAmelCase_ ( self ): return 1e-5 @property def UpperCAmelCase_ ( self ): return 12
77
0
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Optional[Any]: __A : Dict = np.array([[1, item, train_mtch[i]] for i, item in enumerate(__UpperCamelCase )] ) __A : Dict = np.array(__UpperCamelCase ) __A : Any = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , __UpperCamelCase ) ) , x.transpose() ) , __UpperCamelCase ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Dict: __A : Union[str, Any] = (1, 2, 1) __A : Optional[Any] = (1, 1, 0, 7) __A : Tuple = SARIMAX( __UpperCamelCase , exog=__UpperCamelCase , order=__UpperCamelCase , seasonal_order=__UpperCamelCase ) __A : List[str] = model.fit(disp=__UpperCamelCase , maxiter=6_00 , method='nm' ) __A : Union[str, Any] = model_fit.predict(1 , len(__UpperCamelCase ) , exog=[test_match] ) return result[0] def _SCREAMING_SNAKE_CASE ( a , a , a ) -> List[str]: __A : str = SVR(kernel='rbf' , C=1 , gamma=0.1 , epsilon=0.1 ) regressor.fit(__UpperCamelCase , __UpperCamelCase ) __A : Tuple = regressor.predict(__UpperCamelCase ) return y_pred[0] def _SCREAMING_SNAKE_CASE ( a ) -> str: train_user.sort() __A : Optional[int] = np.percentile(__UpperCamelCase , 25 ) __A : List[str] = np.percentile(__UpperCamelCase , 75 ) __A : List[str] = qa - qa __A : Optional[int] = qa - (iqr * 0.1) return low_lim def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: __A : Any = 0 __A : str = 0 for i in list_vote: if i > actual_result: __A : Tuple = not_safe + 1 else: if abs(abs(__UpperCamelCase ) - abs(__UpperCamelCase ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) UpperCAmelCase : Optional[int] = [[1_82_31, 0.0, 1], [2_26_21, 1.0, 2], [1_56_75, 0.0, 3], [2_35_83, 1.0, 4]] UpperCAmelCase : Any = pd.DataFrame( data_input, columns=['''total_user''', '''total_even''', '''days'''] ) UpperCAmelCase : Tuple = Normalizer().fit_transform(data_input_df.values) # split data UpperCAmelCase : str = normalize_df[:, 2].tolist() UpperCAmelCase : Union[str, Any] = normalize_df[:, 0].tolist() UpperCAmelCase : Tuple = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) UpperCAmelCase : Tuple = normalize_df[:, [1, 2]].tolist() UpperCAmelCase : Union[str, Any] = x[: len(x) - 1] UpperCAmelCase : Union[str, Any] = x[len(x) - 1 :] # for linear regression & sarimax UpperCAmelCase : Any = total_date[: len(total_date) - 1] UpperCAmelCase : Optional[Any] = total_user[: len(total_user) - 1] UpperCAmelCase : int = total_match[: len(total_match) - 1] UpperCAmelCase : List[Any] = total_date[len(total_date) - 1 :] UpperCAmelCase : str = total_user[len(total_user) - 1 :] UpperCAmelCase : List[str] = total_match[len(total_match) - 1 :] # voting system with forecasting UpperCAmelCase : Optional[Any] = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data UpperCAmelCase : Dict = '''''' if data_safety_checker(res_vote, tst_user) else '''not ''' print('''Today\'s data is {not_str}safe.''')
721
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _A( nn.Module ): """simple docstring""" def __init__( self ): super().__init__() __A : List[str] = nn.Linear(3 , 4 ) __A : Optional[Any] = nn.BatchNormad(4 ) __A : List[Any] = nn.Linear(4 , 5 ) def UpperCAmelCase_ ( self , _A ): return self.lineara(self.batchnorm(self.lineara(_A ) ) ) class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Dict = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , model.state_dict() ) __A : str = os.path.join(_A , 'index.json' ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: __A : Optional[int] = os.path.join(_A , F"""{key}.dat""" ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on the fact weights are properly loaded def UpperCAmelCase_ ( self ): __A : Dict = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: __A : Tuple = torch.randn(2 , 3 , dtype=_A ) with TemporaryDirectory() as tmp_dir: __A : int = offload_weight(_A , 'weight' , _A , {} ) __A : Union[str, Any] = os.path.join(_A , 'weight.dat' ) self.assertTrue(os.path.isfile(_A ) ) self.assertDictEqual(_A , {'weight': {'shape': [2, 3], 'dtype': str(_A ).split('.' )[1]}} ) __A : List[str] = load_offloaded_weight(_A , index['weight'] ) self.assertTrue(torch.equal(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : int = ModelForTest() __A : Union[str, Any] = model.state_dict() __A : Optional[Any] = {k: v for k, v in state_dict.items() if 'linear2' not in k} __A : str = {k: v for k, v in state_dict.items() if 'linear2' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : List[str] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) __A : Union[str, Any] = {k: v for k, v in state_dict.items() if 'weight' in k} __A : List[Any] = {k: v for k, v in state_dict.items() if 'weight' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : Optional[int] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) # Duplicates are removed __A : str = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) def UpperCAmelCase_ ( self ): __A : Dict = {'a.1': 0, 'a.10': 1, 'a.2': 2} __A : str = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1': 0, 'a.2': 2} ) __A : Optional[Any] = {'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2} __A : Any = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1.a': 0, 'a.2.a': 2} )
77
0
'''simple docstring''' import unittest from transformers import 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 UpperCAmelCase_ ( *_A , **_A ): pass @is_pipeline_test @require_vision class _A( unittest.TestCase ): """simple docstring""" @require_torch def UpperCAmelCase_ ( self ): __A : Dict = pipeline( model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification' , ) __A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) __A : Optional[Any] = image_classifier(A_ , candidate_labels=['a', 'b', 'c'] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(A_ ) , [ [{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'b'}, {'score': 0.3_3_3, 'label': 'c'}], [{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'c'}, {'score': 0.3_3_3, 'label': 'b'}], ] , ) __A : Union[str, Any] = image_classifier([image] * 5 , candidate_labels=['A', 'B', 'C'] , batch_size=2 ) self.assertEqual( nested_simplify(A_ ) , [ [ {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, ], [ {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, ], [ {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, ], [ {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, ], [ {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, ], ] , ) @require_tf def UpperCAmelCase_ ( self ): __A : Dict = pipeline( model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification' , framework='tf' ) __A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) __A : Optional[int] = image_classifier(A_ , candidate_labels=['a', 'b', 'c'] ) self.assertEqual( nested_simplify(A_ ) , [{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'b'}, {'score': 0.3_3_3, 'label': 'c'}] , ) __A : Union[str, Any] = image_classifier([image] * 5 , candidate_labels=['A', 'B', 'C'] , batch_size=2 ) self.assertEqual( nested_simplify(A_ ) , [ [ {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, ], [ {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, ], [ {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, ], [ {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, ], [ {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, {'score': 0.3_3_3, 'label': ANY(A_ )}, ], ] , ) @slow @require_torch def UpperCAmelCase_ ( self ): __A : Dict = pipeline( task='zero-shot-image-classification' , model='openai/clip-vit-base-patch32' , ) # This is an image of 2 cats with remotes and no planes __A : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) __A : Dict = image_classifier(A_ , candidate_labels=['cat', 'plane', 'remote'] ) self.assertEqual( nested_simplify(A_ ) , [ {'score': 0.5_1_1, 'label': 'remote'}, {'score': 0.4_8_5, 'label': 'cat'}, {'score': 0.0_0_4, 'label': 'plane'}, ] , ) __A : int = image_classifier([image] * 5 , candidate_labels=['cat', 'plane', 'remote'] , batch_size=2 ) self.assertEqual( nested_simplify(A_ ) , [ [ {'score': 0.5_1_1, 'label': 'remote'}, {'score': 0.4_8_5, 'label': 'cat'}, {'score': 0.0_0_4, 'label': 'plane'}, ], ] * 5 , ) @slow @require_tf def UpperCAmelCase_ ( self ): __A : Optional[Any] = pipeline( task='zero-shot-image-classification' , model='openai/clip-vit-base-patch32' , framework='tf' ) # This is an image of 2 cats with remotes and no planes __A : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) __A : Tuple = image_classifier(A_ , candidate_labels=['cat', 'plane', 'remote'] ) self.assertEqual( nested_simplify(A_ ) , [ {'score': 0.5_1_1, 'label': 'remote'}, {'score': 0.4_8_5, 'label': 'cat'}, {'score': 0.0_0_4, 'label': 'plane'}, ] , ) __A : List[Any] = image_classifier([image] * 5 , candidate_labels=['cat', 'plane', 'remote'] , batch_size=2 ) self.assertEqual( nested_simplify(A_ ) , [ [ {'score': 0.5_1_1, 'label': 'remote'}, {'score': 0.4_8_5, 'label': 'cat'}, {'score': 0.0_0_4, 'label': 'plane'}, ], ] * 5 , )
700
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): __A : Any = data def __iter__( self ): for element in self.data: yield element def _SCREAMING_SNAKE_CASE ( a=True ) -> Any: __A : List[Any] = Accelerator(even_batches=a ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str: if iterable: __A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) ) else: __A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) ) __A : Optional[Any] = DataLoader(a , batch_size=a ) __A : Optional[int] = accelerator.prepare(a ) return dl def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]: __A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a ) __A : Tuple = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : int = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : str = create_accelerator(even_batches=a ) verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _SCREAMING_SNAKE_CASE ( ) -> str: __A : Optional[Any] = create_accelerator(even_batches=a ) __A : str = torch.nn.Linear(1 , 1 ) __A : Optional[int] = accelerator.prepare(a ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : str = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(a ): __A : Dict = ddp_model(batch[0].float() ) __A : List[str] = output.sum() loss.backward() batch_idxs.append(a ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , a ) assert "only supported for multi-GPU" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : int = True __A : Union[str, Any] = False __A : Optional[int] = create_accelerator(even_batches=a ) __A : int = torch.nn.Linear(1 , 1 ) __A : List[Any] = accelerator.prepare(a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : List[str] = train_dl.batch_sampler.even_batches __A : Dict = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Any = True __A : List[Any] = False __A : Tuple = create_accelerator(even_batches=a ) __A : List[str] = torch.nn.Linear(1 , 1 ) __A : Optional[Any] = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('ignore' ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : Tuple = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Any = create_accelerator() __A : Union[str, Any] = torch.nn.Linear(1 , 1 ) __A : str = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): pass assert issubclass(w[-1].category , a ) assert "only supported for map-style datasets" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : str = create_accelerator() accelerator.print('Test that even_batches variable ensures uniform batches across processes' ) test_default_ensures_even_batch_sizes() accelerator.print('Run tests with even_batches disabled' ) test_can_disable_even_batches() accelerator.print('Test joining uneven inputs' ) test_can_join_uneven_inputs() accelerator.print('Test overriding even_batches when joining uneven inputs' ) test_join_can_override_even_batches() accelerator.print('Test overriding even_batches for mixed dataloader types' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('Test join with non DDP distributed raises warning' ) __A : int = accelerator.state.distributed_type __A : Tuple = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(a ) __A : str = original_state if __name__ == "__main__": main()
77
0
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : List[Any] = inspect.getfile(accelerate.test_utils ) __A : str = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_script.py'] ) __A : Optional[Any] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_distributed_data_loop.py'] ) __A : Any = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_ops.py'] ) @require_multi_gpu def UpperCAmelCase_ ( self ): print(F"""Found {torch.cuda.device_count()} devices.""" ) __A : Optional[int] = ['torchrun', F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_A , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self ): print(F"""Found {torch.cuda.device_count()} devices.""" ) __A : Optional[int] = ['torchrun', F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""" ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_A , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self ): __A : Optional[int] = ['torchrun', F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_A , env=os.environ.copy() ) @require_multi_gpu def UpperCAmelCase_ ( self ): print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""" ) __A : Any = ['torchrun', F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='0,1' ): execute_subprocess_async(_A , env=os.environ.copy() ) if __name__ == "__main__": UpperCAmelCase : int = Accelerator() UpperCAmelCase : Optional[Any] = (accelerator.state.process_index + 2, 10) UpperCAmelCase : int = torch.randint(0, 10, shape).to(accelerator.device) UpperCAmelCase : Optional[Any] = '''''' UpperCAmelCase : int = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." UpperCAmelCase : List[Any] = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." UpperCAmelCase : Dict = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
701
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : str = { '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''', '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''', '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''', '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''', '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''', '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''', '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''', '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''', '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''', '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''', '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''', '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = '''codegen''' UpperCamelCase : List[str] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ): __A : Any = vocab_size __A : Tuple = n_ctx __A : Union[str, Any] = n_positions __A : Optional[Any] = n_embd __A : Any = n_layer __A : Dict = n_head __A : Union[str, Any] = n_inner __A : List[Any] = rotary_dim __A : str = activation_function __A : Any = resid_pdrop __A : Tuple = embd_pdrop __A : Tuple = attn_pdrop __A : Union[str, Any] = layer_norm_epsilon __A : str = initializer_range __A : Optional[Any] = use_cache __A : Union[str, Any] = bos_token_id __A : Tuple = eos_token_id super().__init__( bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A ) class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A = "default" , _A = None , _A = False , ): super().__init__(_A , task=_A , patching_specs=_A , use_past=_A ) if not getattr(self._config , 'pad_token_id' , _A ): # TODO: how to do that better? __A : Dict = 0 @property def UpperCAmelCase_ ( self ): __A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) __A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'} else: __A : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase_ ( self ): return self._config.n_layer @property def UpperCAmelCase_ ( self ): return self._config.n_head def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Any = super(_A , self ).generate_dummy_inputs( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) # We need to order the input in the way they appears in the forward() __A : str = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __A , __A : Any = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Any = seqlen + 2 __A : List[str] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __A : Optional[Any] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] __A : Tuple = common_inputs['attention_mask'] if self.use_past: __A : str = ordered_inputs['attention_mask'].dtype __A : List[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self ): return 13
77
0
import os import jsonlines import numpy as np from tqdm import tqdm UpperCAmelCase : int = 20_48 UpperCAmelCase : int = 40_96 UpperCAmelCase : Union[str, Any] = 42 UpperCAmelCase : Dict = os.environ.pop('''PROCESS_TRAIN''', '''false''') UpperCAmelCase : Tuple = {'''null''': 0, '''short''': 1, '''long''': 2, '''yes''': 3, '''no''': 4} def _SCREAMING_SNAKE_CASE ( a ) -> Optional[int]: def choose_first(a , a=False ): assert isinstance(a , a ) if len(a ) == 1: __A : Optional[Any] = answer[0] return {k: [answer[k]] for k in answer} if is_long_answer else answer for a in answer: if is_long_answer: __A : List[Any] = {k: [a[k]] for k in a} if len(a['start_token'] ) > 0: break return a __A : Optional[int] = {'id': example['id']} __A : Tuple = example['annotations'] __A : Dict = annotation['yes_no_answer'] if 0 in yes_no_answer or 1 in yes_no_answer: __A : List[str] = ['yes'] if 1 in yes_no_answer else ['no'] __A : Dict = [] __A : str = [] __A : Tuple = ['<cls>'] else: __A : Any = ['short'] __A : Union[str, Any] = choose_first(annotation['short_answers'] ) if len(out['start_token'] ) == 0: # answer will be long if short is not available __A : Union[str, Any] = ['long'] __A : List[Any] = choose_first(annotation['long_answer'] , is_long_answer=a ) __A : str = [] answer.update(a ) # disregard some samples if len(answer['start_token'] ) > 1 or answer["start_token"] == answer["end_token"]: __A : Optional[int] = True else: __A : Optional[Any] = False __A : Optional[int] = ['start_token', 'end_token', 'start_byte', 'end_byte', 'text'] if not all(isinstance(answer[k] , a ) for k in cols ): raise ValueError('Issue in ID' , example['id'] ) return answer def _SCREAMING_SNAKE_CASE ( a , a=False ) -> List[Any]: __A : Optional[Any] = _get_single_answer(a ) # bytes are of no use del answer["start_byte"] del answer["end_byte"] # handle yes_no answers explicitly if answer["category"][0] in ["yes", "no"]: # category is list with one element __A : Union[str, Any] = example['document']['tokens'] __A : str = [] for i in range(len(doc['token'] ) ): if not doc["is_html"][i]: context.append(doc['token'][i] ) return { "context": " ".join(a ), "answer": { "start_token": -1_00, # ignore index in cross-entropy "end_token": -1_00, # ignore index in cross-entropy "category": answer["category"], "span": answer["category"], # extra }, } # later, help in removing all no answers if answer["start_token"] == [-1]: return { "context": "None", "answer": { "start_token": -1, "end_token": -1, "category": "null", "span": "None", # extra }, } # handling normal samples __A : int = ['start_token', 'end_token'] answer.update({k: answer[k][0] if len(answer[k] ) > 0 else answer[k] for k in cols} ) # e.g. [10] == 10 __A : Any = example['document']['tokens'] __A : Union[str, Any] = answer['start_token'] __A : Optional[int] = answer['end_token'] __A : Tuple = [] for i in range(len(doc['token'] ) ): if not doc["is_html"][i]: context.append(doc['token'][i] ) else: if answer["start_token"] > i: start_token -= 1 if answer["end_token"] > i: end_token -= 1 __A : int = ' '.join(context[start_token:end_token] ) # checking above code if assertion: __A : List[str] = doc['is_html'][answer['start_token'] : answer['end_token']] __A : Any = doc['token'][answer['start_token'] : answer['end_token']] __A : List[str] = ' '.join([old[i] for i in range(len(a ) ) if not is_html[i]] ) if new != old: print('ID:' , example['id'] ) print('New:' , a , end='\n' ) print('Old:' , a , end='\n\n' ) return { "context": " ".join(a ), "answer": { "start_token": start_token, "end_token": end_token - 1, # this makes it inclusive "category": answer["category"], # either long or short "span": new, # extra }, } def _SCREAMING_SNAKE_CASE ( a , a , a=20_48 , a=40_96 , a=True ) -> int: __A : Union[str, Any] = get_context_and_ans(a , assertion=a ) __A : Union[str, Any] = out['answer'] # later, removing these samples if answer["start_token"] == -1: return { "example_id": example["id"], "input_ids": [[-1]], "labels": { "start_token": [-1], "end_token": [-1], "category": ["null"], }, } __A : Union[str, Any] = tokenizer(example['question']['text'] , out['context'] ).input_ids __A : Dict = input_ids.index(tokenizer.sep_token_id ) + 1 # return yes/no if answer["category"][0] in ["yes", "no"]: # category is list with one element __A : Optional[Any] = [] __A : Optional[int] = [] __A : str = input_ids[:q_len] __A : List[Any] = range(a , len(a ) , max_length - doc_stride ) for i in doc_start_indices: __A : int = i + max_length - q_len __A : List[Any] = input_ids[i:end_index] inputs.append(q_indices + slice ) category.append(answer['category'][0] ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": [-1_00] * len(a ), "end_token": [-1_00] * len(a ), "category": category, }, } __A : Dict = out['context'].split() __A : Dict = splitted_context[answer['end_token']] __A : List[Any] = len( tokenizer( ' '.join(splitted_context[: answer['start_token']] ) , add_special_tokens=a , ).input_ids ) __A : List[Any] = len( tokenizer(' '.join(splitted_context[: answer['end_token']] ) , add_special_tokens=a ).input_ids ) answer["start_token"] += q_len answer["end_token"] += q_len # fixing end token __A : Optional[Any] = len(tokenizer(a , add_special_tokens=a ).input_ids ) if num_sub_tokens > 1: answer["end_token"] += num_sub_tokens - 1 __A : Union[str, Any] = input_ids[answer['start_token'] : answer['end_token'] + 1] # right & left are inclusive __A : Tuple = answer['start_token'] __A : int = answer['end_token'] if assertion: __A : Any = tokenizer.decode(a ) if answer["span"] != new: print('ISSUE IN TOKENIZATION' ) print('OLD:' , answer['span'] ) print('NEW:' , a , end='\n\n' ) if len(a ) <= max_length: return { "example_id": example["id"], "input_ids": [input_ids], "labels": { "start_token": [answer["start_token"]], "end_token": [answer["end_token"]], "category": answer["category"], }, } __A : Any = input_ids[:q_len] __A : int = range(a , len(a ) , max_length - doc_stride ) __A : Union[str, Any] = [] __A : List[Any] = [] __A : Optional[int] = [] __A : List[str] = [] # null, yes, no, long, short for i in doc_start_indices: __A : Any = i + max_length - q_len __A : Dict = input_ids[i:end_index] inputs.append(q_indices + slice ) assert len(inputs[-1] ) <= max_length, "Issue in truncating length" if start_token >= i and end_token <= end_index - 1: __A : Dict = start_token - i + q_len __A : Union[str, Any] = end_token - i + q_len answers_category.append(answer['category'][0] ) # ["short"] -> "short" else: __A : int = -1_00 __A : Optional[int] = -1_00 answers_category.append('null' ) __A : List[Any] = inputs[-1][start_token : end_token + 1] answers_start_token.append(a ) answers_end_token.append(a ) if assertion: if new != old and new != [tokenizer.cls_token_id]: print('ISSUE in strided for ID:' , example['id'] ) print('New:' , tokenizer.decode(a ) ) print('Old:' , tokenizer.decode(a ) , end='\n\n' ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": answers_start_token, "end_token": answers_end_token, "category": answers_category, }, } def _SCREAMING_SNAKE_CASE ( a , a , a=20_48 , a=40_96 , a=False ) -> List[Any]: __A : Dict = get_strided_contexts_and_ans( a , a , doc_stride=a , max_length=a , assertion=a , ) return example def _SCREAMING_SNAKE_CASE ( a , a ) -> Any: with jsonlines.open(a , 'a' ) as writer: for example in tqdm(a , total=len(a ) , desc='Saving samples ... ' ): __A : Any = example['labels'] for ids, start, end, cat in zip( example['input_ids'] , labels['start_token'] , labels['end_token'] , labels['category'] , ): if start == -1 and end == -1: continue # leave waste samples with no answer if cat == "null" and np.random.rand() < 0.6: continue # removing 50 % samples writer.write( { 'input_ids': ids, 'start_token': start, 'end_token': end, 'category': CATEGORY_MAPPING[cat], } ) if __name__ == "__main__": from datasets import load_dataset from transformers import BigBirdTokenizer UpperCAmelCase : Optional[int] = load_dataset('''natural_questions''') UpperCAmelCase : Dict = BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''') UpperCAmelCase : List[str] = data['''train''' if PROCESS_TRAIN == '''true''' else '''validation'''] UpperCAmelCase : Tuple = { '''tokenizer''': tokenizer, '''doc_stride''': DOC_STRIDE, '''max_length''': MAX_LENGTH, '''assertion''': False, } UpperCAmelCase : Dict = data.map(prepare_inputs, fn_kwargs=fn_kwargs) UpperCAmelCase : Any = data.remove_columns(['''annotations''', '''document''', '''id''', '''question''']) print(data) np.random.seed(SEED) UpperCAmelCase : str = '''nq-training.jsonl''' if PROCESS_TRAIN == '''true''' else '''nq-validation.jsonl''' save_to_disk(data, file_name=cache_file_name)
702
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase : List[Any] = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _A , ) super().__init__(*_A , **_A )
77
0
import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : str = inspect.getfile(accelerate.test_utils ) __A : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_script.py'] ) __A : List[str] = os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def UpperCAmelCase_ ( self ): __A : Any = F""" {self.test_dir}/xla_spawn.py --num_cores 8 {self.test_file_path} """.split() __A : Tuple = [sys.executable] + distributed_args execute_subprocess_async(__A , env=os.environ.copy() )
703
import glob import os import random from string import ascii_lowercase, digits import cva UpperCAmelCase : Dict = '''''' UpperCAmelCase : Union[str, Any] = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal) def _SCREAMING_SNAKE_CASE ( ) -> None: __A , __A : List[Any] = get_dataset(a , a ) print('Processing...' ) __A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a ) for index, image in enumerate(a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __A : Optional[int] = random_chars(32 ) __A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] __A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Success {index+1}/{len(a )} with {file_name}""" ) __A : int = [] for anno in new_annos[index]: __A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(a ) with open(F"""/{file_root}.txt""" , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]: __A : int = [] __A : List[Any] = [] for label_file in glob.glob(os.path.join(a , '*.txt' ) ): __A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(a ) as in_file: __A : Tuple = in_file.readlines() __A : Dict = os.path.join(a , F"""{label_name}.jpg""" ) __A : Dict = [] for obj_list in obj_lists: __A : int = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(a ) labels.append(a ) return img_paths, labels def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]: __A : int = [] __A : Optional[Any] = [] __A : Dict = [] for idx in range(len(a ) ): __A : Dict = [] __A : Optional[Any] = img_list[idx] path_list.append(a ) __A : Union[str, Any] = anno_list[idx] __A : Optional[Any] = cva.imread(a ) if flip_type == 1: __A : Any = cva.flip(a , a ) for bbox in img_annos: __A : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __A : Union[str, Any] = cva.flip(a , a ) for bbox in img_annos: __A : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(a ) new_imgs_list.append(a ) return new_imgs_list, new_annos_lists, path_list def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __A : List[Any] = ascii_lowercase + digits return "".join(random.choice(a ) for _ in range(a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
77
0
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _A: """simple docstring""" def __init__( self , _A , _A=13 , _A=32 , _A=3 , _A=4 , _A=[10, 20, 30, 40] , _A=[2, 2, 3, 2] , _A=True , _A=True , _A=37 , _A="gelu" , _A=10 , _A=0.0_2 , _A=["stage2", "stage3", "stage4"] , _A=3 , _A=None , ): __A : Dict = parent __A : str = batch_size __A : Union[str, Any] = image_size __A : Optional[int] = num_channels __A : Dict = num_stages __A : Optional[int] = hidden_sizes __A : Optional[int] = depths __A : Optional[Any] = is_training __A : Any = use_labels __A : Dict = intermediate_size __A : str = hidden_act __A : str = type_sequence_label_size __A : Dict = initializer_range __A : Union[str, Any] = out_features __A : Dict = num_labels __A : List[str] = scope __A : Tuple = num_stages def UpperCAmelCase_ ( self ): __A : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A : Union[str, Any] = None if self.use_labels: __A : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Dict = self.get_config() return config, pixel_values, labels def UpperCAmelCase_ ( self ): return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def UpperCAmelCase_ ( self ): return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=_A , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=_A , loss_ignore_index=255 , num_labels=self.num_labels , ) def UpperCAmelCase_ ( self , _A , _A , _A ): __A : List[Any] = UperNetForSemanticSegmentation(config=_A ) model.to(_A ) model.eval() __A : Optional[Any] = model(_A ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def UpperCAmelCase_ ( self ): __A : List[Any] = self.prepare_config_and_inputs() ( __A ) : Tuple = config_and_inputs __A : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class _A( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = (UperNetForSemanticSegmentation,) if is_torch_available() else () UpperCamelCase : Dict = {'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {} UpperCamelCase : Dict = False UpperCamelCase : Optional[int] = False UpperCamelCase : Dict = False UpperCamelCase : str = False UpperCamelCase : str = False UpperCamelCase : Union[str, Any] = False def UpperCAmelCase_ ( self ): __A : List[Any] = UperNetModelTester(self ) __A : Union[str, Any] = ConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): 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 UpperCAmelCase_ ( self ): return def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : Union[str, Any] = model_class(_A ) __A : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A : int = [*signature.parameters.keys()] __A : Tuple = ["pixel_values"] self.assertListEqual(arg_names[:1] , _A ) def UpperCAmelCase_ ( self ): __A : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_A ) @unittest.skip(reason='UperNet does not use inputs_embeds' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='UperNet does not support input and output embeddings' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='UperNet does not have a base model' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='UperNet does not have a base model' ) def UpperCAmelCase_ ( self ): pass @require_torch_multi_gpu @unittest.skip(reason='UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def UpperCAmelCase_ ( self ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): def check_hidden_states_output(_A , _A , _A ): __A : Optional[int] = model_class(_A ) model.to(_A ) model.eval() with torch.no_grad(): __A : str = model(**self._prepare_for_class(_A , _A ) ) __A : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __A : Union[str, Any] = self.model_tester.num_stages self.assertEqual(len(_A ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __A : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : List[str] = True check_hidden_states_output(_A , _A , _A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A : Dict = True check_hidden_states_output(_A , _A , _A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Optional[int] = _config_zero_init(_A ) __A : List[str] = _config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: __A : Tuple = model_class(config=_A ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip(reason='UperNet does not have tied weights' ) def UpperCAmelCase_ ( self ): pass @slow def UpperCAmelCase_ ( self ): for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A : Dict = UperNetForSemanticSegmentation.from_pretrained(_A ) self.assertIsNotNone(_A ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : Optional[int] = hf_hub_download( repo_id='hf-internal-testing/fixtures_ade20k' , repo_type='dataset' , filename='ADE_val_00000001.jpg' ) __A : Tuple = Image.open(_lowerCamelCase ).convert('RGB' ) return image @require_torch @require_vision @slow class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Optional[int] = AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny' ) __A : Optional[Any] = UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny' ).to(_A ) __A : int = prepare_img() __A : Dict = processor(images=_A , return_tensors='pt' ).to(_A ) with torch.no_grad(): __A : str = model(**_A ) __A : Dict = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _A ) __A : Dict = torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _A , atol=1e-4 ) ) def UpperCAmelCase_ ( self ): __A : List[Any] = AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny' ) __A : Union[str, Any] = UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny' ).to(_A ) __A : Optional[int] = prepare_img() __A : Dict = processor(images=_A , return_tensors='pt' ).to(_A ) with torch.no_grad(): __A : Any = model(**_A ) __A : Any = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , _A ) __A : Optional[int] = torch.tensor( [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , _A , atol=1e-4 ) )
704
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A: """simple docstring""" def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=True , _A=False , _A=True , _A=99 , _A=32 , _A=5 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=16 , _A=2 , _A=0.0_2 , _A=3 , _A=4 , _A=None , ): __A : Union[str, Any] = parent __A : List[str] = batch_size __A : Optional[int] = seq_length __A : List[Any] = is_training __A : Optional[Any] = use_input_mask __A : List[Any] = use_token_type_ids __A : Optional[Any] = use_labels __A : List[str] = vocab_size __A : Optional[int] = hidden_size __A : List[Any] = num_hidden_layers __A : int = num_attention_heads __A : Dict = intermediate_size __A : Any = hidden_act __A : Union[str, Any] = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : Optional[int] = max_position_embeddings __A : Dict = type_vocab_size __A : Any = type_sequence_label_size __A : Dict = initializer_range __A : str = num_labels __A : Union[str, Any] = num_choices __A : str = scope def UpperCAmelCase_ ( self ): __A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : Optional[Any] = None if self.use_input_mask: __A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __A : Dict = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = None __A : List[Any] = None __A : List[Any] = None if self.use_labels: __A : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __A : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[str] = LlamaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A , attention_mask=_A ) __A : Any = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Dict = True __A : int = LlamaModel(_A ) model.to(_A ) model.eval() __A : str = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __A : int = model( _A , attention_mask=_A , encoder_hidden_states=_A , ) __A : List[Any] = model(_A , attention_mask=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Optional[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : int = True __A : List[Any] = True __A : List[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() # first forward pass __A : Optional[Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , ) __A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __A : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) __A : str = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __A : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : str = torch.cat([input_mask, next_mask] , dim=-1 ) __A : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['hidden_states'][0] __A : Union[str, Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , past_key_values=_A , output_hidden_states=_A , )['hidden_states'][0] # select random slice __A : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() __A : Tuple = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_A , _A , atol=1e-3 ) ) def UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Tuple = config_and_inputs __A : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () UpperCamelCase : Optional[Any] = (LlamaForCausalLM,) if is_torch_available() else () UpperCamelCase : Optional[Any] = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False def UpperCAmelCase_ ( self ): __A : List[Any] = LlamaModelTester(self ) __A : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : int = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() __A : str = 3 __A : Optional[int] = input_dict['input_ids'] __A : int = input_ids.ne(1 ).to(_A ) __A : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Union[str, Any] = 3 __A : Tuple = 'single_label_classification' __A : Union[str, Any] = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[int] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Any = 3 __A : int = 'multi_label_classification' __A : int = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __A : List[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def UpperCAmelCase_ ( self ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def UpperCAmelCase_ ( self , _A ): __A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Dict = ids_tensor([1, 10] , config.vocab_size ) __A : Union[str, Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : List[Any] = LlamaModel(_A ) original_model.to(_A ) original_model.eval() __A : Dict = original_model(_A ).last_hidden_state __A : int = original_model(_A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : int = {'type': scaling_type, 'factor': 1_0.0} __A : str = LlamaModel(_A ) scaled_model.to(_A ) scaled_model.eval() __A : Dict = scaled_model(_A ).last_hidden_state __A : str = scaled_model(_A ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(_A , _A , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) __A : Union[str, Any] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __A : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[str] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) __A : int = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) __A : Optional[int] = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : Optional[Any] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) __A : List[Any] = model(torch.tensor(_A ) ) __A : Tuple = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # fmt: off __A : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' __A : List[str] = 'Simply put, the theory of relativity states that ' __A : Union[str, Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) __A : List[str] = tokenizer.encode(_A , return_tensors='pt' ) __A : Tuple = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=_A ) # greedy generation outputs __A : Union[str, Any] = model.generate(_A , max_new_tokens=64 , top_p=_A , temperature=1 , do_sample=_A ) __A : List[str] = tokenizer.decode(generated_ids[0] , skip_special_tokens=_A ) self.assertEqual(_A , _A )
77
0
import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( '''The `inpainting.py` script is outdated. Please use directly `from diffusers import''' ''' StableDiffusionInpaintPipeline` instead.''' )
705
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
0
import json import os import unittest from transformers import BatchEncoding, MvpTokenizer, MvpTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors @require_tokenizers class _A( __a , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[Any] = MvpTokenizer UpperCamelCase : str = MvpTokenizerFast UpperCamelCase : List[str] = True UpperCamelCase : int = filter_roberta_detectors def UpperCAmelCase_ ( self ): super().setUp() __A : str = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] __A : Optional[int] = dict(zip(a_ , range(len(a_ ) ) ) ) __A : Tuple = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] __A : Optional[int] = {"""unk_token""": """<unk>"""} __A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(a_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a_ ) ) def UpperCAmelCase_ ( self , **_A ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **a_ ) def UpperCAmelCase_ ( self , **_A ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **a_ ) def UpperCAmelCase_ ( self , _A ): return "lower newer", "lower newer" @cached_property def UpperCAmelCase_ ( self ): return MvpTokenizer.from_pretrained('RUCAIBox/mvp' ) @cached_property def UpperCAmelCase_ ( self ): return MvpTokenizerFast.from_pretrained('RUCAIBox/mvp' ) @require_torch def UpperCAmelCase_ ( self ): __A : Any = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] __A : List[str] = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __A : List[Any] = tokenizer(a_ , max_length=len(a_ ) , padding=a_ , return_tensors='pt' ) self.assertIsInstance(a_ , a_ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) __A : Union[str, Any] = batch.input_ids.tolist()[0] self.assertListEqual(a_ , a_ ) # Test that special tokens are reset @require_torch def UpperCAmelCase_ ( self ): __A : str = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __A : Dict = tokenizer(a_ , padding=a_ , return_tensors='pt' ) # check if input_ids are returned and no labels self.assertIn('input_ids' , a_ ) self.assertIn('attention_mask' , a_ ) self.assertNotIn('labels' , a_ ) self.assertNotIn('decoder_attention_mask' , a_ ) @require_torch def UpperCAmelCase_ ( self ): __A : str = [ """Summary of the text.""", """Another summary.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __A : int = tokenizer(text_target=a_ , max_length=32 , padding='max_length' , return_tensors='pt' ) self.assertEqual(32 , targets['input_ids'].shape[1] ) @require_torch def UpperCAmelCase_ ( self ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __A : Optional[Any] = tokenizer( ['I am a small frog' * 1024, 'I am a small frog'] , padding=a_ , truncation=a_ , return_tensors='pt' ) self.assertIsInstance(a_ , a_ ) self.assertEqual(batch.input_ids.shape , (2, 1024) ) @require_torch def UpperCAmelCase_ ( self ): __A : Union[str, Any] = ["""A long paragraph for summarization."""] __A : Tuple = [ """Summary of the text.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __A : Dict = tokenizer(a_ , text_target=a_ , return_tensors='pt' ) __A : List[str] = inputs["""input_ids"""] __A : List[str] = inputs["""labels"""] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __A : Any = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) __A : Any = self.tokenizer_class.from_pretrained(a_ , **a_ ) __A : int = """A, <mask> AllenNLP sentence.""" __A : List[Any] = tokenizer_r.encode_plus(a_ , add_special_tokens=a_ , return_token_type_ids=a_ ) __A : List[str] = tokenizer_p.encode_plus(a_ , add_special_tokens=a_ , return_token_type_ids=a_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['token_type_ids'] ) , sum(tokens_p['token_type_ids'] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['attention_mask'] ) / len(tokens_r['attention_mask'] ) , sum(tokens_p['attention_mask'] ) / len(tokens_p['attention_mask'] ) , ) __A : List[Any] = tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids'] ) __A : int = tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids'] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['input_ids'] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r['input_ids'] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] ) self.assertSequenceEqual( a_ , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] ) self.assertSequenceEqual( a_ , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] )
706
import numpy as np from PIL import Image def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : Union[str, Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : List[Any] = 0 __A : Optional[Any] = 0 __A : List[Any] = 0 __A : Dict = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __A : Tuple = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : List[str] = 0 __A : Union[str, Any] = 0 return updated_arr def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : List[Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : Dict = 0 __A : str = 0 __A : Tuple = 0 __A : Optional[int] = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __A : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : Dict = 0 __A : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image UpperCAmelCase : int = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
77
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Dict = { '''xlm-mlm-en-2048''': '''https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json''', '''xlm-mlm-ende-1024''': '''https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json''', '''xlm-mlm-enfr-1024''': '''https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json''', '''xlm-mlm-enro-1024''': '''https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json''', '''xlm-mlm-tlm-xnli15-1024''': '''https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json''', '''xlm-mlm-xnli15-1024''': '''https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json''', '''xlm-clm-enfr-1024''': '''https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json''', '''xlm-clm-ende-1024''': '''https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json''', '''xlm-mlm-17-1280''': '''https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json''', '''xlm-mlm-100-1280''': '''https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Any = '''xlm''' UpperCamelCase : Tuple = { '''hidden_size''': '''emb_dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', '''n_words''': '''vocab_size''', # For backward compatibility } def __init__( self , _A=30145 , _A=2048 , _A=12 , _A=16 , _A=0.1 , _A=0.1 , _A=True , _A=False , _A=False , _A=False , _A=1 , _A=True , _A=512 , _A=2048**-0.5 , _A=1e-1_2 , _A=0.0_2 , _A=0 , _A=1 , _A=2 , _A=3 , _A=5 , _A=True , _A="first" , _A=True , _A=None , _A=True , _A=0.1 , _A=5 , _A=5 , _A=0 , _A=0 , _A=2 , _A=0 , **_A , ): __A : str = vocab_size __A : Dict = emb_dim __A : Tuple = n_layers __A : Any = n_heads __A : List[Any] = dropout __A : str = attention_dropout __A : Dict = gelu_activation __A : Any = sinusoidal_embeddings __A : Any = causal __A : Union[str, Any] = asm __A : Tuple = n_langs __A : Dict = use_lang_emb __A : int = layer_norm_eps __A : Dict = bos_index __A : str = eos_index __A : int = pad_index __A : Union[str, Any] = unk_index __A : str = mask_index __A : Optional[Any] = is_encoder __A : str = max_position_embeddings __A : Tuple = embed_init_std __A : List[str] = init_std __A : Union[str, Any] = summary_type __A : Tuple = summary_use_proj __A : Any = summary_activation __A : Union[str, Any] = summary_proj_to_labels __A : int = summary_first_dropout __A : Optional[int] = start_n_top __A : int = end_n_top __A : Union[str, Any] = mask_token_id __A : int = lang_id if "n_words" in kwargs: __A : Union[str, Any] = kwargs['n_words'] super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) class _A( snake_case__ ): """simple docstring""" @property def UpperCAmelCase_ ( self ): if self.task == "multiple-choice": __A : List[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __A : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
707
from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float: __A : Any = x_start __A : List[str] = fnc(a ) __A : Optional[Any] = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area __A : Any = (x_end - x_start) / steps + xa __A : List[str] = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __A : Any = xa __A : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( a ) -> int: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') UpperCAmelCase : Tuple = 10 while i <= 10_00_00: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
77
0
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint UpperCAmelCase : Dict = { "169M": 12, "430M": 24, "1B5": 24, "3B": 32, "7B": 32, "14B": 40, } UpperCAmelCase : Tuple = { "169M": 7_68, "430M": 10_24, "1B5": 20_48, "3B": 25_60, "7B": 40_96, "14B": 51_20, } def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : int = list(state_dict.keys() ) for name in state_dict_keys: __A : List[str] = state_dict.pop(UpperCAmelCase__ ) # emb -> embedding if name.startswith('emb.' ): __A : str = name.replace('emb.' , 'embeddings.' ) # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0' ): __A : int = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln' ) # att -> attention __A : Union[str, Any] = re.sub(r'blocks\.(\d+)\.att' , r'blocks.\1.attention' , UpperCAmelCase__ ) # ffn -> feed_forward __A : Optional[Any] = re.sub(r'blocks\.(\d+)\.ffn' , r'blocks.\1.feed_forward' , UpperCAmelCase__ ) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k' ): __A : Any = name.replace('.time_mix_k' , '.time_mix_key' ) # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v' ): __A : int = name.replace('.time_mix_v' , '.time_mix_value' ) # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r' ): __A : Any = name.replace('.time_mix_r' , '.time_mix_receptance' ) if name != "head.weight": __A : int = """rwkv.""" + name __A : Any = weight return state_dict def _SCREAMING_SNAKE_CASE ( a , a , a , a=None , a=None , a=False , a=None ) -> Any: # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.' ) __A : Dict = 5_02_77 __A : Optional[int] = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b' ) else: __A : Union[str, Any] = PreTrainedTokenizerFast(tokenizer_file=UpperCAmelCase__ ) __A : str = len(UpperCAmelCase__ ) tokenizer.save_pretrained(UpperCAmelCase__ ) # 2. Build the config __A : Optional[Any] = list(NUM_HIDDEN_LAYERS_MAPPING.keys() ) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: __A : List[str] = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.' ) if size not in possible_sizes: raise ValueError(F"""`size` should be one of {possible_sizes}, got {size}.""" ) __A : Dict = RwkvConfig( vocab_size=UpperCAmelCase__ , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(UpperCAmelCase__ ) # 3. Download model file then convert state_dict __A : Optional[Any] = hf_hub_download(UpperCAmelCase__ , UpperCAmelCase__ ) __A : List[Any] = torch.load(UpperCAmelCase__ , map_location='cpu' ) __A : Dict = convert_state_dict(UpperCAmelCase__ ) # 4. Split in shards and save __A : Dict = shard_checkpoint(UpperCAmelCase__ ) for shard_file, shard in shards.items(): torch.save(UpperCAmelCase__ , os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) ) if index is not None: __A : Dict = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) # Save the index as well with open(UpperCAmelCase__ , 'w' , encoding='utf-8' ) as f: __A : Optional[Any] = json.dumps(UpperCAmelCase__ , indent=2 , sort_keys=UpperCAmelCase__ ) + """\n""" f.write(UpperCAmelCase__ ) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.' ) __A : Optional[Any] = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: __A : Optional[Any] = torch.load(os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) ) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.' ) __A : Dict = AutoModelForCausalLM.from_pretrained(UpperCAmelCase__ ) model.push_to_hub(UpperCAmelCase__ , max_shard_size='2GB' ) tokenizer.push_to_hub(UpperCAmelCase__ ) if __name__ == "__main__": UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--repo_id''', default=None, type=str, required=True, help='''Repo ID from which to pull the checkpoint.''' ) parser.add_argument( '''--checkpoint_file''', default=None, type=str, required=True, help='''Name of the checkpoint file in the repo.''' ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''Where to save the converted model.''' ) parser.add_argument( '''--tokenizer_file''', default=None, type=str, help='''Path to the tokenizer file to use (if not provided, only the model is converted).''', ) parser.add_argument( '''--size''', default=None, type=str, help='''Size of the model. Will be inferred from the `checkpoint_file` if not passed.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Push to the Hub the converted model.''', ) parser.add_argument( '''--model_name''', default=None, type=str, help='''Name of the pushed model on the Hub, including the username / organization.''', ) UpperCAmelCase : List[str] = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
708
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def _SCREAMING_SNAKE_CASE ( ) -> None: print('Making key files...' ) make_key_files('rsa' , 10_24 ) print('Key files generation successful.' ) def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]: print('Generating prime p...' ) __A : Optional[Any] = rabinMiller.generate_large_prime(a ) print('Generating prime q...' ) __A : Union[str, Any] = rabinMiller.generate_large_prime(a ) __A : Tuple = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...' ) while True: __A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1: break print('Calculating d that is mod inverse of e...' ) __A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) ) __A : Dict = (n, e) __A : Dict = (n, d) return (public_key, private_key) def _SCREAMING_SNAKE_CASE ( a , a ) -> 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() __A , __A : Optional[int] = generate_key(a ) 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()
77
0
import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCAmelCase_ ( self ): __A : str = 1 __A : Tuple = 3 __A : Tuple = (32, 32) __A : Tuple = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowerCAmelCase__ ) return image @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Union[str, Any] = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5006 , ) return RobertaSeriesModelWithTransformation(lowerCAmelCase__ ) @property def UpperCAmelCase_ ( self ): def extract(*_A , **_A ): class _A: """simple docstring""" def __init__( self ): __A : Dict = torch.ones([0] ) def UpperCAmelCase_ ( self , _A ): self.pixel_values.to(lowerCAmelCase__ ) return self return Out() return extract def UpperCAmelCase_ ( self ): __A : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator __A : Any = self.dummy_cond_unet __A : Dict = PNDMScheduler(skip_prk_steps=lowerCAmelCase__ ) __A : Tuple = self.dummy_vae __A : Any = self.dummy_text_encoder __A : Tuple = XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta' ) __A : str = 77 __A : Tuple = self.dummy_image.to(lowerCAmelCase__ ) __A : Optional[int] = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk __A : Optional[Any] = AltDiffusionImgaImgPipeline( unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ , vae=lowerCAmelCase__ , text_encoder=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , safety_checker=lowerCAmelCase__ , feature_extractor=self.dummy_extractor , ) __A : Any = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=lowerCAmelCase__ ) __A : Optional[Any] = alt_pipe.to(lowerCAmelCase__ ) alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) __A : List[Any] = "A painting of a squirrel eating a burger" __A : Any = torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 ) __A : Dict = alt_pipe( [prompt] , generator=lowerCAmelCase__ , guidance_scale=6.0 , num_inference_steps=2 , output_type='np' , image=lowerCAmelCase__ , ) __A : List[str] = output.images __A : Dict = torch.Generator(device=lowerCAmelCase__ ).manual_seed(0 ) __A : List[Any] = alt_pipe( [prompt] , generator=lowerCAmelCase__ , guidance_scale=6.0 , num_inference_steps=2 , output_type='np' , image=lowerCAmelCase__ , return_dict=lowerCAmelCase__ , )[0] __A : Optional[int] = image[0, -3:, -3:, -1] __A : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __A : Dict = np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3 @unittest.skipIf(torch_device != 'cuda' , 'This test requires a GPU' ) def UpperCAmelCase_ ( self ): __A : str = self.dummy_cond_unet __A : int = PNDMScheduler(skip_prk_steps=lowerCAmelCase__ ) __A : Optional[Any] = self.dummy_vae __A : Tuple = self.dummy_text_encoder __A : Optional[int] = XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta' ) __A : Optional[Any] = 77 __A : Any = self.dummy_image.to(lowerCAmelCase__ ) # put models in fp16 __A : Any = unet.half() __A : List[str] = vae.half() __A : Optional[Any] = bert.half() # make sure here that pndm scheduler skips prk __A : List[str] = AltDiffusionImgaImgPipeline( unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ , vae=lowerCAmelCase__ , text_encoder=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , safety_checker=lowerCAmelCase__ , feature_extractor=self.dummy_extractor , ) __A : Any = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=lowerCAmelCase__ ) __A : List[str] = alt_pipe.to(lowerCAmelCase__ ) alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) __A : Any = "A painting of a squirrel eating a burger" __A : Any = torch.manual_seed(0 ) __A : int = alt_pipe( [prompt] , generator=lowerCAmelCase__ , num_inference_steps=2 , output_type='np' , image=lowerCAmelCase__ , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != 'cuda' , 'This test requires a GPU' ) def UpperCAmelCase_ ( self ): __A : List[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) # resize to resolution that is divisible by 8 but not 16 or 32 __A : Optional[Any] = init_image.resize((760, 504) ) __A : Optional[int] = "BAAI/AltDiffusion" __A : Union[str, Any] = AltDiffusionImgaImgPipeline.from_pretrained( lowerCAmelCase__ , safety_checker=lowerCAmelCase__ , ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) pipe.enable_attention_slicing() __A : str = "A fantasy landscape, trending on artstation" __A : Tuple = torch.manual_seed(0 ) __A : List[Any] = pipe( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , strength=0.7_5 , guidance_scale=7.5 , generator=lowerCAmelCase__ , output_type='np' , ) __A : Union[str, Any] = output.images[0] __A : List[Any] = image[255:258, 383:386, -1] assert image.shape == (504, 760, 3) __A : Dict = np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) __A : Any = init_image.resize((768, 512) ) __A : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy' ) __A : Optional[Any] = "BAAI/AltDiffusion" __A : Optional[int] = AltDiffusionImgaImgPipeline.from_pretrained( lowerCAmelCase__ , safety_checker=lowerCAmelCase__ , ) pipe.to(lowerCAmelCase__ ) pipe.set_progress_bar_config(disable=lowerCAmelCase__ ) pipe.enable_attention_slicing() __A : Tuple = "A fantasy landscape, trending on artstation" __A : Union[str, Any] = torch.manual_seed(0 ) __A : Dict = pipe( prompt=lowerCAmelCase__ , image=lowerCAmelCase__ , strength=0.7_5 , guidance_scale=7.5 , generator=lowerCAmelCase__ , output_type='np' , ) __A : int = output.images[0] assert image.shape == (512, 768, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1e-2
709
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ProphetNetTokenizer UpperCamelCase : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() __A : Any = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = 'UNwant\u00E9d,running' __A : List[str] = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class(self.vocab_file ) __A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase_ ( self ): __A : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCAmelCase_ ( self ): __A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __A : Optional[int] = {} for i, token in enumerate(_A ): __A : Tuple = i __A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __A : str = tokenizer(_A , padding=_A , return_tensors='pt' ) self.assertIsInstance(_A , _A ) __A : List[str] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A ) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A ) __A : str = tokenizer.build_inputs_with_special_tokens(_A ) __A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
77
0
def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]: __A : Dict = len(UpperCAmelCase__ ) __A : int = [[0] * n for i in range(UpperCAmelCase__ )] for i in range(UpperCAmelCase__ ): __A : int = y_points[i] for i in range(2 , UpperCAmelCase__ ): for j in range(UpperCAmelCase__ , UpperCAmelCase__ ): __A : str = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
710
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Optional[int] = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } UpperCAmelCase : List[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = BertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : Any = getattr(_A , normalizer_state.pop('type' ) ) __A : Union[str, Any] = do_lower_case __A : Optional[int] = strip_accents __A : List[Any] = tokenize_chinese_chars __A : int = normalizer_class(**_A ) __A : Union[str, Any] = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : Tuple = [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 UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[Any] = [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : int = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
0
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor UpperCAmelCase : List[str] = logging.get_logger(__name__) class _A( __UpperCAmelCase ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use CLIPImageProcessor instead.' , UpperCAmelCase_ , ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ )
711
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 UpperCAmelCase_ ( self ): debug_launcher(test_script.main ) def UpperCAmelCase_ ( self ): debug_launcher(test_ops.main )
77
0
import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _A( UpperCamelCase_ , unittest.TestCase ): """simple docstring""" UpperCamelCase : str = PhobertTokenizer UpperCamelCase : Any = False def UpperCAmelCase_ ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __A : Dict = ['''T@@''', '''i''', '''I''', '''R@@''', '''r''', '''e@@'''] __A : int = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) ) __A : Any = ['''#version: 0.2''', '''l à</w>'''] __A : List[Any] = {'''unk_token''': '''<unk>'''} __A : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: for token in vocab_tokens: fp.write(F"""{token} {vocab_tokens[token]}\n""" ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(UpperCamelCase__ ) ) def UpperCAmelCase_ ( self , **_A ): kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def UpperCAmelCase_ ( self , _A ): __A : Union[str, Any] = '''Tôi là VinAI Research''' __A : Optional[int] = '''T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>''' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Any = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __A : str = '''Tôi là VinAI Research''' __A : Optional[Any] = '''T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h'''.split() __A : int = tokenizer.tokenize(UpperCamelCase__ ) print(UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) __A : Any = tokens + [tokenizer.unk_token] __A : List[str] = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , UpperCamelCase__ )
712
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Tuple = tempfile.mkdtemp() # fmt: off __A : Union[str, Any] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Dict = dict(zip(_A , range(len(_A ) ) ) ) __A : int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : Optional[Any] = {'unk_token': '<unk>'} __A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : Union[str, Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : List[str] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[str] = self.get_tokenizer() __A : Dict = self.get_rust_tokenizer() __A : Optional[Any] = self.get_image_processor() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Any = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : int = self.get_image_processor(do_normalize=_A ) __A : int = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : List[Any] = self.prepare_image_inputs() __A : Any = image_processor(_A , return_tensors='np' ) __A : Tuple = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_image_processor() __A : int = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = 'lower newer' __A : Any = processor(text=_A , return_tensors='np' ) __A : Dict = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Tuple = 'lower newer' __A : Union[str, Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[int] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Any = ['cat', 'nasa badge'] __A : List[Any] = processor(text=_A ) __A : Dict = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : int = [['cat', 'nasa badge'], ['person']] __A : str = processor(text=_A ) __A : int = 16 __A : Optional[int] = len(_A ) __A : int = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : int = 'google/owlvit-base-patch32' __A : List[str] = OwlViTProcessor.from_pretrained(_A ) __A : Tuple = ['cat', 'nasa badge'] __A : Dict = processor(text=_A ) __A : Tuple = 16 __A : str = inputs['input_ids'] __A : str = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Dict = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = self.prepare_image_inputs() __A : Tuple = self.prepare_image_inputs() __A : Any = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Union[str, Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
77
0
UpperCAmelCase : Optional[Any] = 6_55_21 def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : Optional[Any] = 1 __A : List[str] = 0 for plain_chr in plain_text: __A : int = (a + ord(__UpperCamelCase )) % MOD_ADLER __A : Any = (b + a) % MOD_ADLER return (b << 16) | a
713
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase : Union[str, Any] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Tuple: for attribute in key.split('.' ): __A : Dict = getattr(a , a ) if weight_type is not None: __A : Any = getattr(a , a ).shape else: __A : Any = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __A : Union[str, Any] = value elif weight_type == "weight_g": __A : Dict = value elif weight_type == "weight_v": __A : Optional[int] = value elif weight_type == "bias": __A : int = value elif weight_type == "running_mean": __A : Union[str, Any] = value elif weight_type == "running_var": __A : Union[str, Any] = value elif weight_type == "num_batches_tracked": __A : Any = value elif weight_type == "inv_freq": __A : Optional[Any] = value else: __A : int = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]: __A : Any = [] __A : Optional[int] = fairseq_model.state_dict() __A : Union[str, Any] = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __A : int = False if "conv_layers" in name: load_conv_layer( a , a , a , a , hf_model.config.feat_extract_norm == 'group' , ) __A : Optional[int] = True else: for key, mapped_key in MAPPING.items(): __A : Any = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __A : Optional[Any] = True if "*" in mapped_key: __A : str = name.split(a )[0].split('.' )[-2] __A : int = mapped_key.replace('*' , a ) if "pos_bias_u" in name: __A : Optional[int] = None elif "pos_bias_v" in name: __A : Dict = None elif "weight_g" in name: __A : Optional[Any] = 'weight_g' elif "weight_v" in name: __A : Dict = 'weight_v' elif "bias" in name: __A : Tuple = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __A : int = 'weight' elif "running_mean" in name: __A : str = 'running_mean' elif "inv_freq" in name: __A : List[Any] = 'inv_freq' elif "running_var" in name: __A : Union[str, Any] = 'running_var' elif "num_batches_tracked" in name: __A : Optional[Any] = 'num_batches_tracked' else: __A : List[str] = None set_recursively(a , a , a , a , a ) continue if not is_used: unused_weights.append(a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Any: __A : str = full_name.split('conv_layers.' )[-1] __A : str = name.split('.' ) __A : Dict = int(items[0] ) __A : Any = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) __A : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) __A : List[str] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a ) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a=None , a=None , a=True ) -> Any: if config_path is not None: __A : Tuple = WavaVecaConformerConfig.from_pretrained(a , hidden_act='swish' ) else: __A : Optional[Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: __A : Dict = 'rotary' if is_finetuned: if dict_path: __A : Dict = Dictionary.load(a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __A : int = target_dict.pad_index __A : List[Any] = target_dict.bos_index __A : Any = target_dict.eos_index __A : Dict = len(target_dict.symbols ) __A : Optional[Any] = os.path.join(a , 'vocab.json' ) if not os.path.isdir(a ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(a ) ) return os.makedirs(a , exist_ok=a ) __A : List[str] = target_dict.indices # fairseq has the <pad> and <s> switched __A : int = 0 __A : Optional[Any] = 1 with open(a , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(a , a ) __A : Optional[Any] = WavaVecaCTCTokenizer( a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=a , ) __A : Tuple = True if config.feat_extract_norm == 'layer' else False __A : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=a , return_attention_mask=a , ) __A : Optional[int] = WavaVecaProcessor(feature_extractor=a , tokenizer=a ) processor.save_pretrained(a ) __A : List[Any] = WavaVecaConformerForCTC(a ) else: __A : List[Any] = WavaVecaConformerForPreTraining(a ) if is_finetuned: __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: __A : Optional[Any] = argparse.Namespace(task='audio_pretraining' ) __A : str = fairseq.tasks.setup_task(a ) __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=a ) __A : Tuple = model[0].eval() recursively_load_weights(a , a , not is_finetuned ) hf_wavavec.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) UpperCAmelCase : List[str] = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
77
0
from math import factorial UpperCAmelCase : Optional[Any] = {str(d): factorial(d) for d in range(10)} def _SCREAMING_SNAKE_CASE ( a ) -> Optional[Any]: return sum(DIGIT_FACTORIAL[d] for d in str(a ) ) def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Optional[int] = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , a ) if sum_of_digit_factorial(a ) == i ) if __name__ == "__main__": print(F"""{solution() = }""")
714
from abc import ABC, abstractmethod from argparse import ArgumentParser class _A( snake_case__ ): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( _A ): raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self ): raise NotImplementedError()
77
0
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase : List[Any] = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''} # See all BART models at https://huggingface.co/models?filter=bart UpperCAmelCase : Any = { '''vocab_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''', }, '''merges_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''', }, } UpperCAmelCase : Optional[int] = { '''facebook/bart-base''': 10_24, '''facebook/bart-large''': 10_24, '''facebook/bart-large-mnli''': 10_24, '''facebook/bart-large-cnn''': 10_24, '''facebook/bart-large-xsum''': 10_24, '''yjernite/bart_eli5''': 10_24, } @lru_cache() def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : str = ( list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) ) ) __A : List[Any] = bs[:] __A : Optional[int] = 0 for b in range(2**8 ): if b not in bs: bs.append(SCREAMING_SNAKE_CASE_ ) cs.append(2**8 + n ) n += 1 __A : List[str] = [chr(SCREAMING_SNAKE_CASE_ ) for n in cs] return dict(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : int = set() __A : Dict = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __A : Union[str, Any] = char return pairs class _A( lowercase__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = VOCAB_FILES_NAMES UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = ["""input_ids""", """attention_mask"""] def __init__( self , _A , _A , _A="replace" , _A="<s>" , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A=False , **_A , ): __A : Optional[Any] = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else bos_token __A : Dict = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else eos_token __A : str = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else sep_token __A : Dict = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else cls_token __A : str = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else unk_token __A : str = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __A : List[str] = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token super().__init__( errors=__lowercase , bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , sep_token=__lowercase , cls_token=__lowercase , pad_token=__lowercase , mask_token=__lowercase , add_prefix_space=__lowercase , **__lowercase , ) with open(__lowercase , encoding='utf-8' ) as vocab_handle: __A : List[Any] = json.load(__lowercase ) __A : str = {v: k for k, v in self.encoder.items()} __A : List[Any] = errors # how to handle errors in decoding __A : int = bytes_to_unicode() __A : Any = {v: k for k, v in self.byte_encoder.items()} with open(__lowercase , encoding='utf-8' ) as merges_handle: __A : Tuple = merges_handle.read().split('\n' )[1:-1] __A : Dict = [tuple(merge.split() ) for merge in bpe_merges] __A : int = dict(zip(__lowercase , range(len(__lowercase ) ) ) ) __A : List[Any] = {} __A : Any = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __A : List[Any] = re.compile(R'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def UpperCAmelCase_ ( self ): return len(self.encoder ) def UpperCAmelCase_ ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase_ ( self , _A ): if token in self.cache: return self.cache[token] __A : Dict = tuple(__lowercase ) __A : List[Any] = get_pairs(__lowercase ) if not pairs: return token while True: __A : Union[str, Any] = min(__lowercase , key=lambda _A : self.bpe_ranks.get(__lowercase , float('inf' ) ) ) if bigram not in self.bpe_ranks: break __A , __A : str = bigram __A : Tuple = [] __A : Dict = 0 while i < len(__lowercase ): try: __A : Dict = word.index(__lowercase , __lowercase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __A : Dict = j if word[i] == first and i < len(__lowercase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __A : Optional[Any] = tuple(__lowercase ) __A : List[Any] = new_word if len(__lowercase ) == 1: break else: __A : Dict = get_pairs(__lowercase ) __A : int = ' '.join(__lowercase ) __A : int = word return word def UpperCAmelCase_ ( self , _A ): __A : Dict = [] for token in re.findall(self.pat , __lowercase ): __A : Any = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__lowercase ).split(' ' ) ) return bpe_tokens def UpperCAmelCase_ ( self , _A ): return self.encoder.get(__lowercase , self.encoder.get(self.unk_token ) ) def UpperCAmelCase_ ( self , _A ): return self.decoder.get(__lowercase ) def UpperCAmelCase_ ( self , _A ): __A : Union[str, Any] = ''.join(__lowercase ) __A : Dict = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def UpperCAmelCase_ ( self , _A , _A = None ): if not os.path.isdir(__lowercase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __A : str = os.path.join( __lowercase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __A : Union[str, Any] = os.path.join( __lowercase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(__lowercase , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__lowercase , ensure_ascii=__lowercase ) + '\n' ) __A : List[Any] = 0 with open(__lowercase , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _A : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ' Please check that the tokenizer is not corrupted!' ) __A : List[Any] = token_index writer.write(' '.join(__lowercase ) + '\n' ) index += 1 return vocab_file, merge_file def UpperCAmelCase_ ( self , _A , _A = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] __A : str = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase_ ( self , _A , _A = None , _A = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowercase , token_ids_a=__lowercase , already_has_special_tokens=__lowercase ) if token_ids_a is None: return [1] + ([0] * len(__lowercase )) + [1] return [1] + ([0] * len(__lowercase )) + [1, 1] + ([0] * len(__lowercase )) + [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : Dict = [self.sep_token_id] __A : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCAmelCase_ ( self , _A , _A=False , **_A ): __A : int = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__lowercase ) > 0 and not text[0].isspace()): __A : Optional[Any] = ' ' + text return (text, kwargs)
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
0
import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : int = logging.get_logger() # the current default level is logging.WARNING __A : Any = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(A_ ) def UpperCAmelCase_ ( self ): __A : Dict = logging.get_verbosity() __A : str = logging.get_logger('transformers.models.bart.tokenization_bart' ) __A : Optional[Any] = "Testing 1, 2, 3" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(A_ ) as cl: logger.warning(A_ ) self.assertEqual(cl.out , msg + '\n' ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(A_ ) as cl: logger.warning(A_ ) self.assertEqual(cl.out , '' ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(A_ ) as cl: logger.warning(A_ ) self.assertEqual(cl.out , msg + '\n' ) # restore to the original level logging.set_verbosity(A_ ) @mockenv(TRANSFORMERS_VERBOSITY='error' ) def UpperCAmelCase_ ( self ): transformers.utils.logging._reset_library_root_logger() # this action activates the env var __A : List[str] = logging.get_logger('transformers.models.bart.tokenization_bart' ) __A : Tuple = os.getenv('TRANSFORMERS_VERBOSITY' , A_ ) __A : List[str] = logging.log_levels[env_level_str] __A : str = logging.get_verbosity() self.assertEqual( A_ , A_ , F"""TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}""" , ) # restore to the original level __A : Any = "" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY='super-error' ) def UpperCAmelCase_ ( self ): transformers.utils.logging._reset_library_root_logger() __A : Optional[int] = logging.logging.getLogger() with CaptureLogger(A_ ) as cl: # this action activates the env var logging.get_logger('transformers.models.bart.tokenization_bart' ) self.assertIn('Unknown option TRANSFORMERS_VERBOSITY=super-error' , cl.out ) # no need to restore as nothing was changed def UpperCAmelCase_ ( self ): transformers.utils.logging._reset_library_root_logger() __A : Union[str, Any] = logging.get_logger('transformers.models.bart.tokenization_bart' ) __A : List[Any] = "Testing 1, 2, 3" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='1' ): # nothing should be logged as env var disables this method with CaptureLogger(A_ ) as cl: logger.warning_advice(A_ ) self.assertEqual(cl.out , '' ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='' ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(A_ ) as cl: logger.warning_advice(A_ ) self.assertEqual(cl.out , msg + '\n' ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
716
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = ShapEPipeline UpperCamelCase : str = ['''prompt'''] UpperCamelCase : Tuple = ['''prompt'''] UpperCamelCase : Optional[int] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] UpperCamelCase : int = False @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self ): return 8 @property def UpperCAmelCase_ ( self ): __A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_A ) @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : int = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __A : Optional[Any] = PriorTransformer(**_A ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : List[str] = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __A : List[Any] = ShapERenderer(**_A ) return model def UpperCAmelCase_ ( self ): __A : List[str] = self.dummy_prior __A : Optional[int] = self.dummy_text_encoder __A : List[Any] = self.dummy_tokenizer __A : str = self.dummy_renderer __A : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=_A , clip_sample=_A , clip_sample_range=1.0 , ) __A : Any = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): if str(_A ).startswith('mps' ): __A : List[Any] = torch.manual_seed(_A ) else: __A : Dict = torch.Generator(device=_A ).manual_seed(_A ) __A : int = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def UpperCAmelCase_ ( self ): __A : Tuple = 'cpu' __A : Any = self.get_dummy_components() __A : Tuple = self.pipeline_class(**_A ) __A : List[str] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Tuple = pipe(**self.get_dummy_inputs(_A ) ) __A : int = output.images[0] __A : str = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __A : Any = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCAmelCase_ ( self ): __A : List[str] = torch_device == 'cpu' __A : Any = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_A , relax_max_difference=_A , ) def UpperCAmelCase_ ( self ): __A : Any = self.get_dummy_components() __A : Any = self.pipeline_class(**_A ) __A : Dict = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Any = 1 __A : Dict = 2 __A : Tuple = self.get_dummy_inputs(_A ) for key in inputs.keys(): if key in self.batch_params: __A : Optional[int] = batch_size * [inputs[key]] __A : Optional[int] = pipe(**_A , num_images_per_prompt=_A )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __A : Dict = ShapEPipeline.from_pretrained('openai/shap-e' ) __A : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : str = torch.Generator(device=_A ).manual_seed(0 ) __A : Tuple = pipe( 'a shark' , generator=_A , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_A , _A )
77
0
'''simple docstring''' import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py UpperCAmelCase : Dict = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase : List[str] = direct_transformers_import(PATH_TO_TRANSFORMERS) UpperCAmelCase : Optional[int] = transformers.models.auto.configuration_auto.CONFIG_MAPPING UpperCAmelCase : List[Any] = { # used to compute the property `self.chunk_length` '''EncodecConfig''': ['''overlap'''], # used as `self.bert_model = BertModel(config, ...)` '''DPRConfig''': True, # not used in modeling files, but it's an important information '''FSMTConfig''': ['''langs'''], # used internally in the configuration class file '''GPTNeoConfig''': ['''attention_types'''], # used internally in the configuration class file '''EsmConfig''': ['''is_folding_model'''], # used during training (despite we don't have training script for these models yet) '''Mask2FormerConfig''': ['''ignore_value'''], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) '''OneFormerConfig''': ['''ignore_value''', '''norm'''], # used during preprocessing and collation, see `collating_graphormer.py` '''GraphormerConfig''': ['''spatial_pos_max'''], # used internally in the configuration class file '''T5Config''': ['''feed_forward_proj'''], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally '''MT5Config''': ['''feed_forward_proj''', '''tokenizer_class'''], '''UMT5Config''': ['''feed_forward_proj''', '''tokenizer_class'''], # used internally in the configuration class file '''LongT5Config''': ['''feed_forward_proj'''], # used internally in the configuration class file '''SwitchTransformersConfig''': ['''feed_forward_proj'''], # having default values other than `1e-5` - we can't fix them without breaking '''BioGptConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''GLPNConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''SegformerConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''CvtConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''PerceiverConfig''': ['''layer_norm_eps'''], # used internally to calculate the feature size '''InformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate the feature size '''TimeSeriesTransformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate the feature size '''AutoformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate `mlp_dim` '''SamVisionConfig''': ['''mlp_ratio'''], # For (head) training, but so far not implemented '''ClapAudioConfig''': ['''num_classes'''], # Not used, but providing useful information to users '''SpeechT5HifiGanConfig''': ['''sampling_rate'''], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { '''CLIPSegConfig''': True, '''DeformableDetrConfig''': True, '''DetaConfig''': True, '''DinatConfig''': True, '''DonutSwinConfig''': True, '''EfficientFormerConfig''': True, '''FSMTConfig''': True, '''JukeboxConfig''': True, '''LayoutLMv2Config''': True, '''MaskFormerSwinConfig''': True, '''MT5Config''': True, '''NatConfig''': True, '''OneFormerConfig''': True, '''PerceiverConfig''': True, '''RagConfig''': True, '''SpeechT5Config''': True, '''SwinConfig''': True, '''Swin2SRConfig''': True, '''Swinv2Config''': True, '''SwitchTransformersConfig''': True, '''TableTransformerConfig''': True, '''TapasConfig''': True, '''TransfoXLConfig''': True, '''UniSpeechConfig''': True, '''UniSpeechSatConfig''': True, '''WavLMConfig''': True, '''WhisperConfig''': True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) '''JukeboxPriorConfig''': True, # TODO: @Younes (for `is_decoder`) '''Pix2StructTextConfig''': True, } ) def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Tuple: __A : Tuple = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( F"""config.{attribute}""" in modeling_source or F"""getattr(config, \"{attribute}\"""" in modeling_source or F"""getattr(self.config, \"{attribute}\"""" in modeling_source ): __A : Optional[Any] = True # Deal with multi-line cases elif ( re.search( rF"""getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*\"{attribute}\"""" , a , ) is not None ): __A : Tuple = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: __A : Dict = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files __A : Optional[Any] = [ 'bos_index', 'eos_index', 'pad_index', 'unk_index', 'mask_index', 'image_size', 'use_cache', 'out_features', 'out_indices', ] __A : Tuple = ['encoder_no_repeat_ngram_size'] # Special cases to be allowed __A : Tuple = True if not attribute_used: __A : int = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: __A : Any = True elif attribute in ["tie_word_embeddings"] and default_value is False: __A : List[str] = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: __A : Optional[Any] = True elif attribute.endswith('_token_id' ): __A : Optional[Any] = True # configuration class specific cases if not case_allowed: __A : List[Any] = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) __A : Union[str, Any] = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: __A : Any = dict(inspect.signature(config_class.__init__ ).parameters ) __A : Union[str, Any] = [x for x in list(signature.keys() ) if x not in ['self', 'kwargs']] __A : Any = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass __A : Dict = {} if len(config_class.attribute_map ) > 0: __A : List[Any] = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files __A : Optional[Any] = inspect.getsourcefile(a ) __A : Dict = os.path.dirname(a ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. __A : List[str] = [os.path.join(a , a ) for fn in os.listdir(a ) if fn.startswith('modeling_' )] # Get the source code strings __A : List[str] = [] for path in modeling_paths: if os.path.isfile(a ): with open(a ) as fp: modeling_sources.append(fp.read() ) __A : str = [] for config_param, default_value in zip(a , a ): # `attributes` here is all the variant names for `config_param` __A : List[str] = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(a , a , a , a ): unused_attributes.append(attributes[0] ) return sorted(a ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : Dict = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) __A : List[Any] = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda a : inspect.isclass(a ) and issubclass(a , a ) and inspect.getmodule(a ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: __A : int = check_config_attributes_being_used(a ) if len(a ) > 0: __A : List[str] = unused_attributes if len(a ) > 0: __A : Any = 'The following configuration classes contain unused attributes in the corresponding modeling files:\n' for name, attributes in configs_with_unused_attributes.items(): error += F"""{name}: {attributes}\n""" raise ValueError(a ) if __name__ == "__main__": check_config_attributes()
717
from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if len(a ) != 2 or len(a[0] ) != 2 or len(a ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __A : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> str: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a ) -> tuple[list, list, list, list]: if len(a ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __A : str = len(a ) __A : List[Any] = matrix_length // 2 __A : List[str] = [[a[i][j] for j in range(a , a )] for i in range(a )] __A : Dict = [ [a[i][j] for j in range(a , a )] for i in range(a , a ) ] __A : int = [[a[i][j] for j in range(a )] for i in range(a )] __A : Any = [[a[i][j] for j in range(a )] for i in range(a , a )] return top_left, top_right, bot_left, bot_right def _SCREAMING_SNAKE_CASE ( a ) -> tuple[int, int]: return len(a ), len(matrix[0] ) def _SCREAMING_SNAKE_CASE ( a ) -> None: print('\n'.join(str(a ) for line in matrix ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a ) == (2, 2): return default_matrix_multiplication(a , a ) __A , __A , __A , __A : str = split_matrix(a ) __A , __A , __A , __A : List[Any] = split_matrix(a ) __A : Any = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Tuple = actual_strassen(matrix_addition(a , a ) , a ) __A : List[str] = actual_strassen(matrix_addition(a , a ) , a ) __A : Optional[int] = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Any = actual_strassen(matrix_addition(a , a ) , matrix_addition(a , a ) ) __A : Any = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = matrix_addition(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) __A : Union[str, Any] = matrix_addition(a , a ) __A : str = matrix_addition(a , a ) __A : Dict = matrix_subtraction(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) # construct the new matrix from our 4 quadrants __A : List[Any] = [] for i in range(len(a ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(a ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a )[1] != matrix_dimensions(a )[0]: __A : Dict = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"""Matrix A: {matrixa}\n""" F"""Matrix B: {matrixa}""" ) raise Exception(a ) __A : int = matrix_dimensions(a ) __A : Any = matrix_dimensions(a ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __A : List[Any] = max(*a , *a ) __A : Optional[Any] = int(math.pow(2 , math.ceil(math.loga(a ) ) ) ) __A : Union[str, Any] = matrixa __A : Optional[int] = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __A : str = actual_strassen(a , a ) # Removing the additional zeros for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] UpperCAmelCase : Optional[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
77
0
import json import sys def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: with open(__lowerCAmelCase , encoding='utf-8' ) as f: __A : Optional[Any] = json.load(__lowerCAmelCase ) __A : Dict = ["<details>", "<summary>Show updated benchmarks!</summary>", " "] for benchmark_name in sorted(__lowerCAmelCase ): __A : List[Any] = results[benchmark_name] __A : str = benchmark_name.split('/' )[-1] output_md.append(F"""### Benchmark: {benchmark_file_name}""" ) __A : int = "| metric |" __A : Dict = "|--------|" __A : int = "| new / old (diff) |" for metric_name in sorted(__lowerCAmelCase ): __A : Union[str, Any] = benchmark_res[metric_name] __A : Dict = metric_vals["new"] __A : Dict = metric_vals.get('old' , __lowerCAmelCase ) __A : Union[str, Any] = metric_vals.get('diff' , __lowerCAmelCase ) __A : Any = F""" {new_val:f}""" if isinstance(__lowerCAmelCase , (int, float) ) else "None" if old_val is not None: val_str += F""" / {old_val:f}""" if isinstance(__lowerCAmelCase , (int, float) ) else "None" if dif_val is not None: val_str += F""" ({dif_val:f})""" if isinstance(__lowerCAmelCase , (int, float) ) else "None" title += " " + metric_name + " |" lines += "---|" value += val_str + " |" output_md += [title, lines, value, " "] output_md.append('</details>' ) with open(__lowerCAmelCase , 'w' , encoding='utf-8' ) as f: f.writelines('\n'.join(__lowerCAmelCase ) ) if __name__ == "__main__": UpperCAmelCase : Dict = sys.argv[1] UpperCAmelCase : Dict = sys.argv[2] format_json_to_md(input_json_file, output_md_file)
718
def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : List[str] = [] __A : Tuple = [] __A : Union[str, Any] = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, } # Priority of each operator __A : List[str] = len(a ) if (len(a ) > 7) else 7 # Print table header for output print( 'Symbol'.center(8 ) , 'Stack'.center(a ) , 'Postfix'.center(a ) , sep=' | ' , ) print('-' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(a ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(a ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(a ) == 0: stack.append(a ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(a ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(a ) # push x to stack print( x.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format while len(a ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ' '.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format return "".join(a ) # return Postfix as str def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : List[Any] = list(infix[::-1] ) # reverse the infix equation for i in range(len(a ) ): if infix[i] == "(": __A : List[str] = ')' # change "(" to ")" elif infix[i] == ")": __A : Any = '(' # change ")" to "(" return (infix_2_postfix(''.join(a ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": UpperCAmelCase : List[str] = input('''\nEnter an Infix Equation = ''') # Input an Infix equation UpperCAmelCase : Union[str, Any] = ''''''.join(Infix.split()) # Remove spaces from the input print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
77
0
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class _A( __a , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[int] = TextToVideoSDPipeline UpperCamelCase : int = TEXT_TO_IMAGE_PARAMS UpperCamelCase : Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. UpperCamelCase : List[Any] = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Dict = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D') , up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D') , cross_attention_dim=32 , attention_head_dim=4 , ) __A : List[Any] = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' , clip_sample=lowerCAmelCase_ , set_alpha_to_one=lowerCAmelCase_ , ) torch.manual_seed(0 ) __A : int = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __A : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) __A : Union[str, Any] = CLIPTextModel(lowerCAmelCase_ ) __A : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __A : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): if str(lowerCAmelCase_ ).startswith('mps' ): __A : Dict = torch.manual_seed(lowerCAmelCase_ ) else: __A : Dict = torch.Generator(device=lowerCAmelCase_ ).manual_seed(lowerCAmelCase_ ) __A : str = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'pt', } return inputs def UpperCAmelCase_ ( self ): __A : Tuple = 'cpu' # ensure determinism for the device-dependent torch.Generator __A : Any = self.get_dummy_components() __A : int = TextToVideoSDPipeline(**lowerCAmelCase_ ) __A : List[Any] = sd_pipe.to(lowerCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) __A : Union[str, Any] = self.get_dummy_inputs(lowerCAmelCase_ ) __A : List[Any] = 'np' __A : Optional[int] = sd_pipe(**lowerCAmelCase_ ).frames __A : Any = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) __A : int = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowerCAmelCase_ , expected_max_diff=3e-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def UpperCAmelCase_ ( self ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowerCAmelCase_ , expected_max_diff=1e-2 ) @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.' ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): return super().test_progress_bar() @slow @skip_mps class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Optional[Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy' ) __A : Optional[int] = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) __A : Union[str, Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) __A : Any = pipe.to('cuda' ) __A : Union[str, Any] = 'Spiderman is surfing' __A : Dict = torch.Generator(device='cpu' ).manual_seed(0 ) __A : Union[str, Any] = pipe(lowerCAmelCase_ , generator=lowerCAmelCase_ , num_inference_steps=25 , output_type='pt' ).frames __A : int = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2 def UpperCAmelCase_ ( self ): __A : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy' ) __A : str = TextToVideoSDPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b' ) __A : Optional[int] = pipe.to('cuda' ) __A : List[str] = 'Spiderman is surfing' __A : int = torch.Generator(device='cpu' ).manual_seed(0 ) __A : Tuple = pipe(lowerCAmelCase_ , generator=lowerCAmelCase_ , num_inference_steps=2 , output_type='pt' ).frames __A : int = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5e-2
719
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : Tuple = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json''' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase : int = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = '''mask2former''' UpperCamelCase : Any = ['''swin'''] UpperCamelCase : Union[str, Any] = {'''hidden_size''': '''hidden_dim'''} def __init__( self , _A = None , _A = 256 , _A = 256 , _A = 256 , _A = 1024 , _A = "relu" , _A = 6 , _A = 10 , _A = 8 , _A = 0.0 , _A = 2048 , _A = False , _A = False , _A = 4 , _A = 255 , _A = 100 , _A = 0.1 , _A = 2.0 , _A = 5.0 , _A = 5.0 , _A = 12544 , _A = 3.0 , _A = 0.7_5 , _A = 0.0_2 , _A = 1.0 , _A = True , _A = [4, 8, 16, 32] , _A = None , **_A , ): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) __A : Optional[int] = CONFIG_MAPPING['swin']( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=_A , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(_A , _A ): __A : Dict = backbone_config.pop('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[str] = config_class.from_dict(_A ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) __A : Optional[int] = backbone_config __A : Optional[Any] = feature_size __A : Any = mask_feature_size __A : Optional[Any] = hidden_dim __A : Union[str, Any] = encoder_feedforward_dim __A : Optional[Any] = activation_function __A : List[Any] = encoder_layers __A : Union[str, Any] = decoder_layers __A : Dict = num_attention_heads __A : Tuple = dropout __A : Dict = dim_feedforward __A : Tuple = pre_norm __A : Dict = enforce_input_projection __A : Optional[int] = common_stride __A : Optional[Any] = ignore_value __A : str = num_queries __A : List[Any] = no_object_weight __A : List[str] = class_weight __A : List[Any] = mask_weight __A : List[Any] = dice_weight __A : Tuple = train_num_points __A : Optional[Any] = oversample_ratio __A : Union[str, Any] = importance_sample_ratio __A : Union[str, Any] = init_std __A : int = init_xavier_std __A : Union[str, Any] = use_auxiliary_loss __A : Union[str, Any] = feature_strides __A : List[Any] = output_auxiliary_logits __A : Optional[Any] = decoder_layers super().__init__(**_A ) @classmethod def UpperCAmelCase_ ( cls , _A , **_A ): return cls( backbone_config=_A , **_A , ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = copy.deepcopy(self.__dict__ ) __A : List[Any] = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output
77
0
UpperCAmelCase : Dict = [0, 2, 4, 6, 8] UpperCAmelCase : List[Any] = [1, 3, 5, 7, 9] def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> int: if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1 , -1 , -1 ): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 __A : Any = 0 for digit in range(10 ): __A : List[Any] = digit result += reversible_numbers( 0 , (remainder + 2 * digit) // 10 , UpperCamelCase__ , UpperCamelCase__ ) return result __A : Tuple = 0 for digita in range(10 ): __A : str = digita if (remainder + digita) % 2 == 0: __A : Union[str, Any] = ODD_DIGITS else: __A : int = EVEN_DIGITS for digita in other_parity_digits: __A : int = digita result += reversible_numbers( remaining_length - 2 , (remainder + digita + digita) // 10 , UpperCamelCase__ , UpperCamelCase__ , ) return result def _SCREAMING_SNAKE_CASE ( a = 9 ) -> int: __A : Dict = 0 for length in range(1 , max_power + 1 ): result += reversible_numbers(UpperCamelCase__ , 0 , [0] * length , UpperCamelCase__ ) return result if __name__ == "__main__": print(F"""{solution() = }""")
720
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : str = '''conditional_detr''' UpperCamelCase : int = ['''past_key_values'''] UpperCamelCase : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , _A=True , _A=None , _A=3 , _A=300 , _A=6 , _A=2048 , _A=8 , _A=6 , _A=2048 , _A=8 , _A=0.0 , _A=0.0 , _A=True , _A="relu" , _A=256 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1.0 , _A=False , _A="sine" , _A="resnet50" , _A=True , _A=False , _A=2 , _A=5 , _A=2 , _A=1 , _A=1 , _A=2 , _A=5 , _A=2 , _A=0.2_5 , **_A , ): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __A : List[str] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_A , _A ): __A : Tuple = backbone_config.get('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[Any] = config_class.from_dict(_A ) __A : Tuple = use_timm_backbone __A : List[str] = backbone_config __A : Dict = num_channels __A : int = num_queries __A : int = d_model __A : str = encoder_ffn_dim __A : List[str] = encoder_layers __A : Optional[Any] = encoder_attention_heads __A : Union[str, Any] = decoder_ffn_dim __A : List[Any] = decoder_layers __A : Optional[Any] = decoder_attention_heads __A : Any = dropout __A : Any = attention_dropout __A : int = activation_dropout __A : Optional[int] = activation_function __A : Union[str, Any] = init_std __A : Union[str, Any] = init_xavier_std __A : Optional[Any] = encoder_layerdrop __A : int = decoder_layerdrop __A : List[str] = encoder_layers __A : str = auxiliary_loss __A : Union[str, Any] = position_embedding_type __A : Optional[int] = backbone __A : List[str] = use_pretrained_backbone __A : List[Any] = dilation # Hungarian matcher __A : List[str] = class_cost __A : Optional[int] = bbox_cost __A : Dict = giou_cost # Loss coefficients __A : Optional[int] = mask_loss_coefficient __A : Union[str, Any] = dice_loss_coefficient __A : List[Any] = cls_loss_coefficient __A : Dict = bbox_loss_coefficient __A : Tuple = giou_loss_coefficient __A : Tuple = focal_alpha super().__init__(is_encoder_decoder=_A , **_A ) @property def UpperCAmelCase_ ( self ): return self.encoder_attention_heads @property def UpperCAmelCase_ ( self ): return self.d_model def UpperCAmelCase_ ( self ): __A : str = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __A : Dict = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = version.parse('''1.11''' ) @property def UpperCAmelCase_ ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def UpperCAmelCase_ ( self ): return 1e-5 @property def UpperCAmelCase_ ( self ): return 12
77
0
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def _SCREAMING_SNAKE_CASE ( a ) -> Optional[int]: __A : Union[str, Any] = args.pruning_method __A : Optional[Any] = args.threshold __A : Dict = args.model_name_or_path.rstrip('/' ) __A : List[Any] = args.target_model_path print(F"""Load fine-pruned model from {model_name_or_path}""" ) __A : Any = torch.load(os.path.join(_UpperCamelCase , 'pytorch_model.bin' ) ) __A : Union[str, Any] = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: __A : Union[str, Any] = tensor print(F"""Copied layer {name}""" ) elif "classifier" in name or "qa_output" in name: __A : List[Any] = tensor print(F"""Copied layer {name}""" ) elif "bias" in name: __A : Dict = tensor print(F"""Copied layer {name}""" ) else: if pruning_method == "magnitude": __A : str = MagnitudeBinarizer.apply(inputs=_UpperCamelCase , threshold=_UpperCamelCase ) __A : Optional[Any] = tensor * mask print(F"""Pruned layer {name}""" ) elif pruning_method == "topK": if "mask_scores" in name: continue __A : Union[str, Any] = name[:-6] __A : Dict = model[F"""{prefix_}mask_scores"""] __A : int = TopKBinarizer.apply(_UpperCamelCase , _UpperCamelCase ) __A : Union[str, Any] = tensor * mask print(F"""Pruned layer {name}""" ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue __A : int = name[:-6] __A : Tuple = model[F"""{prefix_}mask_scores"""] __A : Union[str, Any] = ThresholdBinarizer.apply(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) __A : Any = tensor * mask print(F"""Pruned layer {name}""" ) elif pruning_method == "l0": if "mask_scores" in name: continue __A : str = name[:-6] __A : str = model[F"""{prefix_}mask_scores"""] __A , __A : List[str] = -0.1, 1.1 __A : str = torch.sigmoid(_UpperCamelCase ) __A : Any = s * (r - l) + l __A : Any = s_bar.clamp(min=0.0 , max=1.0 ) __A : Any = tensor * mask print(F"""Pruned layer {name}""" ) else: raise ValueError('Unknown pruning method' ) if target_model_path is None: __A : List[str] = os.path.join( os.path.dirname(_UpperCamelCase ) , F"""bertarized_{os.path.basename(_UpperCamelCase )}""" ) if not os.path.isdir(_UpperCamelCase ): shutil.copytree(_UpperCamelCase , _UpperCamelCase ) print(F"""\nCreated folder {target_model_path}""" ) torch.save(_UpperCamelCase , os.path.join(_UpperCamelCase , 'pytorch_model.bin' ) ) print('\nPruned model saved! See you later!' ) if __name__ == "__main__": UpperCAmelCase : Optional[int] = argparse.ArgumentParser() parser.add_argument( '''--pruning_method''', choices=['''l0''', '''magnitude''', '''topK''', '''sigmoied_threshold'''], type=str, required=True, help=( '''Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,''' ''' sigmoied_threshold = Soft movement pruning)''' ), ) parser.add_argument( '''--threshold''', type=float, required=False, help=( '''For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.''' '''For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.''' '''Not needed for `l0`''' ), ) parser.add_argument( '''--model_name_or_path''', type=str, required=True, help='''Folder containing the model that was previously fine-pruned''', ) parser.add_argument( '''--target_model_path''', default=None, type=str, required=False, help='''Folder containing the model that was previously fine-pruned''', ) UpperCAmelCase : Union[str, Any] = parser.parse_args() main(args)
721
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _A( nn.Module ): """simple docstring""" def __init__( self ): super().__init__() __A : List[str] = nn.Linear(3 , 4 ) __A : Optional[Any] = nn.BatchNormad(4 ) __A : List[Any] = nn.Linear(4 , 5 ) def UpperCAmelCase_ ( self , _A ): return self.lineara(self.batchnorm(self.lineara(_A ) ) ) class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Dict = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , model.state_dict() ) __A : str = os.path.join(_A , 'index.json' ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: __A : Optional[int] = os.path.join(_A , F"""{key}.dat""" ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on the fact weights are properly loaded def UpperCAmelCase_ ( self ): __A : Dict = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: __A : Tuple = torch.randn(2 , 3 , dtype=_A ) with TemporaryDirectory() as tmp_dir: __A : int = offload_weight(_A , 'weight' , _A , {} ) __A : Union[str, Any] = os.path.join(_A , 'weight.dat' ) self.assertTrue(os.path.isfile(_A ) ) self.assertDictEqual(_A , {'weight': {'shape': [2, 3], 'dtype': str(_A ).split('.' )[1]}} ) __A : List[str] = load_offloaded_weight(_A , index['weight'] ) self.assertTrue(torch.equal(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : int = ModelForTest() __A : Union[str, Any] = model.state_dict() __A : Optional[Any] = {k: v for k, v in state_dict.items() if 'linear2' not in k} __A : str = {k: v for k, v in state_dict.items() if 'linear2' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : List[str] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) __A : Union[str, Any] = {k: v for k, v in state_dict.items() if 'weight' in k} __A : List[Any] = {k: v for k, v in state_dict.items() if 'weight' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : Optional[int] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) # Duplicates are removed __A : str = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) def UpperCAmelCase_ ( self ): __A : Dict = {'a.1': 0, 'a.10': 1, 'a.2': 2} __A : str = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1': 0, 'a.2': 2} ) __A : Optional[Any] = {'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2} __A : Any = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1.a': 0, 'a.2.a': 2} )
77
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy UpperCAmelCase : Optional[int] = logging.get_logger(__name__) class _A( __a ): """simple docstring""" def __init__( self , _A , _A , _A , **_A ): __A : int = feature_size __A : Union[str, Any] = sampling_rate __A : Tuple = padding_value __A : Optional[int] = kwargs.pop('padding_side' , 'right' ) __A : Optional[Any] = kwargs.pop('return_attention_mask' , A__ ) super().__init__(**A__ ) def UpperCAmelCase_ ( self , _A , _A = True , _A = None , _A = False , _A = None , _A = None , _A = None , ): # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(A__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __A : List[str] = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' F""" to this method that includes {self.model_input_names[0]}, but you provided""" F""" {list(processed_features.keys() )}""" ) __A : Optional[int] = processed_features[self.model_input_names[0]] __A : List[str] = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(A__ ) == 0: if return_attention_mask: __A : Dict = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __A : int = required_input[0] if isinstance(A__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __A : Dict = 0 while len(required_input[index] ) == 0: index += 1 if index < len(A__ ): __A : Any = required_input[index][0] if return_tensors is None: if is_tf_tensor(A__ ): __A : str = 'tf' elif is_torch_tensor(A__ ): __A : int = 'pt' elif isinstance(A__ , (int, float, list, tuple, np.ndarray) ): __A : List[Any] = 'np' else: raise ValueError( F"""type of {first_element} unknown: {type(A__ )}. """ 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __A : str = to_numpy(A__ ) else: __A : Union[str, Any] = [to_numpy(A__ ) for v in value] # Convert padding_strategy in PaddingStrategy __A : Optional[int] = self._get_padding_strategies(padding=A__ , max_length=A__ ) __A : Optional[Any] = processed_features[self.model_input_names[0]] __A : str = len(A__ ) if not all(len(A__ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) __A : Any = [] for i in range(A__ ): __A : str = {k: v[i] for k, v in processed_features.items()} # truncation __A : Optional[int] = self._truncate( A__ , max_length=A__ , pad_to_multiple_of=A__ , truncation=A__ , ) truncated_inputs.append(A__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __A : Any = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __A : Tuple = PaddingStrategy.MAX_LENGTH __A : Any = {} for i in range(A__ ): # padding __A : Union[str, Any] = self._pad( truncated_inputs[i] , max_length=A__ , padding_strategy=A__ , pad_to_multiple_of=A__ , return_attention_mask=A__ , ) for key, value in outputs.items(): if key not in batch_outputs: __A : Union[str, Any] = [] if value.dtype is np.dtype(np.floataa ): __A : Union[str, Any] = value.astype(np.floataa ) batch_outputs[key].append(A__ ) return BatchFeature(A__ , tensor_type=A__ ) def UpperCAmelCase_ ( self , _A , _A = None , _A = PaddingStrategy.DO_NOT_PAD , _A = None , _A = None , ): __A : str = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __A : int = len(A__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __A : str = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __A : Tuple = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(A__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __A : Tuple = np.ones(len(A__ ) , dtype=np.intaa ) if needs_to_be_padded: __A : Optional[Any] = max_length - len(A__ ) if self.padding_side == "right": if return_attention_mask: __A : Union[str, Any] = np.pad( processed_features['attention_mask'] , (0, difference) ) __A : Any = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __A : List[str] = np.pad( A__ , A__ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __A : Tuple = np.pad( processed_features['attention_mask'] , (difference, 0) ) __A : List[Any] = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __A : Optional[int] = np.pad( A__ , A__ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def UpperCAmelCase_ ( self , _A , _A = None , _A = None , _A = None , ): if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) __A : int = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __A : Any = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __A : Any = len(A__ ) > max_length if needs_to_be_truncated: __A : int = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __A : Any = processed_features['attention_mask'][:max_length] return processed_features def UpperCAmelCase_ ( self , _A=False , _A=None ): # Get padding strategy if padding is not False: if padding is True: __A : Union[str, Any] = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(A__ , A__ ): __A : Optional[int] = PaddingStrategy(A__ ) elif isinstance(A__ , A__ ): __A : List[str] = padding else: __A : Union[str, Any] = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
700
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): __A : Any = data def __iter__( self ): for element in self.data: yield element def _SCREAMING_SNAKE_CASE ( a=True ) -> Any: __A : List[Any] = Accelerator(even_batches=a ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str: if iterable: __A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) ) else: __A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) ) __A : Optional[Any] = DataLoader(a , batch_size=a ) __A : Optional[int] = accelerator.prepare(a ) return dl def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]: __A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a ) __A : Tuple = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : int = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : str = create_accelerator(even_batches=a ) verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _SCREAMING_SNAKE_CASE ( ) -> str: __A : Optional[Any] = create_accelerator(even_batches=a ) __A : str = torch.nn.Linear(1 , 1 ) __A : Optional[int] = accelerator.prepare(a ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : str = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(a ): __A : Dict = ddp_model(batch[0].float() ) __A : List[str] = output.sum() loss.backward() batch_idxs.append(a ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , a ) assert "only supported for multi-GPU" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : int = True __A : Union[str, Any] = False __A : Optional[int] = create_accelerator(even_batches=a ) __A : int = torch.nn.Linear(1 , 1 ) __A : List[Any] = accelerator.prepare(a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : List[str] = train_dl.batch_sampler.even_batches __A : Dict = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Any = True __A : List[Any] = False __A : Tuple = create_accelerator(even_batches=a ) __A : List[str] = torch.nn.Linear(1 , 1 ) __A : Optional[Any] = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('ignore' ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : Tuple = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Any = create_accelerator() __A : Union[str, Any] = torch.nn.Linear(1 , 1 ) __A : str = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): pass assert issubclass(w[-1].category , a ) assert "only supported for map-style datasets" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : str = create_accelerator() accelerator.print('Test that even_batches variable ensures uniform batches across processes' ) test_default_ensures_even_batch_sizes() accelerator.print('Run tests with even_batches disabled' ) test_can_disable_even_batches() accelerator.print('Test joining uneven inputs' ) test_can_join_uneven_inputs() accelerator.print('Test overriding even_batches when joining uneven inputs' ) test_join_can_override_even_batches() accelerator.print('Test overriding even_batches for mixed dataloader types' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('Test join with non DDP distributed raises warning' ) __A : int = accelerator.state.distributed_type __A : Tuple = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(a ) __A : str = original_state if __name__ == "__main__": main()
77
0
def _SCREAMING_SNAKE_CASE ( a , a ) -> float: return base * power(_SCREAMING_SNAKE_CASE , (exponent - 1) ) if exponent else 1 if __name__ == "__main__": print('''Raise base to the power of exponent using recursion...''') UpperCAmelCase : List[str] = int(input('''Enter the base: ''').strip()) UpperCAmelCase : Tuple = int(input('''Enter the exponent: ''').strip()) UpperCAmelCase : str = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents UpperCAmelCase : Any = 1 / result print(F"""{base} to the power of {exponent} is {result}""")
701
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : str = { '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''', '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''', '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''', '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''', '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''', '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''', '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''', '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''', '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''', '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''', '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''', '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = '''codegen''' UpperCamelCase : List[str] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ): __A : Any = vocab_size __A : Tuple = n_ctx __A : Union[str, Any] = n_positions __A : Optional[Any] = n_embd __A : Any = n_layer __A : Dict = n_head __A : Union[str, Any] = n_inner __A : List[Any] = rotary_dim __A : str = activation_function __A : Any = resid_pdrop __A : Tuple = embd_pdrop __A : Tuple = attn_pdrop __A : Union[str, Any] = layer_norm_epsilon __A : str = initializer_range __A : Optional[Any] = use_cache __A : Union[str, Any] = bos_token_id __A : Tuple = eos_token_id super().__init__( bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A ) class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A = "default" , _A = None , _A = False , ): super().__init__(_A , task=_A , patching_specs=_A , use_past=_A ) if not getattr(self._config , 'pad_token_id' , _A ): # TODO: how to do that better? __A : Dict = 0 @property def UpperCAmelCase_ ( self ): __A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) __A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'} else: __A : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase_ ( self ): return self._config.n_layer @property def UpperCAmelCase_ ( self ): return self._config.n_head def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Any = super(_A , self ).generate_dummy_inputs( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) # We need to order the input in the way they appears in the forward() __A : str = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __A , __A : Any = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Any = seqlen + 2 __A : List[str] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __A : Optional[Any] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] __A : Tuple = common_inputs['attention_mask'] if self.use_past: __A : str = ordered_inputs['attention_mask'].dtype __A : List[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self ): return 13
77
0
from math import sqrt def _SCREAMING_SNAKE_CASE ( a = 1_00_00_00 ) -> Dict: __A : Any = 0 __A : str = 0 __A : List[str] = 42 while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(lowercase__ , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(F"""{solution() = }""")
702
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase : List[Any] = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _A , ) super().__init__(*_A , **_A )
77
0
def _SCREAMING_SNAKE_CASE ( a , a , a=False ) -> Tuple: if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): __A : Union[str, Any] = len(set_a.intersection(lowerCAmelCase_ ) ) if alternative_union: __A : Optional[Any] = len(lowerCAmelCase_ ) + len(lowerCAmelCase_ ) else: __A : List[str] = len(set_a.union(lowerCAmelCase_ ) ) return intersection / union if isinstance(lowerCAmelCase_ , (list, tuple) ) and isinstance(lowerCAmelCase_ , (list, tuple) ): __A : Optional[int] = [element for element in set_a if element in set_b] if alternative_union: __A : int = len(lowerCAmelCase_ ) + len(lowerCAmelCase_ ) return len(lowerCAmelCase_ ) / union else: __A : List[str] = set_a + [element for element in set_b if element not in set_a] return len(lowerCAmelCase_ ) / len(lowerCAmelCase_ ) return len(lowerCAmelCase_ ) / len(lowerCAmelCase_ ) return None if __name__ == "__main__": UpperCAmelCase : str = {'a', 'b', 'c', 'd', 'e'} UpperCAmelCase : Tuple = {'c', 'd', 'e', 'f', 'h', 'i'} print(jaccard_similarity(set_a, set_b))
703
import glob import os import random from string import ascii_lowercase, digits import cva UpperCAmelCase : Dict = '''''' UpperCAmelCase : Union[str, Any] = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal) def _SCREAMING_SNAKE_CASE ( ) -> None: __A , __A : List[Any] = get_dataset(a , a ) print('Processing...' ) __A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a ) for index, image in enumerate(a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __A : Optional[int] = random_chars(32 ) __A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] __A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Success {index+1}/{len(a )} with {file_name}""" ) __A : int = [] for anno in new_annos[index]: __A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(a ) with open(F"""/{file_root}.txt""" , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]: __A : int = [] __A : List[Any] = [] for label_file in glob.glob(os.path.join(a , '*.txt' ) ): __A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(a ) as in_file: __A : Tuple = in_file.readlines() __A : Dict = os.path.join(a , F"""{label_name}.jpg""" ) __A : Dict = [] for obj_list in obj_lists: __A : int = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(a ) labels.append(a ) return img_paths, labels def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]: __A : int = [] __A : Optional[Any] = [] __A : Dict = [] for idx in range(len(a ) ): __A : Dict = [] __A : Optional[Any] = img_list[idx] path_list.append(a ) __A : Union[str, Any] = anno_list[idx] __A : Optional[Any] = cva.imread(a ) if flip_type == 1: __A : Any = cva.flip(a , a ) for bbox in img_annos: __A : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __A : Union[str, Any] = cva.flip(a , a ) for bbox in img_annos: __A : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(a ) new_imgs_list.append(a ) return new_imgs_list, new_annos_lists, path_list def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __A : List[Any] = ascii_lowercase + digits return "".join(random.choice(a ) for _ in range(a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
77
0
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class _A( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): """simple docstring""" UpperCamelCase : int = StableUnCLIPPipeline UpperCamelCase : Union[str, Any] = TEXT_TO_IMAGE_PARAMS UpperCamelCase : Any = TEXT_TO_IMAGE_BATCH_PARAMS UpperCamelCase : Optional[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS UpperCamelCase : Any = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false UpperCamelCase : Optional[Any] = False def UpperCAmelCase_ ( self ): __A : List[str] = 32 __A : List[str] = embedder_hidden_size # prior components torch.manual_seed(0 ) __A : Optional[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) __A : Union[str, Any] = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=lowercase__ , projection_dim=lowercase__ , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) __A : Union[str, Any] = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=lowercase__ , num_layers=1 , ) torch.manual_seed(0 ) __A : List[Any] = DDPMScheduler( variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1000 , clip_sample=lowercase__ , clip_sample_range=5.0 , beta_schedule='squaredcos_cap_v2' , ) # regular denoising components torch.manual_seed(0 ) __A : int = StableUnCLIPImageNormalizer(embedding_dim=lowercase__ ) __A : List[Any] = DDPMScheduler(beta_schedule='squaredcos_cap_v2' ) torch.manual_seed(0 ) __A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) __A : Optional[int] = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=lowercase__ , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) __A : Union[str, Any] = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=lowercase__ , layers_per_block=1 , upcast_attention=lowercase__ , use_linear_projection=lowercase__ , ) torch.manual_seed(0 ) __A : str = DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , prediction_type='v_prediction' , set_alpha_to_one=lowercase__ , steps_offset=1 , ) torch.manual_seed(0 ) __A : List[Any] = AutoencoderKL() __A : Union[str, Any] = { # prior components """prior_tokenizer""": prior_tokenizer, """prior_text_encoder""": prior_text_encoder, """prior""": prior, """prior_scheduler""": prior_scheduler, # image noising components """image_normalizer""": image_normalizer, """image_noising_scheduler""": image_noising_scheduler, # regular denoising components """tokenizer""": tokenizer, """text_encoder""": text_encoder, """unet""": unet, """scheduler""": scheduler, """vae""": vae, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): if str(lowercase__ ).startswith('mps' ): __A : Optional[Any] = torch.manual_seed(lowercase__ ) else: __A : List[Any] = torch.Generator(device=lowercase__ ).manual_seed(lowercase__ ) __A : Dict = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """prior_num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def UpperCAmelCase_ ( self ): __A : int = torch_device == """cpu""" self._test_attention_slicing_forward_pass(test_max_difference=lowercase__ ) def UpperCAmelCase_ ( self ): __A : Any = torch_device in ["""cpu""", """mps"""] self._test_inference_batch_single_identical(test_max_difference=lowercase__ ) @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : Optional[Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy' ) __A : Dict = StableUnCLIPPipeline.from_pretrained('fusing/stable-unclip-2-1-l' , torch_dtype=torch.floataa ) pipe.to(lowercase__ ) pipe.set_progress_bar_config(disable=lowercase__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __A : int = torch.Generator(device='cpu' ).manual_seed(0 ) __A : List[str] = pipe('anime turle' , generator=lowercase__ , output_type='np' ) __A : Tuple = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowercase__ , lowercase__ ) def UpperCAmelCase_ ( self ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __A : List[Any] = StableUnCLIPPipeline.from_pretrained('fusing/stable-unclip-2-1-l' , torch_dtype=torch.floataa ) __A : Tuple = pipe.to(lowercase__ ) pipe.set_progress_bar_config(disable=lowercase__ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __A : Optional[int] = pipe( 'anime turtle' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='np' , ) __A : Tuple = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
704
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A: """simple docstring""" def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=True , _A=False , _A=True , _A=99 , _A=32 , _A=5 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=16 , _A=2 , _A=0.0_2 , _A=3 , _A=4 , _A=None , ): __A : Union[str, Any] = parent __A : List[str] = batch_size __A : Optional[int] = seq_length __A : List[Any] = is_training __A : Optional[Any] = use_input_mask __A : List[Any] = use_token_type_ids __A : Optional[Any] = use_labels __A : List[str] = vocab_size __A : Optional[int] = hidden_size __A : List[Any] = num_hidden_layers __A : int = num_attention_heads __A : Dict = intermediate_size __A : Any = hidden_act __A : Union[str, Any] = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : Optional[int] = max_position_embeddings __A : Dict = type_vocab_size __A : Any = type_sequence_label_size __A : Dict = initializer_range __A : str = num_labels __A : Union[str, Any] = num_choices __A : str = scope def UpperCAmelCase_ ( self ): __A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : Optional[Any] = None if self.use_input_mask: __A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __A : Dict = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = None __A : List[Any] = None __A : List[Any] = None if self.use_labels: __A : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __A : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[str] = LlamaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A , attention_mask=_A ) __A : Any = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Dict = True __A : int = LlamaModel(_A ) model.to(_A ) model.eval() __A : str = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __A : int = model( _A , attention_mask=_A , encoder_hidden_states=_A , ) __A : List[Any] = model(_A , attention_mask=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Optional[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : int = True __A : List[Any] = True __A : List[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() # first forward pass __A : Optional[Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , ) __A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __A : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) __A : str = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __A : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : str = torch.cat([input_mask, next_mask] , dim=-1 ) __A : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['hidden_states'][0] __A : Union[str, Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , past_key_values=_A , output_hidden_states=_A , )['hidden_states'][0] # select random slice __A : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() __A : Tuple = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_A , _A , atol=1e-3 ) ) def UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Tuple = config_and_inputs __A : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () UpperCamelCase : Optional[Any] = (LlamaForCausalLM,) if is_torch_available() else () UpperCamelCase : Optional[Any] = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False def UpperCAmelCase_ ( self ): __A : List[Any] = LlamaModelTester(self ) __A : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : int = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() __A : str = 3 __A : Optional[int] = input_dict['input_ids'] __A : int = input_ids.ne(1 ).to(_A ) __A : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Union[str, Any] = 3 __A : Tuple = 'single_label_classification' __A : Union[str, Any] = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[int] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Any = 3 __A : int = 'multi_label_classification' __A : int = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __A : List[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def UpperCAmelCase_ ( self ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def UpperCAmelCase_ ( self , _A ): __A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Dict = ids_tensor([1, 10] , config.vocab_size ) __A : Union[str, Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : List[Any] = LlamaModel(_A ) original_model.to(_A ) original_model.eval() __A : Dict = original_model(_A ).last_hidden_state __A : int = original_model(_A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : int = {'type': scaling_type, 'factor': 1_0.0} __A : str = LlamaModel(_A ) scaled_model.to(_A ) scaled_model.eval() __A : Dict = scaled_model(_A ).last_hidden_state __A : str = scaled_model(_A ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(_A , _A , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) __A : Union[str, Any] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __A : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[str] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) __A : int = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) __A : Optional[int] = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : Optional[Any] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) __A : List[Any] = model(torch.tensor(_A ) ) __A : Tuple = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # fmt: off __A : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' __A : List[str] = 'Simply put, the theory of relativity states that ' __A : Union[str, Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) __A : List[str] = tokenizer.encode(_A , return_tensors='pt' ) __A : Tuple = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=_A ) # greedy generation outputs __A : Union[str, Any] = model.generate(_A , max_new_tokens=64 , top_p=_A , temperature=1 , do_sample=_A ) __A : List[str] = tokenizer.decode(generated_ids[0] , skip_special_tokens=_A ) self.assertEqual(_A , _A )
77
0
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right UpperCAmelCase : Optional[int] = 25_00_04 UpperCAmelCase : List[str] = 25_00_20 @require_sentencepiece @require_tokenizers class _A( __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" UpperCamelCase : Union[str, Any] = MBartaaTokenizer UpperCamelCase : List[Any] = MBartaaTokenizerFast UpperCamelCase : List[Any] = True UpperCamelCase : Optional[int] = True def UpperCAmelCase_ ( self ): super().setUp() # We have a SentencePiece fixture for testing __A : Optional[int] = MBartaaTokenizer(__snake_case , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=__snake_case ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : int = '''<s>''' __A : int = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__snake_case ) , __snake_case ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__snake_case ) , __snake_case ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(__snake_case ) , 1054 ) def UpperCAmelCase_ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1054 ) def UpperCAmelCase_ ( self ): __A : List[Any] = MBartaaTokenizer(__snake_case , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=__snake_case ) __A : List[str] = tokenizer.tokenize('This is a test' ) self.assertListEqual(__snake_case , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__snake_case ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __A : List[str] = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __snake_case , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.'] , ) __A : Tuple = tokenizer.convert_tokens_to_ids(__snake_case ) self.assertListEqual( __snake_case , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __A : str = tokenizer.convert_ids_to_tokens(__snake_case ) self.assertListEqual( __snake_case , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] , ) @slow def UpperCAmelCase_ ( self ): # fmt: off __A : Optional[Any] = {'''input_ids''': [[250004, 11062, 82772, 7, 15, 82772, 538, 51529, 237, 17198, 1290, 206, 9, 215175, 1314, 136, 17198, 1290, 206, 9, 56359, 42, 122009, 9, 16466, 16, 87344, 4537, 9, 4717, 78381, 6, 159958, 7, 15, 24480, 618, 4, 527, 22693, 5428, 4, 2777, 24480, 9874, 4, 43523, 594, 4, 803, 18392, 33189, 18, 4, 43523, 24447, 12399, 100, 24955, 83658, 9626, 144057, 15, 839, 22335, 16, 136, 24955, 83658, 83479, 15, 39102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 122009, 115774, 23, 805, 1328, 46876, 7, 136, 53894, 1940, 42227, 41159, 17721, 823, 425, 4, 27512, 98722, 206, 136, 5531, 4970, 919, 17336, 5, 2], [250004, 20080, 618, 83, 82775, 47, 479, 9, 1517, 73, 53894, 333, 80581, 110117, 18811, 5256, 1295, 51, 152526, 297, 7986, 390, 124416, 538, 35431, 214, 98, 15044, 25737, 136, 7108, 43701, 23, 756, 135355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [250004, 581, 63773, 119455, 6, 147797, 88203, 7, 645, 70, 21, 3285, 10269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__snake_case , model_name='facebook/mbart-large-50' , revision='d3913889c59cd5c9e456b269c376325eabad57e2' , ) def UpperCAmelCase_ ( self ): if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return __A : Optional[Any] = (self.rust_tokenizer_class, '''hf-internal-testing/tiny-random-mbart50''', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __A : Tuple = self.rust_tokenizer_class.from_pretrained(__snake_case , **__snake_case ) __A : Tuple = self.tokenizer_class.from_pretrained(__snake_case , **__snake_case ) __A : int = tempfile.mkdtemp() __A : Union[str, Any] = tokenizer_r.save_pretrained(__snake_case ) __A : List[Any] = tokenizer_p.save_pretrained(__snake_case ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) __A : Union[str, Any] = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(__snake_case , __snake_case ) # Checks everything loads correctly in the same way __A : Any = tokenizer_r.from_pretrained(__snake_case ) __A : Any = tokenizer_p.from_pretrained(__snake_case ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__snake_case , __snake_case ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__snake_case ) # Save tokenizer rust, legacy_format=True __A : Union[str, Any] = tempfile.mkdtemp() __A : List[Any] = tokenizer_r.save_pretrained(__snake_case , legacy_format=__snake_case ) __A : List[str] = tokenizer_p.save_pretrained(__snake_case ) # Checks it save with the same files self.assertSequenceEqual(__snake_case , __snake_case ) # Checks everything loads correctly in the same way __A : Union[str, Any] = tokenizer_r.from_pretrained(__snake_case ) __A : Tuple = tokenizer_p.from_pretrained(__snake_case ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__snake_case , __snake_case ) ) shutil.rmtree(__snake_case ) # Save tokenizer rust, legacy_format=False __A : Optional[Any] = tempfile.mkdtemp() __A : Optional[Any] = tokenizer_r.save_pretrained(__snake_case , legacy_format=__snake_case ) __A : Optional[Any] = tokenizer_p.save_pretrained(__snake_case ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __A : Dict = tokenizer_r.from_pretrained(__snake_case ) __A : List[Any] = tokenizer_p.from_pretrained(__snake_case ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__snake_case , __snake_case ) ) shutil.rmtree(__snake_case ) @require_torch @require_sentencepiece @require_tokenizers class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = '''facebook/mbart-large-50-one-to-many-mmt''' UpperCamelCase : Any = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] UpperCamelCase : Any = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] UpperCamelCase : Tuple = [EN_CODE, 8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2] @classmethod def UpperCAmelCase_ ( cls ): __A : MBartaaTokenizer = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) __A : str = 1 return cls def UpperCAmelCase_ ( self ): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 250020 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['mr_IN'] , 250038 ) def UpperCAmelCase_ ( self ): __A : Dict = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __snake_case ) def UpperCAmelCase_ ( self ): self.assertIn(__snake_case , self.tokenizer.all_special_ids ) __A : Tuple = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] __A : List[str] = self.tokenizer.decode(__snake_case , skip_special_tokens=__snake_case ) __A : Any = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__snake_case ) self.assertEqual(__snake_case , __snake_case ) self.assertNotIn(self.tokenizer.eos_token , __snake_case ) def UpperCAmelCase_ ( self ): __A : Any = ['''this is gunna be a long sentence ''' * 20] assert isinstance(src_text[0] , __snake_case ) __A : Any = 10 __A : List[str] = self.tokenizer(__snake_case , max_length=__snake_case , truncation=__snake_case ).input_ids[0] self.assertEqual(ids[0] , __snake_case ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(__snake_case ) , __snake_case ) def UpperCAmelCase_ ( self ): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [250053, 250001] ) def UpperCAmelCase_ ( self ): __A : Any = tempfile.mkdtemp() __A : List[Any] = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__snake_case ) __A : List[str] = MBartaaTokenizer.from_pretrained(__snake_case ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __snake_case ) @require_torch def UpperCAmelCase_ ( self ): __A : Dict = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__snake_case , return_tensors='pt' ) __A : Optional[Any] = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__snake_case , truncation=__snake_case , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) __A : Any = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) __A : Union[str, Any] = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __snake_case ) self.assertEqual(2 , batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase_ ( self ): __A : int = self.tokenizer(self.src_text , padding=__snake_case , truncation=__snake_case , max_length=3 , return_tensors='pt' ) __A : Tuple = self.tokenizer( text_target=self.tgt_text , padding=__snake_case , truncation=__snake_case , max_length=10 , return_tensors='pt' ) __A : Optional[Any] = targets['''input_ids'''] __A : List[str] = shift_tokens_right(__snake_case , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(__snake_case ) , { # en_XX, A, test, EOS 'input_ids': [[250004, 62, 3034, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 250001, } , )
705
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
0
import math def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : Any = [True] * n __A : Tuple = False __A : str = False __A : Tuple = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): __A : Optional[Any] = i * 2 while index < n: __A : Optional[Any] = False __A : str = index + i __A : Dict = [2] for i in range(3 , a , 2 ): if is_prime[i]: primes.append(a ) return primes def _SCREAMING_SNAKE_CASE ( a = 99_99_66_66_33_33 ) -> Tuple: __A : Optional[Any] = math.floor(math.sqrt(a ) ) + 1_00 __A : Any = prime_sieve(a ) __A : List[str] = 0 __A : Optional[int] = 0 __A : List[str] = primes[prime_index] while (last_prime**2) <= limit: __A : Any = primes[prime_index + 1] __A : Union[str, Any] = last_prime**2 __A : str = next_prime**2 # Get numbers divisible by lps(current) __A : Any = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __A : Any = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __A : Any = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __A : Optional[Any] = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
706
import numpy as np from PIL import Image def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : Union[str, Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : List[Any] = 0 __A : Optional[Any] = 0 __A : List[Any] = 0 __A : Dict = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __A : Tuple = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : List[str] = 0 __A : Union[str, Any] = 0 return updated_arr def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : List[Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : Dict = 0 __A : str = 0 __A : Tuple = 0 __A : Optional[int] = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __A : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : Dict = 0 __A : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image UpperCAmelCase : int = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
77
0
def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> int: __A : Any = len(lowercase_ ), len(grid[0] ) if ( min(lowercase_ , lowercase_ ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) __A : Union[str, Any] = 0 count += depth_first_search(lowercase_ , row + 1 , lowercase_ , lowercase_ ) count += depth_first_search(lowercase_ , row - 1 , lowercase_ , lowercase_ ) count += depth_first_search(lowercase_ , lowercase_ , col + 1 , lowercase_ ) count += depth_first_search(lowercase_ , lowercase_ , col - 1 , lowercase_ ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
707
from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float: __A : Any = x_start __A : List[str] = fnc(a ) __A : Optional[Any] = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area __A : Any = (x_end - x_start) / steps + xa __A : List[str] = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __A : Any = xa __A : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( a ) -> int: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') UpperCAmelCase : Tuple = 10 while i <= 10_00_00: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
77
0
import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class _A( UpperCAmelCase_ ): """simple docstring""" UpperCamelCase : Union[str, Any] = (UnCLIPScheduler,) def UpperCAmelCase_ ( self , **_A ): __A : List[Any] = { 'num_train_timesteps': 1000, 'variance_type': 'fixed_small_log', 'clip_sample': True, 'clip_sample_range': 1.0, 'prediction_type': 'epsilon', } config.update(**_snake_case ) return config def UpperCAmelCase_ ( self ): for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=_snake_case ) def UpperCAmelCase_ ( self ): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=_snake_case ) def UpperCAmelCase_ ( self ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=_snake_case ) def UpperCAmelCase_ ( self ): for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=_snake_case ) def UpperCAmelCase_ ( self ): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=_snake_case ) def UpperCAmelCase_ ( self ): for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=_snake_case , prev_timestep=_snake_case ) def UpperCAmelCase_ ( self ): __A : int = self.scheduler_classes[0] __A : int = self.get_scheduler_config(variance_type='fixed_small_log' ) __A : Dict = scheduler_class(**_snake_case ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0_0_0_0e-1_0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_5_4_9_6_2_5 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.9_9_9_4_9_8_7 ) ) < 1e-5 def UpperCAmelCase_ ( self ): __A : Any = self.scheduler_classes[0] __A : Any = self.get_scheduler_config(variance_type='learned_range' ) __A : List[str] = scheduler_class(**_snake_case ) __A : List[str] = 0.5 assert scheduler._get_variance(1 , predicted_variance=_snake_case ) - -1_0.1_7_1_2_7_9_0 < 1e-5 assert scheduler._get_variance(487 , predicted_variance=_snake_case ) - -5.7_9_9_8_0_5_2 < 1e-5 assert scheduler._get_variance(999 , predicted_variance=_snake_case ) - -0.0_0_1_0_0_1_1 < 1e-5 def UpperCAmelCase_ ( self ): __A : List[str] = self.scheduler_classes[0] __A : Optional[Any] = self.get_scheduler_config() __A : str = scheduler_class(**_snake_case ) __A : List[Any] = scheduler.timesteps __A : Tuple = self.dummy_model() __A : Dict = self.dummy_sample_deter __A : Dict = torch.manual_seed(0 ) for i, t in enumerate(_snake_case ): # 1. predict noise residual __A : List[Any] = model(_snake_case , _snake_case ) # 2. predict previous mean of sample x_t-1 __A : Tuple = scheduler.step(_snake_case , _snake_case , _snake_case , generator=_snake_case ).prev_sample __A : Any = pred_prev_sample __A : Union[str, Any] = torch.sum(torch.abs(_snake_case ) ) __A : Union[str, Any] = torch.mean(torch.abs(_snake_case ) ) assert abs(result_sum.item() - 2_5_2.2_6_8_2_4_9_5 ) < 1e-2 assert abs(result_mean.item() - 0.3_2_8_4_7_4_3 ) < 1e-3 def UpperCAmelCase_ ( self ): __A : int = self.scheduler_classes[0] __A : int = self.get_scheduler_config() __A : Optional[int] = scheduler_class(**_snake_case ) scheduler.set_timesteps(25 ) __A : Union[str, Any] = scheduler.timesteps __A : Tuple = self.dummy_model() __A : List[str] = self.dummy_sample_deter __A : List[str] = torch.manual_seed(0 ) for i, t in enumerate(_snake_case ): # 1. predict noise residual __A : Optional[Any] = model(_snake_case , _snake_case ) if i + 1 == timesteps.shape[0]: __A : str = None else: __A : Optional[Any] = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __A : Tuple = scheduler.step( _snake_case , _snake_case , _snake_case , prev_timestep=_snake_case , generator=_snake_case ).prev_sample __A : Dict = pred_prev_sample __A : Optional[int] = torch.sum(torch.abs(_snake_case ) ) __A : str = torch.mean(torch.abs(_snake_case ) ) assert abs(result_sum.item() - 2_5_8.2_0_4_4_9_8_3 ) < 1e-2 assert abs(result_mean.item() - 0.3_3_6_2_0_3_8 ) < 1e-3 def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): pass
708
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def _SCREAMING_SNAKE_CASE ( ) -> None: print('Making key files...' ) make_key_files('rsa' , 10_24 ) print('Key files generation successful.' ) def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]: print('Generating prime p...' ) __A : Optional[Any] = rabinMiller.generate_large_prime(a ) print('Generating prime q...' ) __A : Union[str, Any] = rabinMiller.generate_large_prime(a ) __A : Tuple = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...' ) while True: __A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1: break print('Calculating d that is mod inverse of e...' ) __A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) ) __A : Dict = (n, e) __A : Dict = (n, d) return (public_key, private_key) def _SCREAMING_SNAKE_CASE ( a , a ) -> 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() __A , __A : Optional[int] = generate_key(a ) 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()
77
0
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Tuple: __A : List[Any] = checkpoint __A : Union[str, Any] = {} __A : Tuple = vae_state_dict['encoder.conv_in.weight'] __A : Dict = vae_state_dict['encoder.conv_in.bias'] __A : Union[str, Any] = vae_state_dict['encoder.conv_out.weight'] __A : Optional[Any] = vae_state_dict['encoder.conv_out.bias'] __A : int = vae_state_dict['encoder.norm_out.weight'] __A : int = vae_state_dict['encoder.norm_out.bias'] __A : Any = vae_state_dict['decoder.conv_in.weight'] __A : int = vae_state_dict['decoder.conv_in.bias'] __A : Tuple = vae_state_dict['decoder.conv_out.weight'] __A : Union[str, Any] = vae_state_dict['decoder.conv_out.bias'] __A : List[Any] = vae_state_dict['decoder.norm_out.weight'] __A : str = vae_state_dict['decoder.norm_out.bias'] __A : Union[str, Any] = vae_state_dict['quant_conv.weight'] __A : Dict = vae_state_dict['quant_conv.bias'] __A : List[str] = vae_state_dict['post_quant_conv.weight'] __A : Optional[int] = vae_state_dict['post_quant_conv.bias'] # Retrieves the keys for the encoder down blocks only __A : Optional[int] = len({'.'.join(layer.split('.' )[:3] ) for layer in vae_state_dict if 'encoder.down' in layer} ) __A : Optional[Any] = { layer_id: [key for key in vae_state_dict if F"""down.{layer_id}""" in key] for layer_id in range(a ) } # Retrieves the keys for the decoder up blocks only __A : int = len({'.'.join(layer.split('.' )[:3] ) for layer in vae_state_dict if 'decoder.up' in layer} ) __A : List[Any] = { layer_id: [key for key in vae_state_dict if F"""up.{layer_id}""" in key] for layer_id in range(a ) } for i in range(a ): __A : Optional[int] = [key for key in down_blocks[i] if F"""down.{i}""" in key and F"""down.{i}.downsample""" not in key] if F"""encoder.down.{i}.downsample.conv.weight""" in vae_state_dict: __A : Dict = vae_state_dict.pop( F"""encoder.down.{i}.downsample.conv.weight""" ) __A : Union[str, Any] = vae_state_dict.pop( F"""encoder.down.{i}.downsample.conv.bias""" ) __A : Dict = renew_vae_resnet_paths(a ) __A : str = {'old': F"""down.{i}.block""", 'new': F"""down_blocks.{i}.resnets"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) __A : List[Any] = [key for key in vae_state_dict if 'encoder.mid.block' in key] __A : Any = 2 for i in range(1 , num_mid_res_blocks + 1 ): __A : Optional[Any] = [key for key in mid_resnets if F"""encoder.mid.block_{i}""" in key] __A : Tuple = renew_vae_resnet_paths(a ) __A : List[str] = {'old': F"""mid.block_{i}""", 'new': F"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) __A : Dict = [key for key in vae_state_dict if 'encoder.mid.attn' in key] __A : Optional[Any] = renew_vae_attention_paths(a ) __A : Dict = {'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) for i in range(a ): __A : Any = num_up_blocks - 1 - i __A : List[str] = [ key for key in up_blocks[block_id] if F"""up.{block_id}""" in key and F"""up.{block_id}.upsample""" not in key ] if F"""decoder.up.{block_id}.upsample.conv.weight""" in vae_state_dict: __A : int = vae_state_dict[ F"""decoder.up.{block_id}.upsample.conv.weight""" ] __A : str = vae_state_dict[ F"""decoder.up.{block_id}.upsample.conv.bias""" ] __A : int = renew_vae_resnet_paths(a ) __A : List[str] = {'old': F"""up.{block_id}.block""", 'new': F"""up_blocks.{i}.resnets"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) __A : Any = [key for key in vae_state_dict if 'decoder.mid.block' in key] __A : Union[str, Any] = 2 for i in range(1 , num_mid_res_blocks + 1 ): __A : Optional[Any] = [key for key in mid_resnets if F"""decoder.mid.block_{i}""" in key] __A : Union[str, Any] = renew_vae_resnet_paths(a ) __A : Dict = {'old': F"""mid.block_{i}""", 'new': F"""mid_block.resnets.{i - 1}"""} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) __A : List[Any] = [key for key in vae_state_dict if 'decoder.mid.attn' in key] __A : Union[str, Any] = renew_vae_attention_paths(a ) __A : int = {'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'} assign_to_checkpoint(a , a , a , additional_replacements=[meta_path] , config=a ) conv_attn_to_linear(a ) return new_checkpoint def _SCREAMING_SNAKE_CASE ( a , a , ) -> List[str]: __A : List[str] = requests.get( ' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml' ) __A : Any = io.BytesIO(r.content ) __A : List[Any] = OmegaConf.load(a ) __A : Tuple = 5_12 __A : Union[str, Any] = 'cuda' if torch.cuda.is_available() else 'cpu' if checkpoint_path.endswith('safetensors' ): from safetensors import safe_open __A : List[str] = {} with safe_open(a , framework='pt' , device='cpu' ) as f: for key in f.keys(): __A : Optional[int] = f.get_tensor(a ) else: __A : Any = torch.load(a , map_location=a )['state_dict'] # Convert the VAE model. __A : Tuple = create_vae_diffusers_config(a , image_size=a ) __A : Optional[int] = custom_convert_ldm_vae_checkpoint(a , a ) __A : int = AutoencoderKL(**a ) vae.load_state_dict(a ) vae.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument('''--vae_pt_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''') parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''') UpperCAmelCase : Tuple = parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
709
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ProphetNetTokenizer UpperCamelCase : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() __A : Any = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = 'UNwant\u00E9d,running' __A : List[str] = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class(self.vocab_file ) __A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase_ ( self ): __A : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCAmelCase_ ( self ): __A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __A : Optional[int] = {} for i, token in enumerate(_A ): __A : Tuple = i __A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __A : str = tokenizer(_A , padding=_A , return_tensors='pt' ) self.assertIsInstance(_A , _A ) __A : List[str] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A ) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A ) __A : str = tokenizer.build_inputs_with_special_tokens(_A ) __A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
77
0
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : Dict = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def UpperCAmelCase_ ( self , _A , _A , _A ): __A : Union[str, Any] = hf_hub_download( repo_id='nateraw/video-demo' , filename='archery.mp4' , repo_type='dataset' ) __A : int = VideoClassificationPipeline(model=_a , image_processor=_a , top_k=2 ) __A : Dict = [ example_video_filepath, """https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4""", ] return video_classifier, examples def UpperCAmelCase_ ( self , _A , _A ): for example in examples: __A : Dict = video_classifier(_a ) self.assertEqual( _a , [ {'score': ANY(_a ), 'label': ANY(_a )}, {'score': ANY(_a ), 'label': ANY(_a )}, ] , ) @require_torch def UpperCAmelCase_ ( self ): __A : Optional[int] = """hf-internal-testing/tiny-random-VideoMAEForVideoClassification""" __A : Union[str, Any] = VideoMAEFeatureExtractor( size={'shortest_edge': 10} , crop_size={'height': 10, 'width': 10} ) __A : Dict = pipeline( 'video-classification' , model=_a , feature_extractor=_a , frame_sampling_rate=4 ) __A : List[Any] = hf_hub_download(repo_id='nateraw/video-demo' , filename='archery.mp4' , repo_type='dataset' ) __A : Dict = video_classifier(_a , top_k=2 ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}] , ) __A : Optional[Any] = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ [{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}], [{'score': 0.5_1_9_9, 'label': 'LABEL_0'}, {'score': 0.4_8_0_1, 'label': 'LABEL_1'}], ] , ) @require_tf def UpperCAmelCase_ ( self ): pass
710
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Optional[int] = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } UpperCAmelCase : List[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = BertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : Any = getattr(_A , normalizer_state.pop('type' ) ) __A : Union[str, Any] = do_lower_case __A : Optional[int] = strip_accents __A : List[Any] = tokenize_chinese_chars __A : int = normalizer_class(**_A ) __A : Union[str, Any] = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : Tuple = [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 UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[Any] = [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : int = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor from ..utils import is_datasets_available from .base import PipelineTool if is_datasets_available(): from datasets import load_dataset class _A( SCREAMING_SNAKE_CASE_ ): """simple docstring""" UpperCamelCase : int = '''microsoft/speecht5_tts''' UpperCamelCase : int = ( '''This is a tool that reads an English text out loud. It takes an input named `text` which should contain the ''' '''text to read (in English) and returns a waveform object containing the sound.''' ) UpperCamelCase : Dict = '''text_reader''' UpperCamelCase : List[str] = SpeechTaProcessor UpperCamelCase : Tuple = SpeechTaForTextToSpeech UpperCamelCase : List[Any] = SpeechTaHifiGan UpperCamelCase : Optional[Any] = ['''text'''] UpperCamelCase : int = ['''audio'''] def UpperCAmelCase_ ( self ): if self.post_processor is None: __A : int = '''microsoft/speecht5_hifigan''' super().setup() def UpperCAmelCase_ ( self , _A , _A=None ): __A : List[Any] = self.pre_processor(text=UpperCamelCase__ , return_tensors='pt' , truncation=UpperCamelCase__ ) if speaker_embeddings is None: if not is_datasets_available(): raise ImportError('Datasets needs to be installed if not passing speaker embeddings.' ) __A : List[Any] = load_dataset('Matthijs/cmu-arctic-xvectors' , split='validation' ) __A : Dict = torch.tensor(embeddings_dataset[7305]['xvector'] ).unsqueeze(0 ) return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings} def UpperCAmelCase_ ( self , _A ): with torch.no_grad(): return self.model.generate_speech(**UpperCamelCase__ ) def UpperCAmelCase_ ( self , _A ): with torch.no_grad(): return self.post_processor(UpperCamelCase__ ).cpu().detach()
711
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 UpperCAmelCase_ ( self ): debug_launcher(test_script.main ) def UpperCAmelCase_ ( self ): debug_launcher(test_ops.main )
77
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase : Tuple = { '''configuration_nezha''': ['''NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NezhaConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[int] = [ '''NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''NezhaForNextSentencePrediction''', '''NezhaForMaskedLM''', '''NezhaForPreTraining''', '''NezhaForMultipleChoice''', '''NezhaForQuestionAnswering''', '''NezhaForSequenceClassification''', '''NezhaForTokenClassification''', '''NezhaModel''', '''NezhaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nezha import ( NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, NezhaPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
712
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Tuple = tempfile.mkdtemp() # fmt: off __A : Union[str, Any] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Dict = dict(zip(_A , range(len(_A ) ) ) ) __A : int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : Optional[Any] = {'unk_token': '<unk>'} __A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : Union[str, Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : List[str] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[str] = self.get_tokenizer() __A : Dict = self.get_rust_tokenizer() __A : Optional[Any] = self.get_image_processor() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Any = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : int = self.get_image_processor(do_normalize=_A ) __A : int = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : List[Any] = self.prepare_image_inputs() __A : Any = image_processor(_A , return_tensors='np' ) __A : Tuple = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_image_processor() __A : int = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = 'lower newer' __A : Any = processor(text=_A , return_tensors='np' ) __A : Dict = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Tuple = 'lower newer' __A : Union[str, Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[int] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Any = ['cat', 'nasa badge'] __A : List[Any] = processor(text=_A ) __A : Dict = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : int = [['cat', 'nasa badge'], ['person']] __A : str = processor(text=_A ) __A : int = 16 __A : Optional[int] = len(_A ) __A : int = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : int = 'google/owlvit-base-patch32' __A : List[str] = OwlViTProcessor.from_pretrained(_A ) __A : Tuple = ['cat', 'nasa badge'] __A : Dict = processor(text=_A ) __A : Tuple = 16 __A : str = inputs['input_ids'] __A : str = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Dict = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = self.prepare_image_inputs() __A : Tuple = self.prepare_image_inputs() __A : Any = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Union[str, Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
77
0
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : str = [ "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(__snake_case , __snake_case ) def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : Optional[int] = emb.weight.shape __A : Any = nn.Linear(__snake_case , __snake_case , bias=__snake_case ) __A : Dict = emb.weight.data return lin_layer def _SCREAMING_SNAKE_CASE ( a , a=None ) -> List[Any]: __A : Any = {} for old_key in state_dict.keys(): __A : Union[str, Any] = old_key if "moe_layer.experts." in key: if expert_idx is not None: __A : Union[str, Any] = key.replace('moe_layer.experts.0' , F"""ffn.experts.expert_{expert_idx}""" ) else: __A : Dict = key.replace('moe_layer.experts.' , 'ffn.experts.expert_' ) if "gate" in key: __A : Optional[int] = key.replace('.moe_layer.gate.wg' , '.ffn.router.classifier' ) if "fc2" and "experts" not in key: __A : int = key.replace('.fc2.' , '.ffn.fc2.' ) if "fc1" and "experts" not in key: __A : Union[str, Any] = key.replace('.fc1.' , '.ffn.fc1.' ) if ".encoder_attn." in key: __A : List[Any] = key.replace('.encoder_attn.' , '.cross_attention.' ) if "encoder_attn_layer_norm" in key: __A : Optional[Any] = key.replace('encoder_attn_layer_norm' , 'cross_attention_layer_norm' ) if "final_layer_norm" in key: __A : Optional[int] = key.replace('final_layer_norm' , 'ff_layer_norm' ) __A : Optional[int] = state_dict[old_key] return new_dict def _SCREAMING_SNAKE_CASE ( a , a , a , a , a = WEIGHTS_NAME ) -> List[Any]: __A : Union[str, Any] = [] __A : Union[str, Any] = 0 os.makedirs(__snake_case , exist_ok=__snake_case ) for expert in range(__snake_case ): __A : Optional[Any] = switch_checkpoint_path + F"""-rank-{expert}.pt""" if os.path.isfile(__snake_case ): __A : Optional[int] = torch.load(__snake_case )["model"] remove_ignore_keys_(__snake_case ) __A : Dict = rename_fairseq_keys(__snake_case , __snake_case ) __A : Optional[int] = os.path.join( __snake_case , weights_name.replace('.bin' , F"""-{len(__snake_case )+1:05d}-of-???.bin""" ) ) torch.save(__snake_case , __snake_case ) sharded_state_dicts.append(expert_state.keys() ) total_size += sum([value.numel() for key, value in expert_state.items()] ) * dtype_byte_size( expert_state[list(__snake_case )[0]].dtype ) # Add the last block __A : List[Any] = os.path.join(__snake_case , weights_name.replace('.bin' , F"""-{len(__snake_case )+1:05d}-of-???.bin""" ) ) __A : List[Any] = torch.load(switch_checkpoint_path + '-shared.pt' )["model"] remove_ignore_keys_(__snake_case ) __A : Optional[Any] = rename_fairseq_keys(__snake_case , __snake_case ) __A : int = shared_weights["decoder.embed_tokens.weight"] sharded_state_dicts.append(shared_weights.keys() ) # If we only have the shared weights (dummy model/experts saved on the same file) if len(__snake_case ) == 1: __A : int = os.path.join(__snake_case , __snake_case ) torch.save(__snake_case , __snake_case ) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(__snake_case , __snake_case ) # Otherwise, let's build the index __A : Any = {} for idx, shard in enumerate(__snake_case ): __A : Optional[Any] = weights_name.replace('.bin' , F"""-{idx+1:05d}-of-{len(__snake_case ):05d}.bin""" ) __A : List[Any] = os.path.join(__snake_case , weights_name.replace('.bin' , F"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(__snake_case , os.path.join(__snake_case , __snake_case ) ) for key in shard: __A : Optional[int] = shard_file # Add the metadata __A : Tuple = {"total_size": total_size} __A : Optional[Any] = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(__snake_case , __snake_case ) , 'w' , encoding='utf-8' ) as f: __A : List[Any] = json.dumps(__snake_case , indent=2 , sort_keys=__snake_case ) + "\n" f.write(__snake_case ) return metadata, index if __name__ == "__main__": UpperCAmelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--nllb_moe_checkpoint_path''', default='''/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000''', type=str, required=False, help='''Path to a directory containing a folder per layer. Follows the original Google format.''', ) parser.add_argument('''--dtype''', default='''float32''', type=str, required=False, help='''dtype of the saved model''') parser.add_argument( '''--pytorch_dump_folder_path''', default='''/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b''', type=str, required=False, help='''Path to the output pytorch model.''', ) UpperCAmelCase : Optional[int] = parser.parse_args() UpperCAmelCase : Any = shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 1_28, args.dtype, ) UpperCAmelCase : int = NllbMoeConfig.from_pretrained( '''facebook/nllb-200-3.3B''', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=1_28 ) config.save_pretrained(args.pytorch_dump_folder_path) UpperCAmelCase : List[Any] = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print('''Done''') model.save_pretrained(args.pytorch_dump_folder_path)
713
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase : Union[str, Any] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Tuple: for attribute in key.split('.' ): __A : Dict = getattr(a , a ) if weight_type is not None: __A : Any = getattr(a , a ).shape else: __A : Any = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __A : Union[str, Any] = value elif weight_type == "weight_g": __A : Dict = value elif weight_type == "weight_v": __A : Optional[int] = value elif weight_type == "bias": __A : int = value elif weight_type == "running_mean": __A : Union[str, Any] = value elif weight_type == "running_var": __A : Union[str, Any] = value elif weight_type == "num_batches_tracked": __A : Any = value elif weight_type == "inv_freq": __A : Optional[Any] = value else: __A : int = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]: __A : Any = [] __A : Optional[int] = fairseq_model.state_dict() __A : Union[str, Any] = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __A : int = False if "conv_layers" in name: load_conv_layer( a , a , a , a , hf_model.config.feat_extract_norm == 'group' , ) __A : Optional[int] = True else: for key, mapped_key in MAPPING.items(): __A : Any = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __A : Optional[Any] = True if "*" in mapped_key: __A : str = name.split(a )[0].split('.' )[-2] __A : int = mapped_key.replace('*' , a ) if "pos_bias_u" in name: __A : Optional[int] = None elif "pos_bias_v" in name: __A : Dict = None elif "weight_g" in name: __A : Optional[Any] = 'weight_g' elif "weight_v" in name: __A : Dict = 'weight_v' elif "bias" in name: __A : Tuple = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __A : int = 'weight' elif "running_mean" in name: __A : str = 'running_mean' elif "inv_freq" in name: __A : List[Any] = 'inv_freq' elif "running_var" in name: __A : Union[str, Any] = 'running_var' elif "num_batches_tracked" in name: __A : Optional[Any] = 'num_batches_tracked' else: __A : List[str] = None set_recursively(a , a , a , a , a ) continue if not is_used: unused_weights.append(a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Any: __A : str = full_name.split('conv_layers.' )[-1] __A : str = name.split('.' ) __A : Dict = int(items[0] ) __A : Any = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) __A : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) __A : List[str] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a ) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a=None , a=None , a=True ) -> Any: if config_path is not None: __A : Tuple = WavaVecaConformerConfig.from_pretrained(a , hidden_act='swish' ) else: __A : Optional[Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: __A : Dict = 'rotary' if is_finetuned: if dict_path: __A : Dict = Dictionary.load(a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __A : int = target_dict.pad_index __A : List[Any] = target_dict.bos_index __A : Any = target_dict.eos_index __A : Dict = len(target_dict.symbols ) __A : Optional[Any] = os.path.join(a , 'vocab.json' ) if not os.path.isdir(a ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(a ) ) return os.makedirs(a , exist_ok=a ) __A : List[str] = target_dict.indices # fairseq has the <pad> and <s> switched __A : int = 0 __A : Optional[Any] = 1 with open(a , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(a , a ) __A : Optional[Any] = WavaVecaCTCTokenizer( a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=a , ) __A : Tuple = True if config.feat_extract_norm == 'layer' else False __A : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=a , return_attention_mask=a , ) __A : Optional[int] = WavaVecaProcessor(feature_extractor=a , tokenizer=a ) processor.save_pretrained(a ) __A : List[Any] = WavaVecaConformerForCTC(a ) else: __A : List[Any] = WavaVecaConformerForPreTraining(a ) if is_finetuned: __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: __A : Optional[Any] = argparse.Namespace(task='audio_pretraining' ) __A : str = fairseq.tasks.setup_task(a ) __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=a ) __A : Tuple = model[0].eval() recursively_load_weights(a , a , not is_finetuned ) hf_wavavec.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) UpperCAmelCase : List[str] = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
77
0
def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Any: def update_area_of_max_square(a , a ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 __A : Tuple = update_area_of_max_square(a__ , col + 1 ) __A : Optional[int] = update_area_of_max_square(row + 1 , col + 1 ) __A : List[str] = update_area_of_max_square(row + 1 , a__ ) if mat[row][col]: __A : List[str] = 1 + min([right, diagonal, down] ) __A : str = max(largest_square_area[0] , a__ ) return sub_problem_sol else: return 0 __A : Union[str, Any] = [0] update_area_of_max_square(0 , 0 ) return largest_square_area[0] def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Any: def update_area_of_max_square_using_dp_array( a , a , a ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] __A : Optional[int] = update_area_of_max_square_using_dp_array(a__ , col + 1 , a__ ) __A : Dict = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , a__ ) __A : Tuple = update_area_of_max_square_using_dp_array(row + 1 , a__ , a__ ) if mat[row][col]: __A : List[str] = 1 + min([right, diagonal, down] ) __A : List[str] = max(largest_square_area[0] , a__ ) __A : Any = sub_problem_sol return sub_problem_sol else: return 0 __A : Tuple = [0] __A : Any = [[-1] * cols for _ in range(a__ )] update_area_of_max_square_using_dp_array(0 , 0 , a__ ) return largest_square_area[0] def _SCREAMING_SNAKE_CASE ( a , a , a ) -> int: __A : Tuple = [[0] * (cols + 1) for _ in range(rows + 1 )] __A : List[str] = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): __A : int = dp_array[row][col + 1] __A : Any = dp_array[row + 1][col + 1] __A : int = dp_array[row + 1][col] if mat[row][col] == 1: __A : str = 1 + min(a__ , a__ , a__ ) __A : List[str] = max(dp_array[row][col] , a__ ) else: __A : str = 0 return largest_square_area def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Optional[Any]: __A : Union[str, Any] = [0] * (cols + 1) __A : List[Any] = [0] * (cols + 1) __A : List[Any] = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): __A : Union[str, Any] = current_row[col + 1] __A : Dict = next_row[col + 1] __A : Optional[int] = next_row[col] if mat[row][col] == 1: __A : Any = 1 + min(a__ , a__ , a__ ) __A : List[str] = max(current_row[col] , a__ ) else: __A : Any = 0 __A : Dict = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
714
from abc import ABC, abstractmethod from argparse import ArgumentParser class _A( snake_case__ ): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( _A ): raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self ): raise NotImplementedError()
77
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class _A( UpperCamelCase__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = '''Salesforce/blip-image-captioning-base''' UpperCamelCase : List[Any] = ( '''This is a tool that generates a description of an image. It takes an input named `image` which should be the ''' '''image to caption, and returns a text that contains the description in English.''' ) UpperCamelCase : List[Any] = '''image_captioner''' UpperCamelCase : List[str] = AutoModelForVisionaSeq UpperCamelCase : Union[str, Any] = ['''image'''] UpperCamelCase : Optional[int] = ['''text'''] def __init__( self , *_A , **_A ): requires_backends(self , ['vision'] ) super().__init__(*__A , **__A ) def UpperCAmelCase_ ( self , _A ): return self.pre_processor(images=__A , return_tensors='pt' ) def UpperCAmelCase_ ( self , _A ): return self.model.generate(**__A ) def UpperCAmelCase_ ( self , _A ): return self.pre_processor.batch_decode(__A , skip_special_tokens=__A )[0].strip()
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
0
def _SCREAMING_SNAKE_CASE ( a ) -> Dict: return " ".join( ''.join(word[::-1] ) if len(_UpperCAmelCase ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('''Hey wollef sroirraw'''))
716
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = ShapEPipeline UpperCamelCase : str = ['''prompt'''] UpperCamelCase : Tuple = ['''prompt'''] UpperCamelCase : Optional[int] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] UpperCamelCase : int = False @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self ): return 8 @property def UpperCAmelCase_ ( self ): __A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_A ) @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : int = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __A : Optional[Any] = PriorTransformer(**_A ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : List[str] = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __A : List[Any] = ShapERenderer(**_A ) return model def UpperCAmelCase_ ( self ): __A : List[str] = self.dummy_prior __A : Optional[int] = self.dummy_text_encoder __A : List[Any] = self.dummy_tokenizer __A : str = self.dummy_renderer __A : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=_A , clip_sample=_A , clip_sample_range=1.0 , ) __A : Any = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): if str(_A ).startswith('mps' ): __A : List[Any] = torch.manual_seed(_A ) else: __A : Dict = torch.Generator(device=_A ).manual_seed(_A ) __A : int = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def UpperCAmelCase_ ( self ): __A : Tuple = 'cpu' __A : Any = self.get_dummy_components() __A : Tuple = self.pipeline_class(**_A ) __A : List[str] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Tuple = pipe(**self.get_dummy_inputs(_A ) ) __A : int = output.images[0] __A : str = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __A : Any = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCAmelCase_ ( self ): __A : List[str] = torch_device == 'cpu' __A : Any = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_A , relax_max_difference=_A , ) def UpperCAmelCase_ ( self ): __A : Any = self.get_dummy_components() __A : Any = self.pipeline_class(**_A ) __A : Dict = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Any = 1 __A : Dict = 2 __A : Tuple = self.get_dummy_inputs(_A ) for key in inputs.keys(): if key in self.batch_params: __A : Optional[int] = batch_size * [inputs[key]] __A : Optional[int] = pipe(**_A , num_images_per_prompt=_A )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __A : Dict = ShapEPipeline.from_pretrained('openai/shap-e' ) __A : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : str = torch.Generator(device=_A ).manual_seed(0 ) __A : Tuple = pipe( 'a shark' , generator=_A , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_A , _A )
77
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : Any = { '''configuration_distilbert''': [ '''DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DistilBertConfig''', '''DistilBertOnnxConfig''', ], '''tokenization_distilbert''': ['''DistilBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = ['''DistilBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Tuple = [ '''DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DistilBertForMaskedLM''', '''DistilBertForMultipleChoice''', '''DistilBertForQuestionAnswering''', '''DistilBertForSequenceClassification''', '''DistilBertForTokenClassification''', '''DistilBertModel''', '''DistilBertPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Dict = [ '''TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDistilBertForMaskedLM''', '''TFDistilBertForMultipleChoice''', '''TFDistilBertForQuestionAnswering''', '''TFDistilBertForSequenceClassification''', '''TFDistilBertForTokenClassification''', '''TFDistilBertMainLayer''', '''TFDistilBertModel''', '''TFDistilBertPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ '''FlaxDistilBertForMaskedLM''', '''FlaxDistilBertForMultipleChoice''', '''FlaxDistilBertForQuestionAnswering''', '''FlaxDistilBertForSequenceClassification''', '''FlaxDistilBertForTokenClassification''', '''FlaxDistilBertModel''', '''FlaxDistilBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys UpperCAmelCase : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
717
from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if len(a ) != 2 or len(a[0] ) != 2 or len(a ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __A : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> str: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a ) -> tuple[list, list, list, list]: if len(a ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __A : str = len(a ) __A : List[Any] = matrix_length // 2 __A : List[str] = [[a[i][j] for j in range(a , a )] for i in range(a )] __A : Dict = [ [a[i][j] for j in range(a , a )] for i in range(a , a ) ] __A : int = [[a[i][j] for j in range(a )] for i in range(a )] __A : Any = [[a[i][j] for j in range(a )] for i in range(a , a )] return top_left, top_right, bot_left, bot_right def _SCREAMING_SNAKE_CASE ( a ) -> tuple[int, int]: return len(a ), len(matrix[0] ) def _SCREAMING_SNAKE_CASE ( a ) -> None: print('\n'.join(str(a ) for line in matrix ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a ) == (2, 2): return default_matrix_multiplication(a , a ) __A , __A , __A , __A : str = split_matrix(a ) __A , __A , __A , __A : List[Any] = split_matrix(a ) __A : Any = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Tuple = actual_strassen(matrix_addition(a , a ) , a ) __A : List[str] = actual_strassen(matrix_addition(a , a ) , a ) __A : Optional[int] = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Any = actual_strassen(matrix_addition(a , a ) , matrix_addition(a , a ) ) __A : Any = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = matrix_addition(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) __A : Union[str, Any] = matrix_addition(a , a ) __A : str = matrix_addition(a , a ) __A : Dict = matrix_subtraction(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) # construct the new matrix from our 4 quadrants __A : List[Any] = [] for i in range(len(a ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(a ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a )[1] != matrix_dimensions(a )[0]: __A : Dict = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"""Matrix A: {matrixa}\n""" F"""Matrix B: {matrixa}""" ) raise Exception(a ) __A : int = matrix_dimensions(a ) __A : Any = matrix_dimensions(a ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __A : List[Any] = max(*a , *a ) __A : Optional[Any] = int(math.pow(2 , math.ceil(math.loga(a ) ) ) ) __A : Union[str, Any] = matrixa __A : Optional[int] = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __A : str = actual_strassen(a , a ) # Removing the additional zeros for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] UpperCAmelCase : Optional[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
77
0
import argparse import struct import unittest class _A: """simple docstring""" def __init__( self , _A ): __A : List[Any] = data # Initialize hash values __A : int = [ 0X6A_09E_667, 0XBB_67A_E85, 0X3C_6EF_372, 0XA5_4FF_53A, 0X51_0E5_27F, 0X9B_056_88C, 0X1F_83D_9AB, 0X5B_E0C_D19, ] # Initialize round constants __A : Optional[int] = [ 0X42_8A2_F98, 0X71_374_491, 0XB5_C0F_BCF, 0XE9_B5D_BA5, 0X39_56C_25B, 0X59_F11_1F1, 0X92_3F8_2A4, 0XAB_1C5_ED5, 0XD8_07A_A98, 0X12_835_B01, 0X24_318_5BE, 0X55_0C7_DC3, 0X72_BE5_D74, 0X80_DEB_1FE, 0X9B_DC0_6A7, 0XC1_9BF_174, 0XE4_9B6_9C1, 0XEF_BE4_786, 0X0F_C19_DC6, 0X24_0CA_1CC, 0X2D_E92_C6F, 0X4A_748_4AA, 0X5C_B0A_9DC, 0X76_F98_8DA, 0X98_3E5_152, 0XA8_31C_66D, 0XB0_032_7C8, 0XBF_597_FC7, 0XC6_E00_BF3, 0XD5_A79_147, 0X06_CA6_351, 0X14_292_967, 0X27_B70_A85, 0X2E_1B2_138, 0X4D_2C6_DFC, 0X53_380_D13, 0X65_0A7_354, 0X76_6A0_ABB, 0X81_C2C_92E, 0X92_722_C85, 0XA2_BFE_8A1, 0XA8_1A6_64B, 0XC2_4B8_B70, 0XC7_6C5_1A3, 0XD1_92E_819, 0XD6_990_624, 0XF4_0E3_585, 0X10_6AA_070, 0X19_A4C_116, 0X1E_376_C08, 0X27_487_74C, 0X34_B0B_CB5, 0X39_1C0_CB3, 0X4E_D8A_A4A, 0X5B_9CC_A4F, 0X68_2E6_FF3, 0X74_8F8_2EE, 0X78_A56_36F, 0X84_C87_814, 0X8C_C70_208, 0X90_BEF_FFA, 0XA4_506_CEB, 0XBE_F9A_3F7, 0XC6_717_8F2, ] __A : List[str] = self.preprocessing(self.data ) self.final_hash() @staticmethod def UpperCAmelCase_ ( _A ): __A : List[str] = b'\x80' + (b'\x00' * (63 - (len(__A ) + 8) % 64)) __A : Union[str, Any] = struct.pack('>Q' , (len(__A ) * 8) ) return data + padding + big_endian_integer def UpperCAmelCase_ ( self ): # Convert into blocks of 64 bytes __A : str = [ self.preprocessed_data[x : x + 64] for x in range(0 , len(self.preprocessed_data ) , 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __A : Union[str, Any] = list(struct.unpack('>16L' , __A ) ) # add 48 0-ed integers words += [0] * 48 __A , __A , __A , __A , __A , __A , __A , __A : Dict = self.hashes for index in range(0 , 64 ): if index > 15: # modify the zero-ed indexes at the end of the array __A : Optional[int] = ( self.ror(words[index - 15] , 7 ) ^ self.ror(words[index - 15] , 18 ) ^ (words[index - 15] >> 3) ) __A : int = ( self.ror(words[index - 2] , 17 ) ^ self.ror(words[index - 2] , 19 ) ^ (words[index - 2] >> 10) ) __A : Dict = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X100_000_000 # Compression __A : str = self.ror(__A , 6 ) ^ self.ror(__A , 11 ) ^ self.ror(__A , 25 ) __A : str = (e & f) ^ ((~e & 0XFF_FFF_FFF) & g) __A : Optional[Any] = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X100_000_000 __A : Optional[int] = self.ror(__A , 2 ) ^ self.ror(__A , 13 ) ^ self.ror(__A , 22 ) __A : List[Any] = (a & b) ^ (a & c) ^ (b & c) __A : Any = (sa + maj) % 0X100_000_000 __A , __A , __A , __A , __A , __A , __A , __A : Union[str, Any] = ( g, f, e, ((d + tempa) % 0X100_000_000), c, b, a, ((tempa + tempa) % 0X100_000_000), ) __A : Any = [a, b, c, d, e, f, g, h] # Modify final values __A : Dict = [ ((element + mutated_hash_values[index]) % 0X100_000_000) for index, element in enumerate(self.hashes ) ] __A : Tuple = ''.join([hex(__A )[2:].zfill(8 ) for value in self.hashes] ) def UpperCAmelCase_ ( self , _A , _A ): return 0XFF_FFF_FFF & (value << (32 - rotations)) | (value >> rotations) class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): import hashlib __A : Union[str, Any] = bytes('Test String' , 'utf-8' ) self.assertEqual(SHAaaa(__A ).hash , hashlib.shaaaa(__A ).hexdigest() ) def _SCREAMING_SNAKE_CASE ( ) -> Dict: import doctest doctest.testmod() __A : Dict = argparse.ArgumentParser() parser.add_argument( '-s' , '--string' , dest='input_string' , default='Hello World!! Welcome to Cryptography' , help='Hash the string' , ) parser.add_argument( '-f' , '--file' , dest='input_file' , help='Hash contents of a file' ) __A : List[str] = parser.parse_args() __A : Optional[int] = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , 'rb' ) as f: __A : Dict = f.read() else: __A : Dict = bytes(_lowercase , 'utf-8' ) print(SHAaaa(_lowercase ).hash ) if __name__ == "__main__": main()
718
def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : List[str] = [] __A : Tuple = [] __A : Union[str, Any] = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, } # Priority of each operator __A : List[str] = len(a ) if (len(a ) > 7) else 7 # Print table header for output print( 'Symbol'.center(8 ) , 'Stack'.center(a ) , 'Postfix'.center(a ) , sep=' | ' , ) print('-' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(a ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(a ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(a ) == 0: stack.append(a ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(a ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(a ) # push x to stack print( x.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format while len(a ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ' '.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format return "".join(a ) # return Postfix as str def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : List[Any] = list(infix[::-1] ) # reverse the infix equation for i in range(len(a ) ): if infix[i] == "(": __A : List[str] = ')' # change "(" to ")" elif infix[i] == ")": __A : Any = '(' # change ")" to "(" return (infix_2_postfix(''.join(a ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": UpperCAmelCase : List[str] = input('''\nEnter an Infix Equation = ''') # Input an Infix equation UpperCAmelCase : Union[str, Any] = ''''''.join(Infix.split()) # Remove spaces from the input print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
77
0
def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Any: return round(float(moles / volume ) * nfactor ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Optional[Any]: return round(float((moles * 0.0_821 * temperature) / (volume) ) ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> List[Any]: return round(float((moles * 0.0_821 * temperature) / (pressure) ) ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> int: return round(float((pressure * volume) / (0.0_821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
719
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : Tuple = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json''' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase : int = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = '''mask2former''' UpperCamelCase : Any = ['''swin'''] UpperCamelCase : Union[str, Any] = {'''hidden_size''': '''hidden_dim'''} def __init__( self , _A = None , _A = 256 , _A = 256 , _A = 256 , _A = 1024 , _A = "relu" , _A = 6 , _A = 10 , _A = 8 , _A = 0.0 , _A = 2048 , _A = False , _A = False , _A = 4 , _A = 255 , _A = 100 , _A = 0.1 , _A = 2.0 , _A = 5.0 , _A = 5.0 , _A = 12544 , _A = 3.0 , _A = 0.7_5 , _A = 0.0_2 , _A = 1.0 , _A = True , _A = [4, 8, 16, 32] , _A = None , **_A , ): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) __A : Optional[int] = CONFIG_MAPPING['swin']( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=_A , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(_A , _A ): __A : Dict = backbone_config.pop('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[str] = config_class.from_dict(_A ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) __A : Optional[int] = backbone_config __A : Optional[Any] = feature_size __A : Any = mask_feature_size __A : Optional[Any] = hidden_dim __A : Union[str, Any] = encoder_feedforward_dim __A : Optional[Any] = activation_function __A : List[Any] = encoder_layers __A : Union[str, Any] = decoder_layers __A : Dict = num_attention_heads __A : Tuple = dropout __A : Dict = dim_feedforward __A : Tuple = pre_norm __A : Dict = enforce_input_projection __A : Optional[int] = common_stride __A : Optional[Any] = ignore_value __A : str = num_queries __A : List[Any] = no_object_weight __A : List[str] = class_weight __A : List[Any] = mask_weight __A : List[Any] = dice_weight __A : Tuple = train_num_points __A : Optional[Any] = oversample_ratio __A : Union[str, Any] = importance_sample_ratio __A : Union[str, Any] = init_std __A : int = init_xavier_std __A : Union[str, Any] = use_auxiliary_loss __A : Union[str, Any] = feature_strides __A : List[Any] = output_auxiliary_logits __A : Optional[Any] = decoder_layers super().__init__(**_A ) @classmethod def UpperCAmelCase_ ( cls , _A , **_A ): return cls( backbone_config=_A , **_A , ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = copy.deepcopy(self.__dict__ ) __A : List[Any] = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output
77
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _A( snake_case__ ): """simple docstring""" UpperCamelCase : int = '''facebook/bart-large-mnli''' UpperCamelCase : Tuple = ( '''This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ''' '''should be the text to classify, and `labels`, which should be the list of labels to use for classification. ''' '''It returns the most likely label in the list of provided `labels` for the input text.''' ) UpperCamelCase : Dict = '''text_classifier''' UpperCamelCase : Optional[Any] = AutoTokenizer UpperCamelCase : List[Any] = AutoModelForSequenceClassification UpperCamelCase : List[Any] = ['''text''', ['''text''']] UpperCamelCase : Optional[Any] = ['''text'''] def UpperCAmelCase_ ( self ): super().setup() __A : List[str] = self.model.config __A : List[str] = -1 for idx, label in config.idalabel.items(): if label.lower().startswith('entail' ): __A : str = int(A__ ) if self.entailment_id == -1: raise ValueError('Could not determine the entailment ID from the model config, please pass it at init.' ) def UpperCAmelCase_ ( self , _A , _A ): __A : Tuple = labels return self.pre_processor( [text] * len(A__ ) , [F"""This example is {label}""" for label in labels] , return_tensors='pt' , padding='max_length' , ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = outputs.logits __A : int = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
720
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : str = '''conditional_detr''' UpperCamelCase : int = ['''past_key_values'''] UpperCamelCase : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , _A=True , _A=None , _A=3 , _A=300 , _A=6 , _A=2048 , _A=8 , _A=6 , _A=2048 , _A=8 , _A=0.0 , _A=0.0 , _A=True , _A="relu" , _A=256 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1.0 , _A=False , _A="sine" , _A="resnet50" , _A=True , _A=False , _A=2 , _A=5 , _A=2 , _A=1 , _A=1 , _A=2 , _A=5 , _A=2 , _A=0.2_5 , **_A , ): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __A : List[str] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_A , _A ): __A : Tuple = backbone_config.get('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[Any] = config_class.from_dict(_A ) __A : Tuple = use_timm_backbone __A : List[str] = backbone_config __A : Dict = num_channels __A : int = num_queries __A : int = d_model __A : str = encoder_ffn_dim __A : List[str] = encoder_layers __A : Optional[Any] = encoder_attention_heads __A : Union[str, Any] = decoder_ffn_dim __A : List[Any] = decoder_layers __A : Optional[Any] = decoder_attention_heads __A : Any = dropout __A : Any = attention_dropout __A : int = activation_dropout __A : Optional[int] = activation_function __A : Union[str, Any] = init_std __A : Union[str, Any] = init_xavier_std __A : Optional[Any] = encoder_layerdrop __A : int = decoder_layerdrop __A : List[str] = encoder_layers __A : str = auxiliary_loss __A : Union[str, Any] = position_embedding_type __A : Optional[int] = backbone __A : List[str] = use_pretrained_backbone __A : List[Any] = dilation # Hungarian matcher __A : List[str] = class_cost __A : Optional[int] = bbox_cost __A : Dict = giou_cost # Loss coefficients __A : Optional[int] = mask_loss_coefficient __A : Union[str, Any] = dice_loss_coefficient __A : List[Any] = cls_loss_coefficient __A : Dict = bbox_loss_coefficient __A : Tuple = giou_loss_coefficient __A : Tuple = focal_alpha super().__init__(is_encoder_decoder=_A , **_A ) @property def UpperCAmelCase_ ( self ): return self.encoder_attention_heads @property def UpperCAmelCase_ ( self ): return self.d_model def UpperCAmelCase_ ( self ): __A : str = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __A : Dict = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = version.parse('''1.11''' ) @property def UpperCAmelCase_ ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def UpperCAmelCase_ ( self ): return 1e-5 @property def UpperCAmelCase_ ( self ): return 12
77
0
import re def _SCREAMING_SNAKE_CASE ( a ) -> bool: __A : List[str] = re.compile( r'^(?:0|94|\+94|0{2}94)' r'7(0|1|2|4|5|6|7|8)' r'(-| |)' r'\d{7}$' ) return bool(re.search(lowerCAmelCase__ , lowerCAmelCase__ ) ) if __name__ == "__main__": UpperCAmelCase : Any = '''0094702343221''' print(is_sri_lankan_phone_number(phone))
721
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _A( nn.Module ): """simple docstring""" def __init__( self ): super().__init__() __A : List[str] = nn.Linear(3 , 4 ) __A : Optional[Any] = nn.BatchNormad(4 ) __A : List[Any] = nn.Linear(4 , 5 ) def UpperCAmelCase_ ( self , _A ): return self.lineara(self.batchnorm(self.lineara(_A ) ) ) class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Dict = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , model.state_dict() ) __A : str = os.path.join(_A , 'index.json' ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: __A : Optional[int] = os.path.join(_A , F"""{key}.dat""" ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on the fact weights are properly loaded def UpperCAmelCase_ ( self ): __A : Dict = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: __A : Tuple = torch.randn(2 , 3 , dtype=_A ) with TemporaryDirectory() as tmp_dir: __A : int = offload_weight(_A , 'weight' , _A , {} ) __A : Union[str, Any] = os.path.join(_A , 'weight.dat' ) self.assertTrue(os.path.isfile(_A ) ) self.assertDictEqual(_A , {'weight': {'shape': [2, 3], 'dtype': str(_A ).split('.' )[1]}} ) __A : List[str] = load_offloaded_weight(_A , index['weight'] ) self.assertTrue(torch.equal(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : int = ModelForTest() __A : Union[str, Any] = model.state_dict() __A : Optional[Any] = {k: v for k, v in state_dict.items() if 'linear2' not in k} __A : str = {k: v for k, v in state_dict.items() if 'linear2' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : List[str] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) __A : Union[str, Any] = {k: v for k, v in state_dict.items() if 'weight' in k} __A : List[Any] = {k: v for k, v in state_dict.items() if 'weight' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : Optional[int] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) # Duplicates are removed __A : str = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) def UpperCAmelCase_ ( self ): __A : Dict = {'a.1': 0, 'a.10': 1, 'a.2': 2} __A : str = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1': 0, 'a.2': 2} ) __A : Optional[Any] = {'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2} __A : Any = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1.a': 0, 'a.2.a': 2} )
77
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCAmelCase : str = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( a ) -> Dict: if isinstance(_lowerCamelCase , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(_lowerCamelCase , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(_lowerCamelCase ): return [[videos]] raise ValueError(F"""Could not make batched video from {videos}""" ) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Any = ["pixel_values"] def __init__( self , _A = True , _A = None , _A = PILImageResampling.BILINEAR , _A = True , _A = None , _A = True , _A = 1 / 255 , _A = True , _A = None , _A = None , **_A , ): super().__init__(**UpperCamelCase__ ) __A : List[str] = size if size is not None else {'shortest_edge': 224} __A : int = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __A : int = crop_size if crop_size is not None else {'height': 224, 'width': 224} __A : Dict = get_size_dict(UpperCamelCase__ , param_name='crop_size' ) __A : str = do_resize __A : List[str] = size __A : List[Any] = do_center_crop __A : Optional[Any] = crop_size __A : Union[str, Any] = resample __A : int = do_rescale __A : Union[str, Any] = rescale_factor __A : Union[str, Any] = do_normalize __A : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __A : List[str] = image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCAmelCase_ ( self , _A , _A , _A = PILImageResampling.BILINEAR , _A = None , **_A , ): __A : List[Any] = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) if "shortest_edge" in size: __A : str = get_resize_output_image_size(UpperCamelCase__ , size['shortest_edge'] , default_to_square=UpperCamelCase__ ) elif "height" in size and "width" in size: __A : Tuple = (size['height'], size['width']) else: raise ValueError(F"""Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCAmelCase_ ( self , _A , _A , _A = None , **_A , ): __A : str = get_size_dict(UpperCamelCase__ ) if "height" not in size or "width" not in size: raise ValueError(F"""Size must have 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(UpperCamelCase__ , size=(size['height'], size['width']) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCAmelCase_ ( self , _A , _A , _A = None , **_A , ): return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCAmelCase_ ( self , _A , _A , _A , _A = None , **_A , ): return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCAmelCase_ ( self , _A , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = ChannelDimension.FIRST , ): if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. __A : Dict = to_numpy_array(UpperCamelCase__ ) if do_resize: __A : Optional[Any] = self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) if do_center_crop: __A : int = self.center_crop(UpperCamelCase__ , size=UpperCamelCase__ ) if do_rescale: __A : List[Any] = self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) if do_normalize: __A : Dict = self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) __A : str = to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) return image def UpperCAmelCase_ ( self , _A , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = ChannelDimension.FIRST , **_A , ): __A : Optional[int] = do_resize if do_resize is not None else self.do_resize __A : str = resample if resample is not None else self.resample __A : str = do_center_crop if do_center_crop is not None else self.do_center_crop __A : Tuple = do_rescale if do_rescale is not None else self.do_rescale __A : int = rescale_factor if rescale_factor is not None else self.rescale_factor __A : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize __A : Optional[int] = image_mean if image_mean is not None else self.image_mean __A : Any = image_std if image_std is not None else self.image_std __A : Optional[int] = size if size is not None else self.size __A : List[Any] = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __A : Dict = crop_size if crop_size is not None else self.crop_size __A : List[str] = get_size_dict(UpperCamelCase__ , param_name='crop_size' ) 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.' ) __A : Any = make_batched(UpperCamelCase__ ) __A : Optional[Any] = [ [ self._preprocess_image( image=UpperCamelCase__ , do_resize=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , do_center_crop=UpperCamelCase__ , crop_size=UpperCamelCase__ , do_rescale=UpperCamelCase__ , rescale_factor=UpperCamelCase__ , do_normalize=UpperCamelCase__ , image_mean=UpperCamelCase__ , image_std=UpperCamelCase__ , data_format=UpperCamelCase__ , ) for img in video ] for video in videos ] __A : int = {'pixel_values': videos} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
700
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): __A : Any = data def __iter__( self ): for element in self.data: yield element def _SCREAMING_SNAKE_CASE ( a=True ) -> Any: __A : List[Any] = Accelerator(even_batches=a ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str: if iterable: __A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) ) else: __A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) ) __A : Optional[Any] = DataLoader(a , batch_size=a ) __A : Optional[int] = accelerator.prepare(a ) return dl def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]: __A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a ) __A : Tuple = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : int = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : str = create_accelerator(even_batches=a ) verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _SCREAMING_SNAKE_CASE ( ) -> str: __A : Optional[Any] = create_accelerator(even_batches=a ) __A : str = torch.nn.Linear(1 , 1 ) __A : Optional[int] = accelerator.prepare(a ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : str = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(a ): __A : Dict = ddp_model(batch[0].float() ) __A : List[str] = output.sum() loss.backward() batch_idxs.append(a ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , a ) assert "only supported for multi-GPU" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : int = True __A : Union[str, Any] = False __A : Optional[int] = create_accelerator(even_batches=a ) __A : int = torch.nn.Linear(1 , 1 ) __A : List[Any] = accelerator.prepare(a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : List[str] = train_dl.batch_sampler.even_batches __A : Dict = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Any = True __A : List[Any] = False __A : Tuple = create_accelerator(even_batches=a ) __A : List[str] = torch.nn.Linear(1 , 1 ) __A : Optional[Any] = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('ignore' ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : Tuple = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Any = create_accelerator() __A : Union[str, Any] = torch.nn.Linear(1 , 1 ) __A : str = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): pass assert issubclass(w[-1].category , a ) assert "only supported for map-style datasets" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : str = create_accelerator() accelerator.print('Test that even_batches variable ensures uniform batches across processes' ) test_default_ensures_even_batch_sizes() accelerator.print('Run tests with even_batches disabled' ) test_can_disable_even_batches() accelerator.print('Test joining uneven inputs' ) test_can_join_uneven_inputs() accelerator.print('Test overriding even_batches when joining uneven inputs' ) test_join_can_override_even_batches() accelerator.print('Test overriding even_batches for mixed dataloader types' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('Test join with non DDP distributed raises warning' ) __A : int = accelerator.state.distributed_type __A : Tuple = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(a ) __A : str = original_state if __name__ == "__main__": main()
77
0
def _SCREAMING_SNAKE_CASE ( a , a ) -> Dict: return number | (1 << position) def _SCREAMING_SNAKE_CASE ( a , a ) -> Dict: return number & ~(1 << position) def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: return number ^ (1 << position) def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: return ((number >> position) & 1) == 1 def _SCREAMING_SNAKE_CASE ( a , a ) -> Tuple: return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
701
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : str = { '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''', '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''', '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''', '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''', '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''', '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''', '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''', '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''', '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''', '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''', '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''', '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = '''codegen''' UpperCamelCase : List[str] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ): __A : Any = vocab_size __A : Tuple = n_ctx __A : Union[str, Any] = n_positions __A : Optional[Any] = n_embd __A : Any = n_layer __A : Dict = n_head __A : Union[str, Any] = n_inner __A : List[Any] = rotary_dim __A : str = activation_function __A : Any = resid_pdrop __A : Tuple = embd_pdrop __A : Tuple = attn_pdrop __A : Union[str, Any] = layer_norm_epsilon __A : str = initializer_range __A : Optional[Any] = use_cache __A : Union[str, Any] = bos_token_id __A : Tuple = eos_token_id super().__init__( bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A ) class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A = "default" , _A = None , _A = False , ): super().__init__(_A , task=_A , patching_specs=_A , use_past=_A ) if not getattr(self._config , 'pad_token_id' , _A ): # TODO: how to do that better? __A : Dict = 0 @property def UpperCAmelCase_ ( self ): __A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) __A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'} else: __A : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase_ ( self ): return self._config.n_layer @property def UpperCAmelCase_ ( self ): return self._config.n_head def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Any = super(_A , self ).generate_dummy_inputs( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) # We need to order the input in the way they appears in the forward() __A : str = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __A , __A : Any = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Any = seqlen + 2 __A : List[str] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __A : Optional[Any] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] __A : Tuple = common_inputs['attention_mask'] if self.use_past: __A : str = ordered_inputs['attention_mask'].dtype __A : List[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self ): return 13
77
0
import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class _A( _UpperCAmelCase , unittest.TestCase ): """simple docstring""" UpperCamelCase : int = FlaxAutoencoderKL @property def UpperCAmelCase_ ( self ): __A : Any = 4 __A : Optional[int] = 3 __A : Union[str, Any] = (32, 32) __A : List[str] = jax.random.PRNGKey(0 ) __A : Tuple = jax.random.uniform(lowercase__ , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase_ ( self ): __A : List[Any] = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __A : List[str] = self.dummy_input return init_dict, inputs_dict
702
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase : List[Any] = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _A , ) super().__init__(*_A , **_A )
77
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) UpperCAmelCase : Dict = { '''SCUT-DLVCLab/lilt-roberta-en-base''': ( '''https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[Any] = '''lilt''' def __init__( self , _A=30522 , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=2 , _A=0.0_2 , _A=1e-1_2 , _A=0 , _A="absolute" , _A=None , _A=4 , _A=1024 , **_A , ): super().__init__(pad_token_id=_A , **_A ) __A : Dict = vocab_size __A : List[str] = hidden_size __A : Union[str, Any] = num_hidden_layers __A : Optional[Any] = num_attention_heads __A : List[Any] = hidden_act __A : Optional[Any] = intermediate_size __A : Optional[Any] = hidden_dropout_prob __A : Optional[int] = attention_probs_dropout_prob __A : List[str] = max_position_embeddings __A : Dict = type_vocab_size __A : Optional[int] = initializer_range __A : Optional[Any] = layer_norm_eps __A : List[Any] = position_embedding_type __A : Optional[int] = classifier_dropout __A : Dict = channel_shrink_ratio __A : Union[str, Any] = max_ad_position_embeddings
703
import glob import os import random from string import ascii_lowercase, digits import cva UpperCAmelCase : Dict = '''''' UpperCAmelCase : Union[str, Any] = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal) def _SCREAMING_SNAKE_CASE ( ) -> None: __A , __A : List[Any] = get_dataset(a , a ) print('Processing...' ) __A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a ) for index, image in enumerate(a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __A : Optional[int] = random_chars(32 ) __A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] __A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Success {index+1}/{len(a )} with {file_name}""" ) __A : int = [] for anno in new_annos[index]: __A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(a ) with open(F"""/{file_root}.txt""" , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]: __A : int = [] __A : List[Any] = [] for label_file in glob.glob(os.path.join(a , '*.txt' ) ): __A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(a ) as in_file: __A : Tuple = in_file.readlines() __A : Dict = os.path.join(a , F"""{label_name}.jpg""" ) __A : Dict = [] for obj_list in obj_lists: __A : int = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(a ) labels.append(a ) return img_paths, labels def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]: __A : int = [] __A : Optional[Any] = [] __A : Dict = [] for idx in range(len(a ) ): __A : Dict = [] __A : Optional[Any] = img_list[idx] path_list.append(a ) __A : Union[str, Any] = anno_list[idx] __A : Optional[Any] = cva.imread(a ) if flip_type == 1: __A : Any = cva.flip(a , a ) for bbox in img_annos: __A : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __A : Union[str, Any] = cva.flip(a , a ) for bbox in img_annos: __A : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(a ) new_imgs_list.append(a ) return new_imgs_list, new_annos_lists, path_list def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __A : List[Any] = ascii_lowercase + digits return "".join(random.choice(a ) for _ in range(a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
77
0
from __future__ import annotations from typing import TypedDict class _A( __A ): """simple docstring""" UpperCamelCase : Tuple = 42 UpperCamelCase : Optional[int] = 42 def _SCREAMING_SNAKE_CASE ( a ) -> Optional[int]: if not isinstance(__lowercase , __lowercase ): raise TypeError('The parameter s type must be str.' ) return [s[i:] + s[:i] for i in range(len(__lowercase ) )] def _SCREAMING_SNAKE_CASE ( a ) -> Optional[Any]: if not isinstance(__lowercase , __lowercase ): raise TypeError('The parameter s type must be str.' ) if not s: raise ValueError('The parameter s must not be empty.' ) __A : Optional[Any] = all_rotations(__lowercase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation __A : BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(__lowercase ), } return response def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: if not isinstance(__lowercase , __lowercase ): raise TypeError('The parameter bwt_string type must be str.' ) if not bwt_string: raise ValueError('The parameter bwt_string must not be empty.' ) try: __A : str = int(__lowercase ) except ValueError: raise TypeError( 'The parameter idx_original_string type must be int or passive' ' of cast to int.' ) if idx_original_string < 0: raise ValueError('The parameter idx_original_string must not be lower than 0.' ) if idx_original_string >= len(__lowercase ): raise ValueError( 'The parameter idx_original_string must be lower than' ' len(bwt_string).' ) __A : Optional[Any] = [''] * len(__lowercase ) for _ in range(len(__lowercase ) ): for i in range(len(__lowercase ) ): __A : Union[str, Any] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": UpperCAmelCase : List[Any] = '''Provide a string that I will generate its BWT transform: ''' UpperCAmelCase : Tuple = input(entry_msg).strip() UpperCAmelCase : Optional[Any] = bwt_transform(s) print( F"""Burrows Wheeler transform for string '{s}' results """ F"""in '{result["bwt_string"]}'""" ) UpperCAmelCase : Dict = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"""Reversing Burrows Wheeler transform for entry '{result["bwt_string"]}' """ F"""we get original string '{original_string}'""" )
704
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A: """simple docstring""" def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=True , _A=False , _A=True , _A=99 , _A=32 , _A=5 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=16 , _A=2 , _A=0.0_2 , _A=3 , _A=4 , _A=None , ): __A : Union[str, Any] = parent __A : List[str] = batch_size __A : Optional[int] = seq_length __A : List[Any] = is_training __A : Optional[Any] = use_input_mask __A : List[Any] = use_token_type_ids __A : Optional[Any] = use_labels __A : List[str] = vocab_size __A : Optional[int] = hidden_size __A : List[Any] = num_hidden_layers __A : int = num_attention_heads __A : Dict = intermediate_size __A : Any = hidden_act __A : Union[str, Any] = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : Optional[int] = max_position_embeddings __A : Dict = type_vocab_size __A : Any = type_sequence_label_size __A : Dict = initializer_range __A : str = num_labels __A : Union[str, Any] = num_choices __A : str = scope def UpperCAmelCase_ ( self ): __A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : Optional[Any] = None if self.use_input_mask: __A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __A : Dict = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = None __A : List[Any] = None __A : List[Any] = None if self.use_labels: __A : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __A : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[str] = LlamaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A , attention_mask=_A ) __A : Any = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Dict = True __A : int = LlamaModel(_A ) model.to(_A ) model.eval() __A : str = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __A : int = model( _A , attention_mask=_A , encoder_hidden_states=_A , ) __A : List[Any] = model(_A , attention_mask=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Optional[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : int = True __A : List[Any] = True __A : List[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() # first forward pass __A : Optional[Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , ) __A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __A : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) __A : str = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __A : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : str = torch.cat([input_mask, next_mask] , dim=-1 ) __A : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['hidden_states'][0] __A : Union[str, Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , past_key_values=_A , output_hidden_states=_A , )['hidden_states'][0] # select random slice __A : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() __A : Tuple = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_A , _A , atol=1e-3 ) ) def UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Tuple = config_and_inputs __A : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () UpperCamelCase : Optional[Any] = (LlamaForCausalLM,) if is_torch_available() else () UpperCamelCase : Optional[Any] = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False def UpperCAmelCase_ ( self ): __A : List[Any] = LlamaModelTester(self ) __A : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : int = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() __A : str = 3 __A : Optional[int] = input_dict['input_ids'] __A : int = input_ids.ne(1 ).to(_A ) __A : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Union[str, Any] = 3 __A : Tuple = 'single_label_classification' __A : Union[str, Any] = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[int] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Any = 3 __A : int = 'multi_label_classification' __A : int = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __A : List[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def UpperCAmelCase_ ( self ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def UpperCAmelCase_ ( self , _A ): __A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Dict = ids_tensor([1, 10] , config.vocab_size ) __A : Union[str, Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : List[Any] = LlamaModel(_A ) original_model.to(_A ) original_model.eval() __A : Dict = original_model(_A ).last_hidden_state __A : int = original_model(_A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : int = {'type': scaling_type, 'factor': 1_0.0} __A : str = LlamaModel(_A ) scaled_model.to(_A ) scaled_model.eval() __A : Dict = scaled_model(_A ).last_hidden_state __A : str = scaled_model(_A ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(_A , _A , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) __A : Union[str, Any] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __A : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[str] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) __A : int = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) __A : Optional[int] = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : Optional[Any] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) __A : List[Any] = model(torch.tensor(_A ) ) __A : Tuple = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # fmt: off __A : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' __A : List[str] = 'Simply put, the theory of relativity states that ' __A : Union[str, Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) __A : List[str] = tokenizer.encode(_A , return_tensors='pt' ) __A : Tuple = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=_A ) # greedy generation outputs __A : Union[str, Any] = model.generate(_A , max_new_tokens=64 , top_p=_A , temperature=1 , do_sample=_A ) __A : List[str] = tokenizer.decode(generated_ids[0] , skip_special_tokens=_A ) self.assertEqual(_A , _A )
77
0
from abc import ABC, abstractmethod from argparse import ArgumentParser class _A( __lowercase ): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( _A ): raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self ): raise NotImplementedError()
705
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
0
import json import os from typing import Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Any = { '''vocab_file''': '''vocab.json''', '''tokenizer_config_file''': '''tokenizer_config.json''', '''merges_file''': '''merges.txt''', } UpperCAmelCase : Optional[Any] = { '''vocab_file''': { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json''' ), }, '''tokenizer_config_file''': { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json''' ), }, '''merges_file''': { '''facebook/s2t-wav2vec2-large-en-de''': ( '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt''' ), }, } UpperCAmelCase : Optional[Any] = '''</w>''' UpperCAmelCase : Union[str, Any] = '''@@ ''' def _SCREAMING_SNAKE_CASE ( a ) -> Any: __A : Tuple = set() __A : Union[str, Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __A : List[str] = char return pairs # Speech2Text2 has no max input length UpperCAmelCase : int = {'''facebook/s2t-wav2vec2-large-en-de''': 10_24} class _A( __a ): """simple docstring""" UpperCamelCase : str = VOCAB_FILES_NAMES UpperCamelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : str = ['''input_ids''', '''attention_mask'''] def __init__( self , _A , _A="<s>" , _A="<pad>" , _A="</s>" , _A="<unk>" , _A=False , _A=None , **_A , ): super().__init__( unk_token=snake_case__ , bos_token=snake_case__ , eos_token=snake_case__ , pad_token=snake_case__ , do_lower_case=snake_case__ , **snake_case__ , ) __A : Optional[int] = do_lower_case with open(snake_case__ , encoding='utf-8' ) as vocab_handle: __A : Optional[Any] = json.load(snake_case__ ) __A : int = {v: k for k, v in self.encoder.items()} if merges_file is None: logger.info(F"""No merges files provided. {self.__class__.__name__} can only be used for decoding.""" ) __A : Union[str, Any] = None __A : Any = None else: with open(snake_case__ , encoding='utf-8' ) as merges_handle: __A : List[str] = merges_handle.read().split('\n' )[:-1] __A : List[str] = [tuple(merge.split()[:2] ) for merge in merges] __A : Optional[Any] = dict(zip(snake_case__ , range(len(snake_case__ ) ) ) ) __A : int = {} @property def UpperCAmelCase_ ( self ): return len(self.decoder ) def UpperCAmelCase_ ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase_ ( self , _A ): __A : Tuple = tuple(token[:-1] ) + (token[-1] + BPE_TOKEN_MERGES,) if token in self.cache: return self.cache[token] __A : Dict = get_pairs(snake_case__ ) if not pairs: return token while True: __A : List[Any] = min(snake_case__ , key=lambda _A : self.bpe_ranks.get(snake_case__ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break __A , __A : List[Any] = bigram __A : Union[str, Any] = [] __A : List[str] = 0 while i < len(snake_case__ ): try: __A : List[Any] = word.index(snake_case__ , snake_case__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __A : str = j if word[i] == first and i < len(snake_case__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __A : Dict = tuple(snake_case__ ) __A : Union[str, Any] = new_word if len(snake_case__ ) == 1: break else: __A : List[Any] = get_pairs(snake_case__ ) __A : List[Any] = ' '.join(snake_case__ ) if word == "\n " + BPE_TOKEN_MERGES: __A : Optional[Any] = '\n' + BPE_TOKEN_MERGES if word.endswith(snake_case__ ): __A : Tuple = word.replace(snake_case__ , '' ) __A : Tuple = word.replace(' ' , snake_case__ ) __A : Union[str, Any] = word return word def UpperCAmelCase_ ( self , _A ): if self.bpe_ranks is None: raise ValueError( 'This tokenizer was instantiated without a `merges.txt` file, so' ' that it can only be used for decoding, not for encoding.' 'Make sure to provide `merges.txt` file at instantiation to enable ' 'encoding.' ) if self.do_lower_case: __A : int = text.lower() __A : Tuple = text.split() __A : List[Any] = [] for token in text: if token: split_tokens.extend(list(self.bpe(snake_case__ ).split(' ' ) ) ) return split_tokens def UpperCAmelCase_ ( self , _A ): return self.encoder.get(snake_case__ , self.encoder.get(self.unk_token ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = self.decoder.get(snake_case__ , self.unk_token ) return result def UpperCAmelCase_ ( self , _A ): __A : Union[str, Any] = ' '.join(snake_case__ ) # make sure @@ tokens are concatenated __A : Optional[int] = ''.join(string.split(snake_case__ ) ) return string def UpperCAmelCase_ ( self , _A , _A = None ): if not os.path.isdir(snake_case__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __A : Optional[int] = os.path.join( snake_case__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __A : Any = os.path.join( snake_case__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(snake_case__ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=snake_case__ , ensure_ascii=snake_case__ ) + '\n' ) __A : Union[str, Any] = 0 if self.bpe_ranks is None: return (vocab_file,) with open(snake_case__ , 'w' , encoding='utf-8' ) as writer: for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _A : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merges_file}: BPE merge indices are not consecutive.""" ' Please check that the tokenizer is not corrupted!' ) __A : Optional[int] = token_index writer.write(' '.join(snake_case__ ) + '\n' ) index += 1 return (vocab_file, merges_file)
706
import numpy as np from PIL import Image def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : Union[str, Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : List[Any] = 0 __A : Optional[Any] = 0 __A : List[Any] = 0 __A : Dict = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __A : Tuple = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : List[str] = 0 __A : Union[str, Any] = 0 return updated_arr def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : List[Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : Dict = 0 __A : str = 0 __A : Tuple = 0 __A : Optional[int] = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __A : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : Dict = 0 __A : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image UpperCAmelCase : int = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
77
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available UpperCAmelCase : Dict = {'''tokenization_herbert''': ['''HerbertTokenizer''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[Any] = ['''HerbertTokenizerFast'''] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys UpperCAmelCase : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
707
from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float: __A : Any = x_start __A : List[str] = fnc(a ) __A : Optional[Any] = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area __A : Any = (x_end - x_start) / steps + xa __A : List[str] = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __A : Any = xa __A : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( a ) -> int: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') UpperCAmelCase : Tuple = 10 while i <= 10_00_00: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
77
0
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 , _A , _A=7 , _A=3 , _A=30 , _A=400 , _A=True , _A=None , _A=0.9 , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , ): __A : str = size if size is not None else {'shortest_edge': 30} __A : Union[str, Any] = crop_size if crop_size is not None else {'height': 30, 'width': 30} __A : List[Any] = parent __A : List[str] = batch_size __A : Dict = num_channels __A : str = min_resolution __A : Any = max_resolution __A : Union[str, Any] = do_resize_and_center_crop __A : Dict = size __A : Any = crop_pct __A : str = crop_size __A : List[Any] = do_normalize __A : Union[str, Any] = image_mean __A : Tuple = image_std def UpperCAmelCase_ ( self ): 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""" UpperCamelCase : int = PoolFormerImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : str = PoolFormerImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'do_resize_and_center_crop' ) ) self.assertTrue(hasattr(_A , 'size' ) ) self.assertTrue(hasattr(_A , 'crop_pct' ) ) self.assertTrue(hasattr(_A , 'do_normalize' ) ) self.assertTrue(hasattr(_A , 'image_mean' ) ) self.assertTrue(hasattr(_A , 'image_std' ) ) def UpperCAmelCase_ ( self ): __A : str = 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} ) __A : Any = 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 UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processing __A : int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __A : Tuple = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : List[str] = 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 __A : Tuple = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Dict = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __A : List[Any] = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
708
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def _SCREAMING_SNAKE_CASE ( ) -> None: print('Making key files...' ) make_key_files('rsa' , 10_24 ) print('Key files generation successful.' ) def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]: print('Generating prime p...' ) __A : Optional[Any] = rabinMiller.generate_large_prime(a ) print('Generating prime q...' ) __A : Union[str, Any] = rabinMiller.generate_large_prime(a ) __A : Tuple = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...' ) while True: __A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1: break print('Calculating d that is mod inverse of e...' ) __A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) ) __A : Dict = (n, e) __A : Dict = (n, d) return (public_key, private_key) def _SCREAMING_SNAKE_CASE ( a , a ) -> 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() __A , __A : Optional[int] = generate_key(a ) 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()
77
0
import argparse import os import re UpperCAmelCase : Optional[Any] = 'src/diffusers' # Pattern that looks at the indentation in a line. UpperCAmelCase : int = re.compile(r'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. UpperCAmelCase : Dict = re.compile(r'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. UpperCAmelCase : Optional[Any] = re.compile(r'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. UpperCAmelCase : int = re.compile(r'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. UpperCAmelCase : Optional[Any] = re.compile(r'''\[([^\]]+)\]''') def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : List[str] = _re_indent.search(_A ) return "" if search is None else search.groups()[0] def _SCREAMING_SNAKE_CASE ( a , a="" , a=None , a=None ) -> List[Any]: __A : int = 0 __A : Any = code.split('\n' ) if start_prompt is not None: while not lines[index].startswith(_A ): index += 1 __A : Dict = ['\n'.join(lines[:index] )] else: __A : List[Any] = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). __A : int = [lines[index]] index += 1 while index < len(_A ) and (end_prompt is None or not lines[index].startswith(_A )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_A ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ' ' ): current_block.append(lines[index] ) blocks.append('\n'.join(_A ) ) if index < len(_A ) - 1: __A : List[Any] = [lines[index + 1]] index += 1 else: __A : Union[str, Any] = [] else: blocks.append('\n'.join(_A ) ) __A : int = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_A ) > 0: blocks.append('\n'.join(_A ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_A ): blocks.append('\n'.join(lines[index:] ) ) return blocks def _SCREAMING_SNAKE_CASE ( a ) -> Optional[int]: def _inner(a ): return key(_A ).lower().replace('_' , '' ) return _inner def _SCREAMING_SNAKE_CASE ( a , a=None ) -> List[str]: # If no key is provided, we use a noop. def noop(a ): return x if key is None: __A : str = noop # Constants are all uppercase, they go first. __A : Tuple = [obj for obj in objects if key(_A ).isupper()] # Classes are not all uppercase but start with a capital, they go second. __A : Tuple = [obj for obj in objects if key(_A )[0].isupper() and not key(_A ).isupper()] # Functions begin with a lowercase, they go last. __A : int = [obj for obj in objects if not key(_A )[0].isupper()] __A : str = ignore_underscore(_A ) return sorted(_A , key=_A ) + sorted(_A , key=_A ) + sorted(_A , key=_A ) def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: # This inner function sort imports between [ ]. def _replace(a ): __A : str = match.groups()[0] if "," not in imports: return F"""[{imports}]""" __A : Dict = [part.strip().replace('\"' , '' ) for part in imports.split(',' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: __A : List[str] = keys[:-1] return "[" + ", ".join([F"""\"{k}\"""" for k in sort_objects(_A )] ) + "]" __A : Dict = import_statement.split('\n' ) if len(_A ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. __A : str = 2 if lines[1].strip() == '[' else 1 __A : Optional[int] = [(i, _re_strip_line.search(_A ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] __A : Tuple = sort_objects(_A , key=lambda a : x[1] ) __A : str = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_A ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: __A : Union[str, Any] = _re_bracket_content.sub(_replace , lines[1] ) else: __A : str = [part.strip().replace('\"' , '' ) for part in lines[1].split(',' )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: __A : str = keys[:-1] __A : Union[str, Any] = get_indent(lines[1] ) + ', '.join([F"""\"{k}\"""" for k in sort_objects(_A )] ) return "\n".join(_A ) else: # Finally we have to deal with imports fitting on one line __A : Tuple = _re_bracket_content.sub(_replace , _A ) return import_statement def _SCREAMING_SNAKE_CASE ( a , a=True ) -> str: with open(_A , 'r' ) as f: __A : Dict = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 __A : Union[str, Any] = split_code_in_indented_blocks( _A , start_prompt='_import_structure = {' , end_prompt='if TYPE_CHECKING:' ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(_A ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. __A : Optional[Any] = main_blocks[block_idx] __A : Dict = block.split('\n' ) # Get to the start of the imports. __A : List[Any] = 0 while line_idx < len(_A ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: __A : Optional[int] = len(_A ) else: line_idx += 1 if line_idx >= len(_A ): continue # Ignore beginning and last line: they don't contain anything. __A : int = '\n'.join(block_lines[line_idx:-1] ) __A : Dict = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. __A : Dict = split_code_in_indented_blocks(_A , indent_level=_A ) # We have two categories of import key: list or _import_structure[key].append/extend __A : Tuple = _re_direct_key if '_import_structure' in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. __A : str = [(pattern.search(_A ).groups()[0] if pattern.search(_A ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. __A : Dict = [(i, key) for i, key in enumerate(_A ) if key is not None] __A : List[Any] = [x[0] for x in sorted(_A , key=lambda a : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. __A : Optional[int] = 0 __A : int = [] for i in range(len(_A ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: __A : List[str] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(_A ) count += 1 # And we put our main block back together with its first and last line. __A : List[Any] = '\n'.join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(_A ): if check_only: return True else: print(F"""Overwriting {file}.""" ) with open(_A , 'w' ) as f: f.write('\n'.join(_A ) ) def _SCREAMING_SNAKE_CASE ( a=True ) -> List[Any]: __A : List[Any] = [] for root, _, files in os.walk(_A ): if "__init__.py" in files: __A : Optional[Any] = sort_imports(os.path.join(_A , '__init__.py' ) , check_only=_A ) if result: __A : Union[str, Any] = [os.path.join(_A , '__init__.py' )] if len(_A ) > 0: raise ValueError(F"""Would overwrite {len(_A )} files, run `make style`.""" ) if __name__ == "__main__": UpperCAmelCase : Tuple = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') UpperCAmelCase : Optional[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
709
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ProphetNetTokenizer UpperCamelCase : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() __A : Any = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = 'UNwant\u00E9d,running' __A : List[str] = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class(self.vocab_file ) __A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase_ ( self ): __A : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCAmelCase_ ( self ): __A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __A : Optional[int] = {} for i, token in enumerate(_A ): __A : Tuple = i __A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __A : str = tokenizer(_A , padding=_A , return_tensors='pt' ) self.assertIsInstance(_A , _A ) __A : List[str] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A ) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A ) __A : str = tokenizer.build_inputs_with_special_tokens(_A ) __A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
77
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Tuple = { 'SCUT-DLVCLab/lilt-roberta-en-base': ( 'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json' ), } class _A( _A ): """simple docstring""" UpperCamelCase : Dict = '''lilt''' def __init__( self , _A=30522 , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=2 , _A=0.0_2 , _A=1e-1_2 , _A=0 , _A="absolute" , _A=None , _A=4 , _A=1024 , **_A , ): super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ ) __A : Optional[Any] = vocab_size __A : List[Any] = hidden_size __A : Union[str, Any] = num_hidden_layers __A : Optional[int] = num_attention_heads __A : Tuple = hidden_act __A : Optional[Any] = intermediate_size __A : Optional[Any] = hidden_dropout_prob __A : str = attention_probs_dropout_prob __A : Tuple = max_position_embeddings __A : Optional[Any] = type_vocab_size __A : Tuple = initializer_range __A : List[str] = layer_norm_eps __A : Union[str, Any] = position_embedding_type __A : Dict = classifier_dropout __A : Tuple = channel_shrink_ratio __A : List[Any] = max_ad_position_embeddings
710
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Optional[int] = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } UpperCAmelCase : List[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = BertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : Any = getattr(_A , normalizer_state.pop('type' ) ) __A : Union[str, Any] = do_lower_case __A : Optional[int] = strip_accents __A : List[Any] = tokenize_chinese_chars __A : int = normalizer_class(**_A ) __A : Union[str, Any] = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : Tuple = [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 UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[Any] = [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : int = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available UpperCAmelCase : str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Tuple = ['''BartphoTokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys UpperCAmelCase : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
711
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 UpperCAmelCase_ ( self ): debug_launcher(test_script.main ) def UpperCAmelCase_ ( self ): debug_launcher(test_ops.main )
77
0
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class _A( lowercase_ ): """simple docstring""" UpperCamelCase : Dict = (DEISMultistepScheduler,) UpperCamelCase : List[Any] = (('''num_inference_steps''', 25),) def UpperCAmelCase_ ( self , **_A ): __A : Dict = { """num_train_timesteps""": 1000, """beta_start""": 0.0_0_0_1, """beta_end""": 0.0_2, """beta_schedule""": """linear""", """solver_order""": 2, } config.update(**lowerCamelCase_ ) return config def UpperCAmelCase_ ( self , _A=0 , **_A ): __A : Any = dict(self.forward_default_kwargs ) __A : List[str] = kwargs.pop('num_inference_steps' , lowerCamelCase_ ) __A : Dict = self.dummy_sample __A : Any = 0.1 * sample __A : str = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] for scheduler_class in self.scheduler_classes: __A : int = self.get_scheduler_config(**lowerCamelCase_ ) __A : Optional[int] = scheduler_class(**lowerCamelCase_ ) scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residuals __A : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase_ ) __A : Optional[int] = scheduler_class.from_pretrained(lowerCamelCase_ ) new_scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residuals __A : List[str] = dummy_past_residuals[: new_scheduler.config.solver_order] __A : str = sample, sample for t in range(lowerCamelCase_ , time_step + scheduler.config.solver_order + 1 ): __A : Tuple = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample __A : Optional[int] = new_scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self , _A=0 , **_A ): __A : Tuple = dict(self.forward_default_kwargs ) __A : Optional[Any] = kwargs.pop('num_inference_steps' , lowerCamelCase_ ) __A : Optional[int] = self.dummy_sample __A : Optional[Any] = 0.1 * sample __A : Optional[Any] = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] for scheduler_class in self.scheduler_classes: __A : str = self.get_scheduler_config() __A : Any = scheduler_class(**lowerCamelCase_ ) scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residuals (must be after setting timesteps) __A : List[str] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase_ ) __A : List[str] = scheduler_class.from_pretrained(lowerCamelCase_ ) # copy over dummy past residuals new_scheduler.set_timesteps(lowerCamelCase_ ) # copy over dummy past residual (must be after setting timesteps) __A : Dict = dummy_past_residuals[: new_scheduler.config.solver_order] __A : List[Any] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample __A : Tuple = new_scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def UpperCAmelCase_ ( self , _A=None , **_A ): if scheduler is None: __A : Optional[int] = self.scheduler_classes[0] __A : Optional[Any] = self.get_scheduler_config(**lowerCamelCase_ ) __A : int = scheduler_class(**lowerCamelCase_ ) __A : List[Any] = self.scheduler_classes[0] __A : str = self.get_scheduler_config(**lowerCamelCase_ ) __A : str = scheduler_class(**lowerCamelCase_ ) __A : Tuple = 10 __A : Any = self.dummy_model() __A : Union[str, Any] = self.dummy_sample_deter scheduler.set_timesteps(lowerCamelCase_ ) for i, t in enumerate(scheduler.timesteps ): __A : Dict = model(lowerCamelCase_ , lowerCamelCase_ ) __A : Optional[int] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ).prev_sample return sample def UpperCAmelCase_ ( self ): __A : Tuple = dict(self.forward_default_kwargs ) __A : int = kwargs.pop('num_inference_steps' , lowerCamelCase_ ) for scheduler_class in self.scheduler_classes: __A : str = self.get_scheduler_config() __A : Optional[Any] = scheduler_class(**lowerCamelCase_ ) __A : Optional[int] = self.dummy_sample __A : Any = 0.1 * sample if num_inference_steps is not None and hasattr(lowerCamelCase_ , 'set_timesteps' ): scheduler.set_timesteps(lowerCamelCase_ ) elif num_inference_steps is not None and not hasattr(lowerCamelCase_ , 'set_timesteps' ): __A : str = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __A : Optional[Any] = [residual + 0.2, residual + 0.1_5, residual + 0.1_0] __A : int = dummy_past_residuals[: scheduler.config.solver_order] __A : int = scheduler.timesteps[5] __A : int = scheduler.timesteps[6] __A : List[Any] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample __A : Tuple = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCAmelCase_ ( self ): __A : str = DEISMultistepScheduler(**self.get_scheduler_config() ) __A : Union[str, Any] = self.full_loop(scheduler=lowerCamelCase_ ) __A : List[Any] = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.2_3_9_1_6 ) < 1e-3 __A : List[str] = DPMSolverSinglestepScheduler.from_config(scheduler.config ) __A : Tuple = DPMSolverMultistepScheduler.from_config(scheduler.config ) __A : Dict = UniPCMultistepScheduler.from_config(scheduler.config ) __A : int = DEISMultistepScheduler.from_config(scheduler.config ) __A : Optional[Any] = self.full_loop(scheduler=lowerCamelCase_ ) __A : List[str] = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.2_3_9_1_6 ) < 1e-3 def UpperCAmelCase_ ( self ): for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=lowerCamelCase_ ) def UpperCAmelCase_ ( self ): self.check_over_configs(thresholding=lowerCamelCase_ ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=lowerCamelCase_ , prediction_type=lowerCamelCase_ , sample_max_value=lowerCamelCase_ , algorithm_type='deis' , solver_order=lowerCamelCase_ , solver_type=lowerCamelCase_ , ) def UpperCAmelCase_ ( self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowerCamelCase_ ) def UpperCAmelCase_ ( self ): for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=lowerCamelCase_ , solver_type=lowerCamelCase_ , prediction_type=lowerCamelCase_ , algorithm_type=lowerCamelCase_ , ) __A : Dict = self.full_loop( solver_order=lowerCamelCase_ , solver_type=lowerCamelCase_ , prediction_type=lowerCamelCase_ , algorithm_type=lowerCamelCase_ , ) assert not torch.isnan(lowerCamelCase_ ).any(), "Samples have nan numbers" def UpperCAmelCase_ ( self ): self.check_over_configs(lower_order_final=lowerCamelCase_ ) self.check_over_configs(lower_order_final=lowerCamelCase_ ) def UpperCAmelCase_ ( self ): for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=lowerCamelCase_ , time_step=0 ) def UpperCAmelCase_ ( self ): __A : List[Any] = self.full_loop() __A : List[Any] = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.2_3_9_1_6 ) < 1e-3 def UpperCAmelCase_ ( self ): __A : List[str] = self.full_loop(prediction_type='v_prediction' ) __A : Any = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_mean.item() - 0.0_9_1 ) < 1e-3 def UpperCAmelCase_ ( self ): __A : Optional[int] = self.scheduler_classes[0] __A : List[str] = self.get_scheduler_config(thresholding=lowerCamelCase_ , dynamic_thresholding_ratio=0 ) __A : Dict = scheduler_class(**lowerCamelCase_ ) __A : List[str] = 10 __A : Optional[int] = self.dummy_model() __A : Dict = self.dummy_sample_deter.half() scheduler.set_timesteps(lowerCamelCase_ ) for i, t in enumerate(scheduler.timesteps ): __A : List[Any] = model(lowerCamelCase_ , lowerCamelCase_ ) __A : List[Any] = scheduler.step(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ).prev_sample assert sample.dtype == torch.floataa
712
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Tuple = tempfile.mkdtemp() # fmt: off __A : Union[str, Any] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Dict = dict(zip(_A , range(len(_A ) ) ) ) __A : int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : Optional[Any] = {'unk_token': '<unk>'} __A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : Union[str, Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : List[str] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[str] = self.get_tokenizer() __A : Dict = self.get_rust_tokenizer() __A : Optional[Any] = self.get_image_processor() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Any = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : int = self.get_image_processor(do_normalize=_A ) __A : int = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : List[Any] = self.prepare_image_inputs() __A : Any = image_processor(_A , return_tensors='np' ) __A : Tuple = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_image_processor() __A : int = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = 'lower newer' __A : Any = processor(text=_A , return_tensors='np' ) __A : Dict = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Tuple = 'lower newer' __A : Union[str, Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[int] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Any = ['cat', 'nasa badge'] __A : List[Any] = processor(text=_A ) __A : Dict = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : int = [['cat', 'nasa badge'], ['person']] __A : str = processor(text=_A ) __A : int = 16 __A : Optional[int] = len(_A ) __A : int = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : int = 'google/owlvit-base-patch32' __A : List[str] = OwlViTProcessor.from_pretrained(_A ) __A : Tuple = ['cat', 'nasa badge'] __A : Dict = processor(text=_A ) __A : Tuple = 16 __A : str = inputs['input_ids'] __A : str = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Dict = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = self.prepare_image_inputs() __A : Tuple = self.prepare_image_inputs() __A : Any = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Union[str, Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
77
0
from __future__ import annotations import math class _A: """simple docstring""" def __init__( self , _A ): __A : Any = size # approximate the overall size of segment tree with given value __A : Optional[Any] = [0 for i in range(0 , 4 * size )] # create array to store lazy update __A : List[str] = [0 for i in range(0 , 4 * size )] __A : str = [0 for i in range(0 , 4 * size )] # flag for lazy update def UpperCAmelCase_ ( self , _A ): return idx * 2 def UpperCAmelCase_ ( self , _A ): return idx * 2 + 1 def UpperCAmelCase_ ( self , _A , _A , _A , _A ): if left_element == right_element: __A : Optional[int] = a[left_element - 1] else: __A : List[Any] = (left_element + right_element) // 2 self.build(self.left(UpperCamelCase_ ) , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) self.build(self.right(UpperCamelCase_ ) , mid + 1 , UpperCamelCase_ , UpperCamelCase_ ) __A : Dict = max( self.segment_tree[self.left(UpperCamelCase_ )] , self.segment_tree[self.right(UpperCamelCase_ )] ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A ): if self.flag[idx] is True: __A : Optional[int] = self.lazy[idx] __A : Optional[int] = False if left_element != right_element: __A : Tuple = self.lazy[idx] __A : Optional[int] = self.lazy[idx] __A : str = True __A : Optional[int] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __A : Tuple = val if left_element != right_element: __A : Tuple = val __A : Optional[int] = val __A : List[Any] = True __A : int = True return True __A : Tuple = (left_element + right_element) // 2 self.update(self.left(UpperCamelCase_ ) , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) self.update(self.right(UpperCamelCase_ ) , mid + 1 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) __A : Tuple = max( self.segment_tree[self.left(UpperCamelCase_ )] , self.segment_tree[self.right(UpperCamelCase_ )] ) return True def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A ): if self.flag[idx] is True: __A : str = self.lazy[idx] __A : Dict = False if left_element != right_element: __A : Union[str, Any] = self.lazy[idx] __A : List[Any] = self.lazy[idx] __A : Optional[Any] = True __A : int = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __A : Optional[int] = (left_element + right_element) // 2 __A : Any = self.query(self.left(UpperCamelCase_ ) , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) __A : Any = self.query(self.right(UpperCamelCase_ ) , mid + 1 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) return max(UpperCamelCase_ , UpperCamelCase_ ) def __str__( self ): return str([self.query(1 , 1 , self.size , UpperCamelCase_ , UpperCamelCase_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": UpperCAmelCase : Optional[int] = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] UpperCAmelCase : Any = 15 UpperCAmelCase : str = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 1_11) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 2_35) print(segt)
713
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } UpperCAmelCase : Union[str, Any] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Tuple: for attribute in key.split('.' ): __A : Dict = getattr(a , a ) if weight_type is not None: __A : Any = getattr(a , a ).shape else: __A : Any = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __A : Union[str, Any] = value elif weight_type == "weight_g": __A : Dict = value elif weight_type == "weight_v": __A : Optional[int] = value elif weight_type == "bias": __A : int = value elif weight_type == "running_mean": __A : Union[str, Any] = value elif weight_type == "running_var": __A : Union[str, Any] = value elif weight_type == "num_batches_tracked": __A : Any = value elif weight_type == "inv_freq": __A : Optional[Any] = value else: __A : int = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]: __A : Any = [] __A : Optional[int] = fairseq_model.state_dict() __A : Union[str, Any] = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __A : int = False if "conv_layers" in name: load_conv_layer( a , a , a , a , hf_model.config.feat_extract_norm == 'group' , ) __A : Optional[int] = True else: for key, mapped_key in MAPPING.items(): __A : Any = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __A : Optional[Any] = True if "*" in mapped_key: __A : str = name.split(a )[0].split('.' )[-2] __A : int = mapped_key.replace('*' , a ) if "pos_bias_u" in name: __A : Optional[int] = None elif "pos_bias_v" in name: __A : Dict = None elif "weight_g" in name: __A : Optional[Any] = 'weight_g' elif "weight_v" in name: __A : Dict = 'weight_v' elif "bias" in name: __A : Tuple = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __A : int = 'weight' elif "running_mean" in name: __A : str = 'running_mean' elif "inv_freq" in name: __A : List[Any] = 'inv_freq' elif "running_var" in name: __A : Union[str, Any] = 'running_var' elif "num_batches_tracked" in name: __A : Optional[Any] = 'num_batches_tracked' else: __A : List[str] = None set_recursively(a , a , a , a , a ) continue if not is_used: unused_weights.append(a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Any: __A : str = full_name.split('conv_layers.' )[-1] __A : str = name.split('.' ) __A : Dict = int(items[0] ) __A : Any = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __A : int = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) __A : Any = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) __A : List[str] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a ) @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a=None , a=None , a=True ) -> Any: if config_path is not None: __A : Tuple = WavaVecaConformerConfig.from_pretrained(a , hidden_act='swish' ) else: __A : Optional[Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: __A : Dict = 'rotary' if is_finetuned: if dict_path: __A : Dict = Dictionary.load(a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __A : int = target_dict.pad_index __A : List[Any] = target_dict.bos_index __A : Any = target_dict.eos_index __A : Dict = len(target_dict.symbols ) __A : Optional[Any] = os.path.join(a , 'vocab.json' ) if not os.path.isdir(a ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(a ) ) return os.makedirs(a , exist_ok=a ) __A : List[str] = target_dict.indices # fairseq has the <pad> and <s> switched __A : int = 0 __A : Optional[Any] = 1 with open(a , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(a , a ) __A : Optional[Any] = WavaVecaCTCTokenizer( a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=a , ) __A : Tuple = True if config.feat_extract_norm == 'layer' else False __A : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=a , return_attention_mask=a , ) __A : Optional[int] = WavaVecaProcessor(feature_extractor=a , tokenizer=a ) processor.save_pretrained(a ) __A : List[Any] = WavaVecaConformerForCTC(a ) else: __A : List[Any] = WavaVecaConformerForPreTraining(a ) if is_finetuned: __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: __A : Optional[Any] = argparse.Namespace(task='audio_pretraining' ) __A : str = fairseq.tasks.setup_task(a ) __A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=a ) __A : Tuple = model[0].eval() recursively_load_weights(a , a , not is_finetuned ) hf_wavavec.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) UpperCAmelCase : List[str] = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
77
0
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, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Optional[int] = tempfile.mkdtemp() __A : Any = BlipImageProcessor() __A : Optional[Any] = GPTaTokenizer.from_pretrained('hf-internal-testing/tiny-random-GPT2Model' ) __A : Optional[int] = BlipaProcessor(_A , _A ) processor.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self , **_A ): return AutoProcessor.from_pretrained(self.tmpdirname , **_A ).tokenizer def UpperCAmelCase_ ( self , **_A ): return AutoProcessor.from_pretrained(self.tmpdirname , **_A ).image_processor def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : str = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[Any] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : Dict = BlipaProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : int = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : Union[str, Any] = self.get_image_processor(do_normalize=_A , padding_value=1.0 ) __A : Any = BlipaProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Any = self.get_image_processor() __A : Any = self.get_tokenizer() __A : Optional[Any] = BlipaProcessor(tokenizer=_A , image_processor=_A ) __A : Any = self.prepare_image_inputs() __A : Optional[int] = image_processor(_A , return_tensors='np' ) __A : Union[str, Any] = processor(images=_A , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_image_processor() __A : Dict = self.get_tokenizer() __A : List[Any] = BlipaProcessor(tokenizer=_A , image_processor=_A ) __A : List[str] = "lower newer" __A : Dict = processor(text=_A ) __A : Any = tokenizer(_A , return_token_type_ids=_A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_image_processor() __A : Any = self.get_tokenizer() __A : Tuple = BlipaProcessor(tokenizer=_A , image_processor=_A ) __A : Tuple = "lower newer" __A : str = self.prepare_image_inputs() __A : Any = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'input_ids', 'attention_mask'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : int = self.get_image_processor() __A : Tuple = self.get_tokenizer() __A : Optional[Any] = BlipaProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Optional[Any] = processor.batch_decode(_A ) __A : Union[str, Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.get_image_processor() __A : Any = self.get_tokenizer() __A : Optional[Any] = BlipaProcessor(tokenizer=_A , image_processor=_A ) __A : List[Any] = "lower newer" __A : Tuple = self.prepare_image_inputs() __A : Tuple = processor(text=_A , images=_A ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'input_ids', 'attention_mask'] )
714
from abc import ABC, abstractmethod from argparse import ArgumentParser class _A( snake_case__ ): """simple docstring""" @staticmethod @abstractmethod def UpperCAmelCase_ ( _A ): raise NotImplementedError() @abstractmethod def UpperCAmelCase_ ( self ): raise NotImplementedError()
77
0
import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision 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 DPTImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=7 , _A=3 , _A=18 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , ): __A : str = size if size is not None else {'height': 18, 'width': 18} __A : int = parent __A : Optional[int] = batch_size __A : int = num_channels __A : Dict = image_size __A : List[str] = min_resolution __A : List[str] = max_resolution __A : List[Any] = do_resize __A : List[Any] = size __A : Dict = do_normalize __A : Optional[Any] = image_mean __A : Dict = image_std def UpperCAmelCase_ ( self ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : str = DPTImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : List[str] = DPTImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase_ , 'image_mean' ) ) self.assertTrue(hasattr(lowercase_ , 'image_std' ) ) self.assertTrue(hasattr(lowercase_ , 'do_normalize' ) ) self.assertTrue(hasattr(lowercase_ , 'do_resize' ) ) self.assertTrue(hasattr(lowercase_ , 'size' ) ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 18} ) __A : str = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) def UpperCAmelCase_ ( self ): __A : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_ ) for image in image_inputs: self.assertIsInstance(lowercase_ , Image.Image ) # Test not batched input __A : List[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __A : Dict = image_processing(lowercase_ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def UpperCAmelCase_ ( self ): __A : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_ , numpify=lowercase_ ) for image in image_inputs: self.assertIsInstance(lowercase_ , np.ndarray ) # Test not batched input __A : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __A : List[Any] = image_processing(lowercase_ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def UpperCAmelCase_ ( self ): __A : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase_ , torchify=lowercase_ ) for image in image_inputs: self.assertIsInstance(lowercase_ , torch.Tensor ) # Test not batched input __A : List[str] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __A : int = image_processing(lowercase_ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , )
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
77
0
def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Dict: global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: __A : str = mf_knapsack(i - 1 , snake_case__ , snake_case__ , snake_case__ ) else: __A : Tuple = max( mf_knapsack(i - 1 , snake_case__ , snake_case__ , snake_case__ ) , mf_knapsack(i - 1 , snake_case__ , snake_case__ , j - wt[i - 1] ) + val[i - 1] , ) __A : List[str] = val return f[i][j] def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> List[str]: __A : Dict = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1 , n + 1 ): for w_ in range(1 , w + 1 ): if wt[i - 1] <= w_: __A : Any = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] ) else: __A : Dict = dp[i - 1][w_] return dp[n][w_], dp def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Dict: if not (isinstance(snake_case__ , (list, tuple) ) and isinstance(snake_case__ , (list, tuple) )): raise ValueError( 'Both the weights and values vectors must be either lists or tuples' ) __A : Dict = len(snake_case__ ) if num_items != len(snake_case__ ): __A : List[Any] = ( 'The number of weights must be the same as the number of values.\n' F"""But got {num_items} weights and {len(snake_case__ )} values""" ) raise ValueError(snake_case__ ) for i in range(snake_case__ ): if not isinstance(wt[i] , snake_case__ ): __A : Optional[Any] = ( 'All weights must be integers but got weight of ' F"""type {type(wt[i] )} at index {i}""" ) raise TypeError(snake_case__ ) __A , __A : Tuple = knapsack(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) __A : Any = set() _construct_solution(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) return optimal_val, example_optional_set def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> List[str]: # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(snake_case__ , snake_case__ , i - 1 , snake_case__ , snake_case__ ) else: optimal_set.add(snake_case__ ) _construct_solution(snake_case__ , snake_case__ , i - 1 , j - wt[i - 1] , snake_case__ ) if __name__ == "__main__": UpperCAmelCase : int = [3, 2, 4, 4] UpperCAmelCase : List[str] = [4, 3, 2, 3] UpperCAmelCase : int = 4 UpperCAmelCase : Union[str, Any] = 6 UpperCAmelCase : Any = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] UpperCAmelCase , UpperCAmelCase : Any = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 UpperCAmelCase , UpperCAmelCase : Union[str, Any] = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print('''optimal_value = ''', optimal_solution) print('''An optimal subset corresponding to the optimal value''', optimal_subset)
716
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = ShapEPipeline UpperCamelCase : str = ['''prompt'''] UpperCamelCase : Tuple = ['''prompt'''] UpperCamelCase : Optional[int] = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] UpperCamelCase : int = False @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return 32 @property def UpperCAmelCase_ ( self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self ): return 8 @property def UpperCAmelCase_ ( self ): __A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_A ) @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : int = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __A : Optional[Any] = PriorTransformer(**_A ) return model @property def UpperCAmelCase_ ( self ): torch.manual_seed(0 ) __A : List[str] = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __A : List[Any] = ShapERenderer(**_A ) return model def UpperCAmelCase_ ( self ): __A : List[str] = self.dummy_prior __A : Optional[int] = self.dummy_text_encoder __A : List[Any] = self.dummy_tokenizer __A : str = self.dummy_renderer __A : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=_A , clip_sample=_A , clip_sample_range=1.0 , ) __A : Any = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def UpperCAmelCase_ ( self , _A , _A=0 ): if str(_A ).startswith('mps' ): __A : List[Any] = torch.manual_seed(_A ) else: __A : Dict = torch.Generator(device=_A ).manual_seed(_A ) __A : int = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def UpperCAmelCase_ ( self ): __A : Tuple = 'cpu' __A : Any = self.get_dummy_components() __A : Tuple = self.pipeline_class(**_A ) __A : List[str] = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Tuple = pipe(**self.get_dummy_inputs(_A ) ) __A : int = output.images[0] __A : str = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __A : Any = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase_ ( self ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCAmelCase_ ( self ): __A : List[str] = torch_device == 'cpu' __A : Any = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_A , relax_max_difference=_A , ) def UpperCAmelCase_ ( self ): __A : Any = self.get_dummy_components() __A : Any = self.pipeline_class(**_A ) __A : Dict = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : Any = 1 __A : Dict = 2 __A : Tuple = self.get_dummy_inputs(_A ) for key in inputs.keys(): if key in self.batch_params: __A : Optional[int] = batch_size * [inputs[key]] __A : Optional[int] = pipe(**_A , num_images_per_prompt=_A )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self ): __A : List[str] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __A : Dict = ShapEPipeline.from_pretrained('openai/shap-e' ) __A : int = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A : str = torch.Generator(device=_A ).manual_seed(0 ) __A : Tuple = pipe( 'a shark' , generator=_A , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_A , _A )
77
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase : int = logging.get_logger(__name__) UpperCAmelCase : int = { 'facebook/data2vec-text-base': 'https://huggingface.co/data2vec/resolve/main/config.json', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Tuple = 'data2vec-text' def __init__( self , _A=30522 , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=2 , _A=0.0_2 , _A=1e-1_2 , _A=1 , _A=0 , _A=2 , _A="absolute" , _A=True , _A=None , **_A , ): super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __A : List[str] = vocab_size __A : List[str] = hidden_size __A : str = num_hidden_layers __A : Any = num_attention_heads __A : Optional[int] = hidden_act __A : Optional[int] = intermediate_size __A : Union[str, Any] = hidden_dropout_prob __A : List[Any] = attention_probs_dropout_prob __A : Optional[Any] = max_position_embeddings __A : Union[str, Any] = type_vocab_size __A : Optional[int] = initializer_range __A : List[str] = layer_norm_eps __A : Any = position_embedding_type __A : int = use_cache __A : List[Any] = classifier_dropout class _A( snake_case__ ): """simple docstring""" @property def UpperCAmelCase_ ( self ): if self.task == "multiple-choice": __A : Optional[Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __A : List[str] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
717
from __future__ import annotations import math def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if len(a ) != 2 or len(a[0] ) != 2 or len(a ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __A : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> str: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(a ) ) ] def _SCREAMING_SNAKE_CASE ( a ) -> tuple[list, list, list, list]: if len(a ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __A : str = len(a ) __A : List[Any] = matrix_length // 2 __A : List[str] = [[a[i][j] for j in range(a , a )] for i in range(a )] __A : Dict = [ [a[i][j] for j in range(a , a )] for i in range(a , a ) ] __A : int = [[a[i][j] for j in range(a )] for i in range(a )] __A : Any = [[a[i][j] for j in range(a )] for i in range(a , a )] return top_left, top_right, bot_left, bot_right def _SCREAMING_SNAKE_CASE ( a ) -> tuple[int, int]: return len(a ), len(matrix[0] ) def _SCREAMING_SNAKE_CASE ( a ) -> None: print('\n'.join(str(a ) for line in matrix ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a ) == (2, 2): return default_matrix_multiplication(a , a ) __A , __A , __A , __A : str = split_matrix(a ) __A , __A , __A , __A : List[Any] = split_matrix(a ) __A : Any = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Tuple = actual_strassen(matrix_addition(a , a ) , a ) __A : List[str] = actual_strassen(matrix_addition(a , a ) , a ) __A : Optional[int] = actual_strassen(a , matrix_subtraction(a , a ) ) __A : Any = actual_strassen(matrix_addition(a , a ) , matrix_addition(a , a ) ) __A : Any = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) ) __A : List[Any] = matrix_addition(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) __A : Union[str, Any] = matrix_addition(a , a ) __A : str = matrix_addition(a , a ) __A : Dict = matrix_subtraction(matrix_subtraction(matrix_addition(a , a ) , a ) , a ) # construct the new matrix from our 4 quadrants __A : List[Any] = [] for i in range(len(a ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(a ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _SCREAMING_SNAKE_CASE ( a , a ) -> list: if matrix_dimensions(a )[1] != matrix_dimensions(a )[0]: __A : Dict = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"""Matrix A: {matrixa}\n""" F"""Matrix B: {matrixa}""" ) raise Exception(a ) __A : int = matrix_dimensions(a ) __A : Any = matrix_dimensions(a ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __A : List[Any] = max(*a , *a ) __A : Optional[Any] = int(math.pow(2 , math.ceil(math.loga(a ) ) ) ) __A : Union[str, Any] = matrixa __A : Optional[int] = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __A : str = actual_strassen(a , a ) # Removing the additional zeros for i in range(0 , a ): if i < dimensiona[0]: for _ in range(dimensiona[1] , a ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": UpperCAmelCase : Union[str, Any] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] UpperCAmelCase : Optional[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
77
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Optional[Any] = { """configuration_nllb_moe""": [ """NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """NllbMoeConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = [ """NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST""", """NllbMoeForConditionalGeneration""", """NllbMoeModel""", """NllbMoePreTrainedModel""", """NllbMoeTop2Router""", """NllbMoeSparseMLP""", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys UpperCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
718
def _SCREAMING_SNAKE_CASE ( a ) -> int: __A : List[str] = [] __A : Tuple = [] __A : Union[str, Any] = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, } # Priority of each operator __A : List[str] = len(a ) if (len(a ) > 7) else 7 # Print table header for output print( 'Symbol'.center(8 ) , 'Stack'.center(a ) , 'Postfix'.center(a ) , sep=' | ' , ) print('-' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(a ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(a ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(a ) == 0: stack.append(a ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(a ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(a ) # push x to stack print( x.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format while len(a ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ' '.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format return "".join(a ) # return Postfix as str def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: __A : List[Any] = list(infix[::-1] ) # reverse the infix equation for i in range(len(a ) ): if infix[i] == "(": __A : List[str] = ')' # change "(" to ")" elif infix[i] == ")": __A : Any = '(' # change ")" to "(" return (infix_2_postfix(''.join(a ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": UpperCAmelCase : List[str] = input('''\nEnter an Infix Equation = ''') # Input an Infix equation UpperCAmelCase : Union[str, Any] = ''''''.join(Infix.split()) # Remove spaces from the input print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
77
0
from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase : List[str] = '''T5Config''' class _A( __lowerCamelCase ): """simple docstring""" UpperCamelCase : Dict = '''mt5''' UpperCamelCase : Optional[int] = MTaConfig class _A( __lowerCamelCase ): """simple docstring""" UpperCamelCase : str = '''mt5''' UpperCamelCase : Optional[int] = MTaConfig class _A( __lowerCamelCase ): """simple docstring""" UpperCamelCase : Tuple = '''mt5''' UpperCamelCase : int = MTaConfig
719
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : Tuple = { '''facebook/mask2former-swin-small-coco-instance''': ( '''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json''' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase : int = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" UpperCamelCase : Union[str, Any] = '''mask2former''' UpperCamelCase : Any = ['''swin'''] UpperCamelCase : Union[str, Any] = {'''hidden_size''': '''hidden_dim'''} def __init__( self , _A = None , _A = 256 , _A = 256 , _A = 256 , _A = 1024 , _A = "relu" , _A = 6 , _A = 10 , _A = 8 , _A = 0.0 , _A = 2048 , _A = False , _A = False , _A = 4 , _A = 255 , _A = 100 , _A = 0.1 , _A = 2.0 , _A = 5.0 , _A = 5.0 , _A = 12544 , _A = 3.0 , _A = 0.7_5 , _A = 0.0_2 , _A = 1.0 , _A = True , _A = [4, 8, 16, 32] , _A = None , **_A , ): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) __A : Optional[int] = CONFIG_MAPPING['swin']( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=_A , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(_A , _A ): __A : Dict = backbone_config.pop('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[str] = config_class.from_dict(_A ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) __A : Optional[int] = backbone_config __A : Optional[Any] = feature_size __A : Any = mask_feature_size __A : Optional[Any] = hidden_dim __A : Union[str, Any] = encoder_feedforward_dim __A : Optional[Any] = activation_function __A : List[Any] = encoder_layers __A : Union[str, Any] = decoder_layers __A : Dict = num_attention_heads __A : Tuple = dropout __A : Dict = dim_feedforward __A : Tuple = pre_norm __A : Dict = enforce_input_projection __A : Optional[int] = common_stride __A : Optional[Any] = ignore_value __A : str = num_queries __A : List[Any] = no_object_weight __A : List[str] = class_weight __A : List[Any] = mask_weight __A : List[Any] = dice_weight __A : Tuple = train_num_points __A : Optional[Any] = oversample_ratio __A : Union[str, Any] = importance_sample_ratio __A : Union[str, Any] = init_std __A : int = init_xavier_std __A : Union[str, Any] = use_auxiliary_loss __A : Union[str, Any] = feature_strides __A : List[Any] = output_auxiliary_logits __A : Optional[Any] = decoder_layers super().__init__(**_A ) @classmethod def UpperCAmelCase_ ( cls , _A , **_A ): return cls( backbone_config=_A , **_A , ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = copy.deepcopy(self.__dict__ ) __A : List[Any] = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output
77
0
def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> int: if height >= 1: move_tower(height - 1 , a , a , a ) move_disk(a , a ) move_tower(height - 1 , a , a , a ) def _SCREAMING_SNAKE_CASE ( a , a ) -> List[str]: print('moving disk from' , a , 'to' , a ) def _SCREAMING_SNAKE_CASE ( ) -> Tuple: __A : Dict = int(input('Height of hanoi: ' ).strip() ) move_tower(a , 'A' , 'B' , 'C' ) if __name__ == "__main__": main()
720
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : str = '''conditional_detr''' UpperCamelCase : int = ['''past_key_values'''] UpperCamelCase : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , _A=True , _A=None , _A=3 , _A=300 , _A=6 , _A=2048 , _A=8 , _A=6 , _A=2048 , _A=8 , _A=0.0 , _A=0.0 , _A=True , _A="relu" , _A=256 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1.0 , _A=False , _A="sine" , _A="resnet50" , _A=True , _A=False , _A=2 , _A=5 , _A=2 , _A=1 , _A=1 , _A=2 , _A=5 , _A=2 , _A=0.2_5 , **_A , ): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __A : List[str] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_A , _A ): __A : Tuple = backbone_config.get('model_type' ) __A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __A : List[Any] = config_class.from_dict(_A ) __A : Tuple = use_timm_backbone __A : List[str] = backbone_config __A : Dict = num_channels __A : int = num_queries __A : int = d_model __A : str = encoder_ffn_dim __A : List[str] = encoder_layers __A : Optional[Any] = encoder_attention_heads __A : Union[str, Any] = decoder_ffn_dim __A : List[Any] = decoder_layers __A : Optional[Any] = decoder_attention_heads __A : Any = dropout __A : Any = attention_dropout __A : int = activation_dropout __A : Optional[int] = activation_function __A : Union[str, Any] = init_std __A : Union[str, Any] = init_xavier_std __A : Optional[Any] = encoder_layerdrop __A : int = decoder_layerdrop __A : List[str] = encoder_layers __A : str = auxiliary_loss __A : Union[str, Any] = position_embedding_type __A : Optional[int] = backbone __A : List[str] = use_pretrained_backbone __A : List[Any] = dilation # Hungarian matcher __A : List[str] = class_cost __A : Optional[int] = bbox_cost __A : Dict = giou_cost # Loss coefficients __A : Optional[int] = mask_loss_coefficient __A : Union[str, Any] = dice_loss_coefficient __A : List[Any] = cls_loss_coefficient __A : Dict = bbox_loss_coefficient __A : Tuple = giou_loss_coefficient __A : Tuple = focal_alpha super().__init__(is_encoder_decoder=_A , **_A ) @property def UpperCAmelCase_ ( self ): return self.encoder_attention_heads @property def UpperCAmelCase_ ( self ): return self.d_model def UpperCAmelCase_ ( self ): __A : str = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __A : Dict = self.backbone_config.to_dict() __A : Union[str, Any] = self.__class__.model_type return output class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = version.parse('''1.11''' ) @property def UpperCAmelCase_ ( self ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def UpperCAmelCase_ ( self ): return 1e-5 @property def UpperCAmelCase_ ( self ): return 12
77
0
import torch def _SCREAMING_SNAKE_CASE ( ) -> Any: if torch.cuda.is_available(): __A : Any = torch.cuda.device_count() else: __A : Optional[Any] = 0 print(F"""Successfully ran on {num_gpus} GPUs""" ) if __name__ == "__main__": main()
721
import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class _A( nn.Module ): """simple docstring""" def __init__( self ): super().__init__() __A : List[str] = nn.Linear(3 , 4 ) __A : Optional[Any] = nn.BatchNormad(4 ) __A : List[Any] = nn.Linear(4 , 5 ) def UpperCAmelCase_ ( self , _A ): return self.lineara(self.batchnorm(self.lineara(_A ) ) ) class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Dict = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , model.state_dict() ) __A : str = os.path.join(_A , 'index.json' ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: __A : Optional[int] = os.path.join(_A , F"""{key}.dat""" ) self.assertTrue(os.path.isfile(_A ) ) # TODO: add tests on the fact weights are properly loaded def UpperCAmelCase_ ( self ): __A : Dict = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: __A : Tuple = torch.randn(2 , 3 , dtype=_A ) with TemporaryDirectory() as tmp_dir: __A : int = offload_weight(_A , 'weight' , _A , {} ) __A : Union[str, Any] = os.path.join(_A , 'weight.dat' ) self.assertTrue(os.path.isfile(_A ) ) self.assertDictEqual(_A , {'weight': {'shape': [2, 3], 'dtype': str(_A ).split('.' )[1]}} ) __A : List[str] = load_offloaded_weight(_A , index['weight'] ) self.assertTrue(torch.equal(_A , _A ) ) def UpperCAmelCase_ ( self ): __A : int = ModelForTest() __A : Union[str, Any] = model.state_dict() __A : Optional[Any] = {k: v for k, v in state_dict.items() if 'linear2' not in k} __A : str = {k: v for k, v in state_dict.items() if 'linear2' in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : List[str] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) __A : Union[str, Any] = {k: v for k, v in state_dict.items() if 'weight' in k} __A : List[Any] = {k: v for k, v in state_dict.items() if 'weight' not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) __A : Optional[int] = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(_A , _A ) # Duplicates are removed __A : str = OffloadedWeightsLoader(state_dict=_A , save_folder=_A ) # Every key is there with the right value self.assertEqual(sorted(_A ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(_A , weight_map[key] ) ) def UpperCAmelCase_ ( self ): __A : Dict = {'a.1': 0, 'a.10': 1, 'a.2': 2} __A : str = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1': 0, 'a.2': 2} ) __A : Optional[Any] = {'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2} __A : Any = extract_submodules_state_dict(_A , ['a.1', 'a.2'] ) self.assertDictEqual(_A , {'a.1.a': 0, 'a.2.a': 2} )
77
0
'''simple docstring''' import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class _A: """simple docstring""" def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=True , _A=True , _A=True , _A=99 , _A=32 , _A=5 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=128 , _A=32 , _A=16 , _A=2 , _A=0.0_2 , _A=3 , _A=4 , _A=None , ): __A : Tuple = parent __A : List[Any] = batch_size __A : Dict = seq_length __A : int = is_training __A : Optional[Any] = use_input_mask __A : Optional[Any] = use_token_type_ids __A : str = use_labels __A : List[str] = vocab_size __A : Optional[Any] = hidden_size __A : Union[str, Any] = num_hidden_layers __A : Optional[int] = num_attention_heads __A : int = intermediate_size __A : List[str] = hidden_act __A : Any = hidden_dropout_prob __A : Optional[Any] = attention_probs_dropout_prob __A : List[Any] = max_position_embeddings __A : int = type_vocab_size __A : str = type_sequence_label_size __A : Optional[Any] = initializer_range __A : List[Any] = num_labels __A : List[Any] = num_choices __A : Any = scope def UpperCAmelCase_ ( self ): __A : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : int = None if self.use_input_mask: __A : Dict = random_attention_mask([self.batch_size, self.seq_length] ) __A : List[str] = None if self.use_token_type_ids: __A : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Tuple = None __A : str = None __A : Optional[Any] = None if self.use_labels: __A : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : Dict = ids_tensor([self.batch_size] , self.num_choices ) __A : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return NezhaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self ): ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Tuple = self.prepare_config_and_inputs() __A : str = True __A : Optional[Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __A : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : Any = NezhaModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __A : int = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase ) __A : Dict = model(_lowerCamelCase , token_type_ids=_lowerCamelCase ) __A : Any = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Tuple = True __A : Tuple = NezhaModel(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __A : Tuple = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , encoder_attention_mask=_lowerCamelCase , ) __A : Dict = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , ) __A : Optional[Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[Any] = NezhaForMaskedLM(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __A : Union[str, Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : Dict = NezhaForNextSentencePrediction(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __A : Optional[Any] = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : int = NezhaForPreTraining(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __A : Tuple = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase , next_sentence_label=_lowerCamelCase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : Union[str, Any] = NezhaForQuestionAnswering(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __A : List[Any] = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , start_positions=_lowerCamelCase , end_positions=_lowerCamelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : Optional[Any] = self.num_labels __A : int = NezhaForSequenceClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __A : str = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : Optional[Any] = self.num_labels __A : int = NezhaForTokenClassification(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __A : int = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : Optional[int] = self.num_choices __A : Union[str, Any] = NezhaForMultipleChoice(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __A : List[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __A : Tuple = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __A : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __A : Optional[int] = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : int = config_and_inputs __A : Any = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" UpperCamelCase : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) UpperCamelCase : List[str] = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : List[Any] = True def UpperCAmelCase_ ( self , _A , _A , _A=False ): __A : Tuple = super()._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) if return_labels: if model_class in get_values(_lowerCamelCase ): __A : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_lowerCamelCase ) __A : Optional[int] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_lowerCamelCase ) return inputs_dict def UpperCAmelCase_ ( self ): __A : Optional[int] = NezhaModelTester(self ) __A : List[str] = ConfigTester(self , config_class=_lowerCamelCase , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def UpperCAmelCase_ ( self ): __A : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_lowerCamelCase ) def UpperCAmelCase_ ( self ): # This regression test was failing with PyTorch < 1.3 ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : str = self.model_tester.prepare_config_and_inputs_for_decoder() __A : Optional[int] = None self.model_tester.create_and_check_model_as_decoder( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ) def UpperCAmelCase_ ( self ): __A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_lowerCamelCase ) def UpperCAmelCase_ ( self ): __A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*_lowerCamelCase ) def UpperCAmelCase_ ( self ): __A : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_lowerCamelCase ) def UpperCAmelCase_ ( self ): __A : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_lowerCamelCase ) def UpperCAmelCase_ ( self ): __A : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_lowerCamelCase ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_lowerCamelCase ) @slow def UpperCAmelCase_ ( self ): for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A : int = NezhaModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @slow @require_torch_gpu def UpperCAmelCase_ ( self ): __A , __A : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __A : Union[str, Any] = True __A : int = model_class(config=_lowerCamelCase ) __A : Optional[int] = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) __A : Tuple = torch.jit.trace( _lowerCamelCase , (inputs_dict['input_ids'].to('cpu' ), inputs_dict['attention_mask'].to('cpu' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(_lowerCamelCase , os.path.join(_lowerCamelCase , 'bert.pt' ) ) __A : int = torch.jit.load(os.path.join(_lowerCamelCase , 'bert.pt' ) , map_location=_lowerCamelCase ) loaded(inputs_dict['input_ids'].to(_lowerCamelCase ) , inputs_dict['attention_mask'].to(_lowerCamelCase ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ ( self ): __A : Tuple = NezhaModel.from_pretrained('sijunhe/nezha-cn-base' ) __A : Optional[Any] = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __A : Union[str, Any] = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __A : Union[str, Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] __A : Union[str, Any] = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , _lowerCamelCase ) __A : Optional[Any] = torch.tensor([[[0.0_6_8_5, 0.2_4_4_1, 0.1_1_0_2], [0.0_6_0_0, 0.1_9_0_6, 0.1_3_4_9], [0.0_2_2_1, 0.0_8_1_9, 0.0_5_8_6]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _lowerCamelCase , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): __A : Any = NezhaForMaskedLM.from_pretrained('sijunhe/nezha-cn-base' ) __A : str = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __A : Optional[int] = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __A : Any = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] __A : int = torch.Size((1, 6, 21128) ) self.assertEqual(output.shape , _lowerCamelCase ) __A : int = torch.tensor( [[-2.7_9_3_9, -1.7_9_0_2, -2.2_1_8_9], [-2.8_5_8_5, -1.8_9_0_8, -2.3_7_2_3], [-2.6_4_9_9, -1.7_7_5_0, -2.2_5_5_8]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _lowerCamelCase , atol=1e-4 ) )
700
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator from accelerate.utils.dataclasses import DistributedType class _A( snake_case__ ): """simple docstring""" def __init__( self , _A ): __A : Any = data def __iter__( self ): for element in self.data: yield element def _SCREAMING_SNAKE_CASE ( a=True ) -> Any: __A : List[Any] = Accelerator(even_batches=a ) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str: if iterable: __A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) ) else: __A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) ) __A : Optional[Any] = DataLoader(a , batch_size=a ) __A : Optional[int] = accelerator.prepare(a ) return dl def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]: __A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a ) __A : Tuple = [len(batch[0] ) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : int = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , ) def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : str = create_accelerator(even_batches=a ) verify_dataloader_batch_sizes( a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , ) verify_dataloader_batch_sizes( a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , ) def _SCREAMING_SNAKE_CASE ( ) -> str: __A : Optional[Any] = create_accelerator(even_batches=a ) __A : str = torch.nn.Linear(1 , 1 ) __A : Optional[int] = accelerator.prepare(a ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : str = [] with accelerator.join_uneven_inputs([ddp_model] ): for batch_idx, batch in enumerate(a ): __A : Dict = ddp_model(batch[0].float() ) __A : List[str] = output.sum() loss.backward() batch_idxs.append(a ) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]: with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([Mock()] ): pass assert issubclass(w[-1].category , a ) assert "only supported for multi-GPU" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: __A : int = True __A : Union[str, Any] = False __A : Optional[int] = create_accelerator(even_batches=a ) __A : int = torch.nn.Linear(1 , 1 ) __A : List[Any] = accelerator.prepare(a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) __A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 ) with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : List[str] = train_dl.batch_sampler.even_batches __A : Dict = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Any = True __A : List[Any] = False __A : Tuple = create_accelerator(even_batches=a ) __A : List[str] = torch.nn.Linear(1 , 1 ) __A : Optional[Any] = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) __A : int = create_dataloader(a , dataset_size=3 , batch_size=1 ) with warnings.catch_warnings(): warnings.filterwarnings('ignore' ) try: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): __A : Tuple = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def _SCREAMING_SNAKE_CASE ( ) -> Dict: __A : Any = create_accelerator() __A : Union[str, Any] = torch.nn.Linear(1 , 1 ) __A : str = accelerator.prepare(a ) create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a ) with warnings.catch_warnings(record=a ) as w: with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ): pass assert issubclass(w[-1].category , a ) assert "only supported for map-style datasets" in str(w[-1].message ) def _SCREAMING_SNAKE_CASE ( ) -> List[str]: __A : str = create_accelerator() accelerator.print('Test that even_batches variable ensures uniform batches across processes' ) test_default_ensures_even_batch_sizes() accelerator.print('Run tests with even_batches disabled' ) test_can_disable_even_batches() accelerator.print('Test joining uneven inputs' ) test_can_join_uneven_inputs() accelerator.print('Test overriding even_batches when joining uneven inputs' ) test_join_can_override_even_batches() accelerator.print('Test overriding even_batches for mixed dataloader types' ) test_join_can_override_for_mixed_type_dataloaders() accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' ) test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print('Test join with non DDP distributed raises warning' ) __A : int = accelerator.state.distributed_type __A : Tuple = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(a ) __A : str = original_state if __name__ == "__main__": main()
77
0
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase : Dict = {'vocab_file': 'sentencepiece.model'} UpperCAmelCase : Optional[Any] = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCAmelCase : int = { 'google/rembert': 2_56, } class _A( lowerCamelCase__ ): """simple docstring""" UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase : str = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _A , _A=False , _A=True , _A=True , _A="[CLS]" , _A="[SEP]" , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , **_A , ): super().__init__( do_lower_case=__lowerCamelCase , remove_space=__lowerCamelCase , keep_accents=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , pad_token=__lowerCamelCase , cls_token=__lowerCamelCase , mask_token=__lowerCamelCase , **__lowerCamelCase , ) __A : int = do_lower_case __A : Optional[Any] = remove_space __A : Any = keep_accents __A : Dict = vocab_file __A : List[str] = spm.SentencePieceProcessor() self.sp_model.Load(__lowerCamelCase ) @property def UpperCAmelCase_ ( self ): return len(self.sp_model ) def UpperCAmelCase_ ( self ): __A : int = {self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): __A : Any = self.__dict__.copy() __A : Dict = None return state def __setstate__( self , _A ): __A : Dict = d __A : List[str] = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def UpperCAmelCase_ ( self , _A , _A=False ): __A : str = self.sp_model.EncodeAsPieces(__lowerCamelCase ) return pieces def UpperCAmelCase_ ( self , _A ): return self.sp_model.PieceToId(__lowerCamelCase ) def UpperCAmelCase_ ( self , _A ): return self.sp_model.IdToPiece(__lowerCamelCase ) def UpperCAmelCase_ ( self , _A ): __A : Any = self.sp_model.decode_pieces(__lowerCamelCase ) return out_string def UpperCAmelCase_ ( self , _A , _A = None ): __A : str = [self.sep_token_id] __A : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCAmelCase_ ( self , _A , _A = None , _A = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__lowerCamelCase )) + [1] + ([0] * len(__lowerCamelCase )) + [1] return [1] + ([0] * len(__lowerCamelCase )) + [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : Union[str, Any] = [self.sep_token_id] __A : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): if not os.path.isdir(__lowerCamelCase ): logger.error('Vocabulary path ({}) should be a directory'.format(__lowerCamelCase ) ) return __A : Union[str, Any] = os.path.join( __lowerCamelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ): copyfile(self.vocab_file , __lowerCamelCase ) return (out_vocab_file,)
701
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : str = { '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''', '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''', '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''', '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''', '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''', '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''', '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''', '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''', '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''', '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''', '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''', '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''', } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = '''codegen''' UpperCamelCase : List[str] = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ): __A : Any = vocab_size __A : Tuple = n_ctx __A : Union[str, Any] = n_positions __A : Optional[Any] = n_embd __A : Any = n_layer __A : Dict = n_head __A : Union[str, Any] = n_inner __A : List[Any] = rotary_dim __A : str = activation_function __A : Any = resid_pdrop __A : Tuple = embd_pdrop __A : Tuple = attn_pdrop __A : Union[str, Any] = layer_norm_epsilon __A : str = initializer_range __A : Optional[Any] = use_cache __A : Union[str, Any] = bos_token_id __A : Tuple = eos_token_id super().__init__( bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A ) class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A = "default" , _A = None , _A = False , ): super().__init__(_A , task=_A , patching_specs=_A , use_past=_A ) if not getattr(self._config , 'pad_token_id' , _A ): # TODO: how to do that better? __A : Dict = 0 @property def UpperCAmelCase_ ( self ): __A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(_A , direction='inputs' ) __A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'} else: __A : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def UpperCAmelCase_ ( self ): return self._config.n_layer @property def UpperCAmelCase_ ( self ): return self._config.n_head def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): __A : Any = super(_A , self ).generate_dummy_inputs( _A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A ) # We need to order the input in the way they appears in the forward() __A : str = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch __A , __A : Any = common_inputs['input_ids'].shape # Not using the same length for past_key_values __A : Any = seqlen + 2 __A : List[str] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __A : Optional[Any] = [ (torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers ) ] __A : Tuple = common_inputs['attention_mask'] if self.use_past: __A : str = ordered_inputs['attention_mask'].dtype __A : List[Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self ): return 13
77
0
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a ) -> list[tuple[int, int]]: __A , __A : str = position __A : Optional[Any] = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] __A : Optional[int] = [] for position in positions: __A , __A : int = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(UpperCamelCase__ ) return permissible_positions def _SCREAMING_SNAKE_CASE ( a ) -> bool: return not any(elem == 0 for row in board for elem in row ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> bool: if is_complete(UpperCamelCase__ ): return True for position in get_valid_pos(UpperCamelCase__ , len(UpperCamelCase__ ) ): __A , __A : Optional[Any] = position if board[y][x] == 0: __A : List[Any] = curr + 1 if open_knight_tour_helper(UpperCamelCase__ , UpperCamelCase__ , curr + 1 ): return True __A : Union[str, Any] = 0 return False def _SCREAMING_SNAKE_CASE ( a ) -> list[list[int]]: __A : int = [[0 for i in range(UpperCamelCase__ )] for j in range(UpperCamelCase__ )] for i in range(UpperCamelCase__ ): for j in range(UpperCamelCase__ ): __A : Optional[int] = 1 if open_knight_tour_helper(UpperCamelCase__ , (i, j) , 1 ): return board __A : str = 0 __A : Optional[Any] = F"""Open Kight Tour cannot be performed on a board of size {n}""" raise ValueError(UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
702
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase : List[Any] = logging.get_logger(__name__) class _A( snake_case__ ): """simple docstring""" def __init__( self , *_A , **_A ): warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _A , ) super().__init__(*_A , **_A )
77
0
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a ) -> int: __A : list[list[int]] = [] create_all_state(1 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , [] , __SCREAMING_SNAKE_CASE ) return result def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> List[Any]: if level == 0: total_list.append(current_list[:] ) return for i in range(__SCREAMING_SNAKE_CASE , total_number - level + 2 ): current_list.append(__SCREAMING_SNAKE_CASE ) create_all_state(i + 1 , __SCREAMING_SNAKE_CASE , level - 1 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) current_list.pop() def _SCREAMING_SNAKE_CASE ( a ) -> Union[str, Any]: for i in total_list: print(*__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": UpperCAmelCase : List[Any] = 4 UpperCAmelCase : str = 2 UpperCAmelCase : Dict = generate_all_combinations(n, k) print_all_state(total_list)
703
import glob import os import random from string import ascii_lowercase, digits import cva UpperCAmelCase : Dict = '''''' UpperCAmelCase : Union[str, Any] = '''''' UpperCAmelCase : Optional[int] = '''''' UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal) def _SCREAMING_SNAKE_CASE ( ) -> None: __A , __A : List[Any] = get_dataset(a , a ) print('Processing...' ) __A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a ) for index, image in enumerate(a ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __A : Optional[int] = random_chars(32 ) __A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] __A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}""" cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F"""Success {index+1}/{len(a )} with {file_name}""" ) __A : int = [] for anno in new_annos[index]: __A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}""" annos_list.append(a ) with open(F"""/{file_root}.txt""" , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]: __A : int = [] __A : List[Any] = [] for label_file in glob.glob(os.path.join(a , '*.txt' ) ): __A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(a ) as in_file: __A : Tuple = in_file.readlines() __A : Dict = os.path.join(a , F"""{label_name}.jpg""" ) __A : Dict = [] for obj_list in obj_lists: __A : int = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(a ) labels.append(a ) return img_paths, labels def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]: __A : int = [] __A : Optional[Any] = [] __A : Dict = [] for idx in range(len(a ) ): __A : Dict = [] __A : Optional[Any] = img_list[idx] path_list.append(a ) __A : Union[str, Any] = anno_list[idx] __A : Optional[Any] = cva.imread(a ) if flip_type == 1: __A : Any = cva.flip(a , a ) for bbox in img_annos: __A : Dict = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __A : Union[str, Any] = cva.flip(a , a ) for bbox in img_annos: __A : Optional[Any] = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(a ) new_imgs_list.append(a ) return new_imgs_list, new_annos_lists, path_list def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" __A : List[Any] = ascii_lowercase + digits return "".join(random.choice(a ) for _ in range(a ) ) if __name__ == "__main__": main() print('''DONE ✅''')
77
0
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase : Dict = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( a ) -> Optional[Any]: __A : List[str] = torch.load(a , map_location='cpu' ) if "model" in sd.keys(): __A : Union[str, Any] = torch.load(a , map_location='cpu' )['model'] # pop unnecessary weights __A : Tuple = [ 'decoder.version', 'decoder.output_projection.weight', ] for key in keys_to_delete: if key in sd: sd.pop(a ) __A : Optional[Any] = { 'decoder.project_in_dim.weight': 'decoder.project_in.weight', 'decoder.project_out_dim.weight': 'decoder.project_out.weight', 'decoder.layer_norm.weight': 'decoder.final_layer_norm.weight', 'decoder.layer_norm.bias': 'decoder.final_layer_norm.bias', } for old_key, new_key in keys_to_rename.items(): if old_key in sd: __A : str = sd.pop(a ) __A : int = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: __A : Optional[int] = sd[key] # We split QKV in separate Q,K,V __A : Any = key.replace('.qkv_proj.' , '.q_proj.' ) __A : Optional[int] = key.replace('.qkv_proj.' , '.k_proj.' ) __A : Optional[Any] = key.replace('.qkv_proj.' , '.v_proj.' ) __A : Optional[int] = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 __A , __A , __A : Dict = torch.split(a , depth // 3 , dim=0 ) __A : Tuple = q __A : Dict = k __A : Tuple = v del sd[key] return sd @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a=None ) -> Union[str, Any]: __A : Dict = load_checkpoint(a ) if config is not None: __A : Dict = OPTConfig.from_pretrained(a ) else: __A : List[Any] = OPTConfig() __A : str = OPTModel(a ).half().eval() model.load_state_dict(a ) # Check results Path(a ).mkdir(exist_ok=a ) model.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--fairseq_path''', type=str, help=( '''path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:''' ''' https://huggingface.co/models?other=opt_metasq''' ), ) parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--hf_config''', default=None, type=str, help='''Define HF config.''') UpperCAmelCase : Optional[Any] = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
704
import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class _A: """simple docstring""" def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=True , _A=False , _A=True , _A=99 , _A=32 , _A=5 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=16 , _A=2 , _A=0.0_2 , _A=3 , _A=4 , _A=None , ): __A : Union[str, Any] = parent __A : List[str] = batch_size __A : Optional[int] = seq_length __A : List[Any] = is_training __A : Optional[Any] = use_input_mask __A : List[Any] = use_token_type_ids __A : Optional[Any] = use_labels __A : List[str] = vocab_size __A : Optional[int] = hidden_size __A : List[Any] = num_hidden_layers __A : int = num_attention_heads __A : Dict = intermediate_size __A : Any = hidden_act __A : Union[str, Any] = hidden_dropout_prob __A : Union[str, Any] = attention_probs_dropout_prob __A : Optional[int] = max_position_embeddings __A : Dict = type_vocab_size __A : Any = type_sequence_label_size __A : Dict = initializer_range __A : str = num_labels __A : Union[str, Any] = num_choices __A : str = scope def UpperCAmelCase_ ( self ): __A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : Optional[Any] = None if self.use_input_mask: __A : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __A : Dict = None if self.use_token_type_ids: __A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = None __A : List[Any] = None __A : List[Any] = None if self.use_labels: __A : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __A : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __A : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ): return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ): __A : List[str] = LlamaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A , attention_mask=_A ) __A : Any = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Dict = True __A : int = LlamaModel(_A ) model.to(_A ) model.eval() __A : str = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , ) __A : int = model( _A , attention_mask=_A , encoder_hidden_states=_A , ) __A : List[Any] = model(_A , attention_mask=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : Optional[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ): __A : int = True __A : List[Any] = True __A : List[Any] = LlamaForCausalLM(config=_A ) model.to(_A ) model.eval() # first forward pass __A : Optional[Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , ) __A : Optional[int] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __A : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) __A : str = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __A : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) __A : str = torch.cat([input_mask, next_mask] , dim=-1 ) __A : Tuple = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['hidden_states'][0] __A : Union[str, Any] = model( _A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , past_key_values=_A , output_hidden_states=_A , )['hidden_states'][0] # select random slice __A : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() __A : Tuple = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_A , _A , atol=1e-3 ) ) def UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) : Tuple = config_and_inputs __A : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () UpperCamelCase : Optional[Any] = (LlamaForCausalLM,) if is_torch_available() else () UpperCamelCase : Optional[Any] = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False def UpperCAmelCase_ ( self ): __A : List[Any] = LlamaModelTester(self ) __A : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A : int = type self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() __A : str = 3 __A : Optional[int] = input_dict['input_ids'] __A : int = input_ids.ne(1 ).to(_A ) __A : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : List[Any] = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Union[str, Any] = 3 __A : Tuple = 'single_label_classification' __A : Union[str, Any] = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __A : Optional[int] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self ): __A , __A : str = self.model_tester.prepare_config_and_inputs_for_common() __A : Any = 3 __A : int = 'multi_label_classification' __A : int = input_dict['input_ids'] __A : List[str] = input_ids.ne(1 ).to(_A ) __A : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __A : List[Any] = LlamaForSequenceClassification(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A , attention_mask=_A , labels=_A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def UpperCAmelCase_ ( self ): pass @parameterized.expand([('linear',), ('dynamic',)] ) def UpperCAmelCase_ ( self , _A ): __A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() __A : Dict = ids_tensor([1, 10] , config.vocab_size ) __A : Union[str, Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : List[Any] = LlamaModel(_A ) original_model.to(_A ) original_model.eval() __A : Dict = original_model(_A ).last_hidden_state __A : int = original_model(_A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __A : int = {'type': scaling_type, 'factor': 1_0.0} __A : str = LlamaModel(_A ) scaled_model.to(_A ) scaled_model.eval() __A : Dict = scaled_model(_A ).last_hidden_state __A : str = scaled_model(_A ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(_A , _A , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) ) @require_torch class _A( unittest.TestCase ): """simple docstring""" @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) __A : Union[str, Any] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 __A : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : int = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[str] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) __A : int = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) __A : Optional[int] = model(torch.tensor(_A ) ) # Expected mean on dim = -1 __A : List[str] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off __A : Optional[Any] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def UpperCAmelCase_ ( self ): __A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338] __A : List[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) __A : List[Any] = model(torch.tensor(_A ) ) __A : Tuple = torch.tensor( [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 ) # fmt: off __A : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' __A : List[str] = 'Simply put, the theory of relativity states that ' __A : Union[str, Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) __A : List[str] = tokenizer.encode(_A , return_tensors='pt' ) __A : Tuple = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=_A ) # greedy generation outputs __A : Union[str, Any] = model.generate(_A , max_new_tokens=64 , top_p=_A , temperature=1 , do_sample=_A ) __A : List[str] = tokenizer.decode(generated_ids[0] , skip_special_tokens=_A ) self.assertEqual(_A , _A )
77
0
def _SCREAMING_SNAKE_CASE ( a = 60_08_51_47_51_43 ) -> int: try: __A : Dict = int(_lowerCamelCase ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) __A : Tuple = 2 __A : List[str] = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 __A : str = i while n % i == 0: __A : str = n // i i += 1 return int(_lowerCamelCase ) if __name__ == "__main__": print(F"""{solution() = }""")
705
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
0
def _SCREAMING_SNAKE_CASE ( a , a ) -> Any: if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) __A : str = str(bin(_SCREAMING_SNAKE_CASE ) )[2:] # remove the leading "0b" __A : Optional[Any] = str(bin(_SCREAMING_SNAKE_CASE ) )[2:] # remove the leading "0b" __A : str = max(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) return "0b" + "".join( str(int(char_a == '1' and char_b == '1' ) ) for char_a, char_b in zip(a_binary.zfill(_SCREAMING_SNAKE_CASE ) , b_binary.zfill(_SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
706
import numpy as np from PIL import Image def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : Union[str, Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : List[Any] = 0 __A : Optional[Any] = 0 __A : List[Any] = 0 __A : Dict = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __A : Tuple = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : List[str] = 0 __A : Union[str, Any] = 0 return updated_arr def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray: __A : List[Any] = np.array(a ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __A : Dict = 0 __A : str = 0 __A : Tuple = 0 __A : Optional[int] = 0 # compute the shape of the output matrix __A : List[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __A : Any = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __A : Dict = 0 __A : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='''avgpooling''', verbose=True) # Loading the image UpperCAmelCase : int = Image.open('''path_to_image''') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
77
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## UpperCAmelCase : Optional[int] = 16 UpperCAmelCase : Union[str, Any] = 32 def _SCREAMING_SNAKE_CASE ( a , a = 16 ) -> Optional[Any]: __A : Any = AutoTokenizer.from_pretrained('bert-base-cased' ) __A : Optional[int] = load_dataset('glue' , 'mrpc' ) def tokenize_function(a ): # max_length=None => use the model max length (it's actually the default) __A : List[str] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=a , max_length=a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __A : Optional[Any] = datasets.map( a , batched=a , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __A : str = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(a ): # On TPU it's best to pad everything to the same length or training will be very slow. __A : int = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __A : int = 16 elif accelerator.mixed_precision != "no": __A : Any = 8 else: __A : Tuple = None return tokenizer.pad( a , padding='longest' , max_length=a , pad_to_multiple_of=a , return_tensors='pt' , ) # Instantiate dataloaders. __A : List[Any] = DataLoader( tokenized_datasets['train'] , shuffle=a , collate_fn=a , batch_size=a ) __A : str = DataLoader( tokenized_datasets['validation'] , shuffle=a , collate_fn=a , batch_size=a ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders UpperCAmelCase : Optional[int] = mocked_dataloaders # noqa: F811 def _SCREAMING_SNAKE_CASE ( a , a ) -> List[Any]: if os.environ.get('TESTING_MOCKED_DATALOADERS' , a ) == "1": __A : Dict = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: __A : Dict = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='all' , project_dir=args.project_dir ) else: __A : str = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __A : Dict = config["""lr"""] __A : Dict = int(config['num_epochs'] ) __A : Optional[int] = int(config['seed'] ) __A : Dict = int(config['batch_size'] ) set_seed(a ) __A : Optional[Any] = get_dataloaders(a , a ) __A : Optional[Any] = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation __A : int = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __A : Tuple = batch_size // MAX_GPU_BATCH_SIZE __A : Dict = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) __A : Union[str, Any] = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=a ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __A : List[str] = model.to(accelerator.device ) # Instantiate optimizer __A : List[str] = AdamW(params=model.parameters() , lr=a ) # Instantiate scheduler __A : List[str] = get_linear_schedule_with_warmup( optimizer=a , num_warmup_steps=1_00 , num_training_steps=(len(a ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __A : List[Any] = accelerator.prepare( a , a , a , a , a ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: __A : Tuple = os.path.split(a )[-1].split('.' )[0] accelerator.init_trackers(a , a ) # Now we train the model for epoch in range(a ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: __A : Optional[Any] = 0 for step, batch in enumerate(a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __A : Any = model(**a ) __A : Any = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() __A : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(a ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): __A : Any = model(**a ) __A : Union[str, Any] = outputs.logits.argmax(dim=-1 ) __A : Tuple = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=a , references=a , ) __A : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , a ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { 'accuracy': eval_metric['accuracy'], 'f1': eval_metric['f1'], 'train_loss': total_loss.item() / len(a ), 'epoch': epoch, } , step=a , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def _SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: __A : Optional[Any] = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=a , default=a , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) parser.add_argument( '--with_tracking' , action='store_true' , help='Whether to load in all available experiment trackers from the environment and use them for logging.' , ) parser.add_argument( '--project_dir' , type=a , default='logs' , help='Location on where to store experiment tracking logs` and relevent project information' , ) __A : Any = parser.parse_args() __A : List[Any] = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(a , a ) if __name__ == "__main__": main()
707
from __future__ import annotations from collections.abc import Callable def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float: __A : Any = x_start __A : List[str] = fnc(a ) __A : Optional[Any] = 0.0 for _ in range(a ): # Approximates small segments of curve as linear and solve # for trapezoidal area __A : Any = (x_end - x_start) / steps + xa __A : List[str] = fnc(a ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __A : Any = xa __A : Dict = fxa return area if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( a ) -> int: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') UpperCAmelCase : Tuple = 10 while i <= 10_00_00: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
77
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def _SCREAMING_SNAKE_CASE ( a ) -> Any: __A : Optional[Any] = [2, 2, 6, 2] if 'tiny' in model_name else [2, 2, 18, 2] __A : Dict = True if 'large' in model_name or 'huge' in model_name else False __A : Any = True if 'large' in model_name or 'huge' in model_name else False __A : Union[str, Any] = True if 'large' in model_name or 'huge' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: __A : Optional[int] = [3, 3, 3, 3] __A : int = [5, 5, 5, 5] elif "fl4" in model_name: __A : Any = [4, 4, 4, 4] __A : Any = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: __A : List[str] = [3, 3, 3, 3] if "lrf" in model_name: __A : Optional[int] = [3, 3, 3, 3] else: __A : Any = [2, 2, 2, 2] if "tiny" in model_name: __A : Tuple = 96 elif "small" in model_name: __A : Tuple = 96 elif "base" in model_name: __A : List[str] = 1_28 elif "large" in model_name: __A : Dict = 1_92 elif "xlarge" in model_name: __A : Union[str, Any] = 2_56 elif "huge" in model_name: __A : Union[str, Any] = 3_52 # set label information __A : int = 'huggingface/label-files' if "large" in model_name or "huge" in model_name: __A : Union[str, Any] = 'imagenet-22k-id2label.json' else: __A : List[str] = 'imagenet-1k-id2label.json' __A : Union[str, Any] = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type='dataset' ) , 'r' ) ) __A : Union[str, Any] = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} __A : int = {v: k for k, v in idalabel.items()} __A : Tuple = FocalNetConfig( embed_dim=lowerCAmelCase__ , depths=lowerCAmelCase__ , focal_levels=lowerCAmelCase__ , focal_windows=lowerCAmelCase__ , use_conv_embed=lowerCAmelCase__ , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__ , use_post_layernorm=lowerCAmelCase__ , use_layerscale=lowerCAmelCase__ , ) return config def _SCREAMING_SNAKE_CASE ( a ) -> List[str]: if "patch_embed.proj" in name: __A : Dict = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: __A : List[str] = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: __A : Optional[int] = 'encoder.' + name if "encoder.layers" in name: __A : List[Any] = name.replace('encoder.layers' , 'encoder.stages' ) if "downsample.proj" in name: __A : Union[str, Any] = name.replace('downsample.proj' , 'downsample.projection' ) if "blocks" in name: __A : Optional[int] = name.replace('blocks' , 'layers' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: __A : Union[str, Any] = name.replace('modulation.f' , 'modulation.projection_in' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: __A : int = name.replace('modulation.h' , 'modulation.projection_context' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: __A : Union[str, Any] = name.replace('modulation.proj' , 'modulation.projection_out' ) if name == "norm.weight": __A : List[str] = 'layernorm.weight' if name == "norm.bias": __A : Union[str, Any] = 'layernorm.bias' if "head" in name: __A : str = name.replace('head' , 'classifier' ) else: __A : Tuple = 'focalnet.' + name return name def _SCREAMING_SNAKE_CASE ( a , a , a=False ) -> Optional[int]: __A : List[str] = { 'focalnet-tiny': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth', 'focalnet-tiny-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth', 'focalnet-small': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth', 'focalnet-small-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth', 'focalnet-base': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth', 'focalnet-base-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth', 'focalnet-large-lrf-fl3': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth', 'focalnet-large-lrf-fl4': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth', 'focalnet-xlarge-lrf-fl3': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth', 'focalnet-xlarge-lrf-fl4': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth', } # fmt: on __A : Tuple = model_name_to_url[model_name] print('Checkpoint URL: ' , lowerCAmelCase__ ) __A : List[Any] = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='cpu' )['model'] # rename keys for key in state_dict.copy().keys(): __A : Dict = state_dict.pop(lowerCAmelCase__ ) __A : int = val __A : List[Any] = get_focalnet_config(lowerCAmelCase__ ) __A : Tuple = FocalNetForImageClassification(lowerCAmelCase__ ) model.eval() # load state dict model.load_state_dict(lowerCAmelCase__ ) # verify conversion __A : Dict = 'http://images.cocodataset.org/val2017/000000039769.jpg' __A : Union[str, Any] = BitImageProcessor( do_resize=lowerCAmelCase__ , size={'shortest_edge': 2_56} , resample=PILImageResampling.BILINEAR , do_center_crop=lowerCAmelCase__ , crop_size=2_24 , do_normalize=lowerCAmelCase__ , image_mean=lowerCAmelCase__ , image_std=lowerCAmelCase__ , ) __A : Optional[Any] = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) __A : List[str] = processor(images=lowerCAmelCase__ , return_tensors='pt' ) __A : Dict = transforms.Compose( [ transforms.Resize(2_56 ), transforms.CenterCrop(2_24 ), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) __A : str = image_transforms(lowerCAmelCase__ ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values , lowerCAmelCase__ , atol=1e-4 ) __A : Any = model(**lowerCAmelCase__ ) __A : Union[str, Any] = outputs.logits.argmax(-1 ).item() print('Predicted class:' , model.config.idalabel[predicted_class_idx] ) print('First values of logits:' , outputs.logits[0, :3] ) if model_name == "focalnet-tiny": __A : Dict = torch.tensor([0.2_166, -0.4_368, 0.2_191] ) elif model_name == "focalnet-tiny-lrf": __A : Optional[int] = torch.tensor([1.1_669, 0.0_125, -0.1_695] ) elif model_name == "focalnet-small": __A : Any = torch.tensor([0.4_917, -0.0_430, 0.1_341] ) elif model_name == "focalnet-small-lrf": __A : Tuple = torch.tensor([-0.2_588, -0.5_342, -0.2_331] ) elif model_name == "focalnet-base": __A : Union[str, Any] = torch.tensor([-0.1_655, -0.4_090, -0.1_730] ) elif model_name == "focalnet-base-lrf": __A : Any = torch.tensor([0.5_306, -0.0_483, -0.3_928] ) assert torch.allclose(outputs.logits[0, :3] , lowerCAmelCase__ , atol=1e-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F"""Saving model and processor of {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) if push_to_hub: print(F"""Pushing model and processor of {model_name} to the hub...""" ) model.push_to_hub(F"""{model_name}""" ) processor.push_to_hub(F"""{model_name}""" ) if __name__ == "__main__": UpperCAmelCase : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''focalnet-tiny''', type=str, help='''Name of the FocalNet model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to push the model and processor to the hub.''', ) UpperCAmelCase : Tuple = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
708
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def _SCREAMING_SNAKE_CASE ( ) -> None: print('Making key files...' ) make_key_files('rsa' , 10_24 ) print('Key files generation successful.' ) def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]: print('Generating prime p...' ) __A : Optional[Any] = rabinMiller.generate_large_prime(a ) print('Generating prime q...' ) __A : Union[str, Any] = rabinMiller.generate_large_prime(a ) __A : Tuple = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...' ) while True: __A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1: break print('Calculating d that is mod inverse of e...' ) __A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) ) __A : Dict = (n, e) __A : Dict = (n, d) return (public_key, private_key) def _SCREAMING_SNAKE_CASE ( a , a ) -> 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() __A , __A : Optional[int] = generate_key(a ) 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()
77
0
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[str] = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right UpperCAmelCase : List[Any] = 25_00_04 UpperCAmelCase : Optional[int] = 25_00_20 @require_sentencepiece @require_tokenizers class _A( a__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Any = MBartTokenizer UpperCamelCase : str = MBartTokenizerFast UpperCamelCase : List[Any] = True UpperCamelCase : List[Any] = True def UpperCAmelCase_ ( self ): super().setUp() # We have a SentencePiece fixture for testing __A : Tuple = MBartTokenizer(lowerCamelCase_ , keep_accents=lowerCamelCase_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : Tuple = MBartTokenizer(lowerCamelCase_ , keep_accents=lowerCamelCase_ ) __A : str = tokenizer.tokenize('This is a test' ) self.assertListEqual(lowerCamelCase_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __A : Dict = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( lowerCamelCase_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __A : str = tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) self.assertListEqual( lowerCamelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) __A : Tuple = tokenizer.convert_ids_to_tokens(lowerCamelCase_ ) self.assertListEqual( lowerCamelCase_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def UpperCAmelCase_ ( self ): if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return __A : Optional[Any] = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __A : Dict = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) __A : Optional[int] = self.tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) __A : int = tempfile.mkdtemp() __A : Optional[int] = tokenizer_r.save_pretrained(lowerCamelCase_ ) __A : Union[str, Any] = tokenizer_p.save_pretrained(lowerCamelCase_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) __A : Optional[int] = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(lowerCamelCase_ , lowerCamelCase_ ) # Checks everything loads correctly in the same way __A : Union[str, Any] = tokenizer_r.from_pretrained(lowerCamelCase_ ) __A : str = tokenizer_p.from_pretrained(lowerCamelCase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCamelCase_ , lowerCamelCase_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(lowerCamelCase_ ) # Save tokenizer rust, legacy_format=True __A : Optional[int] = tempfile.mkdtemp() __A : Dict = tokenizer_r.save_pretrained(lowerCamelCase_ , legacy_format=lowerCamelCase_ ) __A : Tuple = tokenizer_p.save_pretrained(lowerCamelCase_ ) # Checks it save with the same files self.assertSequenceEqual(lowerCamelCase_ , lowerCamelCase_ ) # Checks everything loads correctly in the same way __A : Optional[int] = tokenizer_r.from_pretrained(lowerCamelCase_ ) __A : List[Any] = tokenizer_p.from_pretrained(lowerCamelCase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCamelCase_ , lowerCamelCase_ ) ) shutil.rmtree(lowerCamelCase_ ) # Save tokenizer rust, legacy_format=False __A : Optional[int] = tempfile.mkdtemp() __A : Optional[int] = tokenizer_r.save_pretrained(lowerCamelCase_ , legacy_format=lowerCamelCase_ ) __A : Optional[int] = tokenizer_p.save_pretrained(lowerCamelCase_ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __A : str = tokenizer_r.from_pretrained(lowerCamelCase_ ) __A : str = tokenizer_p.from_pretrained(lowerCamelCase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowerCamelCase_ , lowerCamelCase_ ) ) shutil.rmtree(lowerCamelCase_ ) @require_torch @require_sentencepiece @require_tokenizers class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : Union[str, Any] = "facebook/mbart-large-en-ro" UpperCamelCase : Tuple = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] UpperCamelCase : Optional[int] = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] UpperCamelCase : Optional[int] = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE] @classmethod def UpperCAmelCase_ ( cls ): __A : Any = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) __A : Any = 1 return cls def UpperCAmelCase_ ( self ): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 250020 ) def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowerCamelCase_ ) def UpperCAmelCase_ ( self ): self.assertIn(lowerCamelCase_ , self.tokenizer.all_special_ids ) __A : List[str] = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] __A : int = self.tokenizer.decode(lowerCamelCase_ , skip_special_tokens=lowerCamelCase_ ) __A : List[str] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowerCamelCase_ ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) self.assertNotIn(self.tokenizer.eos_token , lowerCamelCase_ ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , lowerCamelCase_ ) __A : List[Any] = 10 __A : Optional[Any] = self.tokenizer(lowerCamelCase_ , max_length=lowerCamelCase_ , truncation=lowerCamelCase_ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , lowerCamelCase_ ) self.assertEqual(len(lowerCamelCase_ ) , lowerCamelCase_ ) def UpperCAmelCase_ ( self ): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [250026, 250001] ) def UpperCAmelCase_ ( self ): __A : Any = tempfile.mkdtemp() __A : Optional[Any] = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(lowerCamelCase_ ) __A : Optional[Any] = MBartTokenizer.from_pretrained(lowerCamelCase_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , lowerCamelCase_ ) @require_torch def UpperCAmelCase_ ( self ): __A : Any = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowerCamelCase_ , return_tensors='pt' ) __A : Any = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=lowerCamelCase_ , truncation=lowerCamelCase_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) __A : str = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) __A : List[str] = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , lowerCamelCase_ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.tokenizer(self.src_text , padding=lowerCamelCase_ , truncation=lowerCamelCase_ , max_length=3 , return_tensors='pt' ) __A : Tuple = self.tokenizer( text_target=self.tgt_text , padding=lowerCamelCase_ , truncation=lowerCamelCase_ , max_length=10 , return_tensors='pt' ) __A : Optional[Any] = targets['input_ids'] __A : List[str] = shift_tokens_right(lowerCamelCase_ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(lowerCamelCase_ ) , { # A, test, EOS, en_XX 'input_ids': [[62, 3034, 2, 250004]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 250001, } , )
709
import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = ProphetNetTokenizer UpperCamelCase : Tuple = False def UpperCAmelCase_ ( self ): super().setUp() __A : Any = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = 'UNwant\u00E9d,running' __A : List[str] = 'unwanted, running' return input_text, output_text def UpperCAmelCase_ ( self ): __A : Tuple = self.tokenizer_class(self.vocab_file ) __A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] ) def UpperCAmelCase_ ( self ): __A : int = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCAmelCase_ ( self ): __A : Union[str, Any] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCAmelCase_ ( self ): __A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCAmelCase_ ( self ): __A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCAmelCase_ ( self ): __A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __A : Optional[int] = {} for i, token in enumerate(_A ): __A : Tuple = i __A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCAmelCase_ ( self ): __A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __A : str = tokenizer(_A , padding=_A , return_tensors='pt' ) self.assertIsInstance(_A , _A ) __A : List[str] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(_A , _A ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCAmelCase_ ( self ): self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def UpperCAmelCase_ ( self ): __A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A ) __A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A ) __A : str = tokenizer.build_inputs_with_special_tokens(_A ) __A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
77
0
import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Any: __A : Optional[Any] = s.rsplit(a , a ) return new.join(a ) def _SCREAMING_SNAKE_CASE ( a ) -> Dict: # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if 'encoder.embeddings' not in key else 0 for key, param in state_dict.items() ) def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : List[Any] = {} __A : Union[str, Any] = ['group_1', 'group_2', 'group_3', 'group_4'] for key, value in state_dict.items(): for group_key in group_keys: if group_key in key: __A : int = key.replace(F"""{group_key}.""" , F"""{group_key}.group.""" ) if "res_path" in key: __A : str = key.replace('res_path.' , 'res_path.path.' ) if key.endswith('.w' ): __A : str = rreplace(a , '.w' , '.weight' , 1 ) if key.endswith('.b' ): __A : Union[str, Any] = rreplace(a , '.b' , '.bias' , 1 ) __A : Tuple = value.float() return upgrade @torch.no_grad() def _SCREAMING_SNAKE_CASE ( a , a , a=None , a=True ) -> Any: from dall_e import Encoder __A : List[str] = Encoder() if os.path.exists(a ): __A : List[Any] = torch.load(a ) else: __A : Any = torch.hub.load_state_dict_from_url(a ) if isinstance(a , a ): __A : Tuple = ckpt.state_dict() encoder.load_state_dict(a ) if config_path is not None: __A : Union[str, Any] = FlavaImageCodebookConfig.from_pretrained(a ) else: __A : Tuple = FlavaImageCodebookConfig() __A : Dict = FlavaImageCodebook(a ).eval() __A : List[Any] = encoder.state_dict() __A : Union[str, Any] = upgrade_state_dict(a ) hf_model.load_state_dict(a ) __A : List[str] = hf_model.state_dict() __A : Union[str, Any] = count_parameters(a ) __A : Any = count_parameters(a ) assert torch.allclose(a , a , atol=1e-3 ) if save_checkpoint: hf_model.save_pretrained(a ) else: return hf_state_dict if __name__ == "__main__": UpperCAmelCase__ : Dict = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to flava checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') UpperCAmelCase__ : Tuple = parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
710
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase : Any = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } UpperCAmelCase : Optional[int] = { '''bert-base-uncased''': 5_12, '''bert-large-uncased''': 5_12, '''bert-base-cased''': 5_12, '''bert-large-cased''': 5_12, '''bert-base-multilingual-uncased''': 5_12, '''bert-base-multilingual-cased''': 5_12, '''bert-base-chinese''': 5_12, '''bert-base-german-cased''': 5_12, '''bert-large-uncased-whole-word-masking''': 5_12, '''bert-large-cased-whole-word-masking''': 5_12, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12, '''bert-base-cased-finetuned-mrpc''': 5_12, '''bert-base-german-dbmdz-cased''': 5_12, '''bert-base-german-dbmdz-uncased''': 5_12, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_12, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12, '''wietsedv/bert-base-dutch-cased''': 5_12, } UpperCAmelCase : List[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class _A( snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : List[str] = BertTokenizer def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ): super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , ) __A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _A ) != do_lower_case or normalizer_state.get('strip_accents' , _A ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars ): __A : Any = getattr(_A , normalizer_state.pop('type' ) ) __A : Union[str, Any] = do_lower_case __A : Optional[int] = strip_accents __A : List[Any] = tokenize_chinese_chars __A : int = normalizer_class(**_A ) __A : Union[str, Any] = do_lower_case def UpperCAmelCase_ ( self , _A , _A=None ): __A : Tuple = [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 UpperCAmelCase_ ( self , _A , _A = None ): __A : Optional[Any] = [self.sep_token_id] __A : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self , _A , _A = None ): __A : int = self._tokenizer.model.save(_A , name=_A ) return tuple(_A )
77
0
import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def _SCREAMING_SNAKE_CASE ( a=None ) -> Dict: if subparsers is not None: __A : Optional[Any] = subparsers.add_parser('env' ) else: __A : Optional[Any] = argparse.ArgumentParser('Accelerate env command' ) parser.add_argument( '--config_file' , default=__lowerCAmelCase , help='The config file to use for the default values in the launching script.' ) if subparsers is not None: parser.set_defaults(func=__lowerCAmelCase ) return parser def _SCREAMING_SNAKE_CASE ( a ) -> Optional[Any]: __A : Optional[Any] = torch.__version__ __A : str = torch.cuda.is_available() __A : Union[str, Any] = is_xpu_available() __A : Tuple = is_npu_available() __A : Tuple = 'Not found' # Get the default from the config file. if args.config_file is not None or os.path.isfile(__lowerCAmelCase ): __A : List[Any] = load_config_from_file(args.config_file ).to_dict() __A : Union[str, Any] = { '`Accelerate` version': version, 'Platform': platform.platform(), 'Python version': platform.python_version(), 'Numpy version': np.__version__, 'PyTorch version (GPU?)': F"""{pt_version} ({pt_cuda_available})""", 'PyTorch XPU available': str(__lowerCAmelCase ), 'PyTorch NPU available': str(__lowerCAmelCase ), 'System RAM': F"""{psutil.virtual_memory().total / 10_24 ** 3:.2f} GB""", } if pt_cuda_available: __A : str = torch.cuda.get_device_name() print('\nCopy-and-paste the text below in your GitHub issue\n' ) print('\n'.join([F"""- {prop}: {val}""" for prop, val in info.items()] ) ) print('- `Accelerate` default config:' if args.config_file is None else '- `Accelerate` config passed:' ) __A : Union[str, Any] = ( '\n'.join([F"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ) else F"""\t{accelerate_config}""" ) print(__lowerCAmelCase ) __A : Dict = accelerate_config return info def _SCREAMING_SNAKE_CASE ( ) -> int: __A : int = env_command_parser() __A : Optional[Any] = parser.parse_args() env_command(__lowerCAmelCase ) return 0 if __name__ == "__main__": raise SystemExit(main())
711
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 UpperCAmelCase_ ( self ): debug_launcher(test_script.main ) def UpperCAmelCase_ ( self ): debug_launcher(test_ops.main )
77
0
import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=True , _A=True , _A=True , _A=99 , _A=32 , _A=5 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=16 , _A=2 , _A=0.0_2 , _A=4 , ): __A : Optional[int] = parent __A : Union[str, Any] = batch_size __A : str = seq_length __A : Tuple = is_training __A : List[str] = use_attention_mask __A : Dict = use_token_type_ids __A : List[Any] = use_labels __A : str = vocab_size __A : int = hidden_size __A : Optional[int] = num_hidden_layers __A : str = num_attention_heads __A : Optional[Any] = intermediate_size __A : Dict = hidden_act __A : Any = hidden_dropout_prob __A : str = attention_probs_dropout_prob __A : str = max_position_embeddings __A : Union[str, Any] = type_vocab_size __A : Tuple = type_sequence_label_size __A : Any = initializer_range __A : Optional[Any] = num_choices def UpperCAmelCase_ ( self ): __A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __A : List[str] = None if self.use_attention_mask: __A : str = random_attention_mask([self.batch_size, self.seq_length] ) __A : List[Any] = None if self.use_token_type_ids: __A : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __A : Dict = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_UpperCAmelCase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCAmelCase_ ( self ): __A : int = self.prepare_config_and_inputs() __A : Optional[Any] = config_and_inputs __A : int = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def UpperCAmelCase_ ( self ): __A : Tuple = self.prepare_config_and_inputs() __A : Any = config_and_inputs __A : List[Any] = True __A : Optional[int] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __A : Tuple = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class _A( _UpperCamelCase , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[Any] = True UpperCamelCase : List[str] = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def UpperCAmelCase_ ( self ): __A : Any = FlaxRobertaModelTester(self ) @slow def UpperCAmelCase_ ( self ): for model_class_name in self.all_model_classes: __A : Any = model_class_name.from_pretrained('roberta-base' , from_pt=_UpperCAmelCase ) __A : List[str] = model(np.ones((1, 1) ) ) self.assertIsNotNone(_UpperCAmelCase )
712
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : Tuple = tempfile.mkdtemp() # fmt: off __A : Union[str, Any] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on __A : Dict = dict(zip(_A , range(len(_A ) ) ) ) __A : int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : Optional[Any] = {'unk_token': '<unk>'} __A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : Union[str, Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : List[str] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[str] = self.get_tokenizer() __A : Dict = self.get_rust_tokenizer() __A : Optional[Any] = self.get_image_processor() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Any = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : int = self.get_image_processor(do_normalize=_A ) __A : int = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : List[Any] = self.prepare_image_inputs() __A : Any = image_processor(_A , return_tensors='np' ) __A : Tuple = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : Tuple = self.get_image_processor() __A : int = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = 'lower newer' __A : Any = processor(text=_A , return_tensors='np' ) __A : Dict = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Tuple = 'lower newer' __A : Union[str, Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[int] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Any = ['cat', 'nasa badge'] __A : List[Any] = processor(text=_A ) __A : Dict = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : int = [['cat', 'nasa badge'], ['person']] __A : str = processor(text=_A ) __A : int = 16 __A : Optional[int] = len(_A ) __A : int = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : int = 'google/owlvit-base-patch32' __A : List[str] = OwlViTProcessor.from_pretrained(_A ) __A : Tuple = ['cat', 'nasa badge'] __A : Dict = processor(text=_A ) __A : Tuple = 16 __A : str = inputs['input_ids'] __A : str = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Dict = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = self.prepare_image_inputs() __A : Tuple = self.prepare_image_inputs() __A : Any = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Union[str, Any] = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
77
0