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 _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[list[int]] = [[0 for _ in range(lowercase__ )] for _ in range(m + 1 )] for i in range(m + 1 ): SCREAMING_SNAKE_CASE__ : Any = 1 for n in range(m + 1 ): for k in range(1 , lowercase__ ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: SCREAMING_SNAKE_CASE__ : Dict = int(input("Enter a number: ").strip()) print(partition(n)) except ValueError: print("Please enter a number.") else: try: SCREAMING_SNAKE_CASE__ : int = int(sys.argv[1]) print(partition(n)) except ValueError: print("Please pass a number.")
636
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
1
from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = { 'repo_name': ['test_repo1', 'test_repo2', 'test_repo3'], 'path': ['test_1.py', 'test_2.py', 'unit_test.py'], 'content': ['a ' * 20, 'a ' * 30, 'b ' * 7], } SCREAMING_SNAKE_CASE__ : int = Dataset.from_dict(lowercase__ ) return dataset class snake_case ( UpperCamelCase_ ): def __lowercase( self : Tuple )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = get_dataset() SCREAMING_SNAKE_CASE__ : List[Any] = make_duplicate_clusters(a_ , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = get_dataset() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = deduplicate_dataset(a_ ) self.assertEqual(len(a_ ) , 2 ) print(a_ ) self.assertEqual(duplicate_clusters[0][0]['copies'] , 2 ) self.assertEqual(duplicate_clusters[0][0]['is_extreme'] , a_ )
636
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( 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 __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
1
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
1
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaInpaintPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = KandinskyVaaInpaintPipeline lowercase_ = ['image_embeds', 'negative_image_embeds', 'image', 'mask_image'] lowercase_ = [ 'image_embeds', 'negative_image_embeds', 'image', 'mask_image', ] lowercase_ = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] lowercase_ = False @property def __lowercase( self : Optional[int] )-> str: """simple docstring""" return 32 @property def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" return 32 @property def __lowercase( self : List[Any] )-> Dict: """simple docstring""" return self.time_input_dim @property def __lowercase( self : Tuple )-> Optional[int]: """simple docstring""" return self.time_input_dim * 4 @property def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" return 100 @property def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = { 'in_channels': 9, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'image', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } SCREAMING_SNAKE_CASE__ : Optional[int] = UNetaDConditionModel(**a_ ) return model @property def __lowercase( self : List[str] )-> Any: """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __lowercase( self : List[str] )-> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = VQModel(**self.dummy_movq_kwargs ) return model def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_unet SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_movq SCREAMING_SNAKE_CASE__ : Optional[int] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule='linear' , beta_start=0.0_0085 , beta_end=0.012 , clip_sample=a_ , set_alpha_to_one=a_ , steps_offset=1 , prediction_type='epsilon' , thresholding=a_ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def __lowercase( self : List[str] , a_ : Any , a_ : Dict=0 )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( a_ ) # create init_image SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ).resize((256, 256) ) # create mask SCREAMING_SNAKE_CASE__ : Optional[Any] = np.ones((64, 64) , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = 0 if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : List[str] = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = { 'image': init_image, 'mask_image': mask, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 64, 'width': 64, 'num_inference_steps': 2, 'guidance_scale': 4.0, 'output_type': 'np', } return inputs def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 'cpu' SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Dict = self.pipeline_class(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = pipe(**self.get_dummy_inputs(a_ ) ) SCREAMING_SNAKE_CASE__ : int = output.images SCREAMING_SNAKE_CASE__ : Any = pipe( **self.get_dummy_inputs(a_ ) , return_dict=a_ , )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_from_tuple[0, -3:, -3:, -1] print(F'''image.shape {image.shape}''' ) assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array( [0.5077_5903, 0.4952_7195, 0.4882_4543, 0.5019_2237, 0.4864_4906, 0.4937_3814, 0.478_0598, 0.4723_4827, 0.4832_7848] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' def __lowercase( self : List[str] )-> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : str )-> int: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_inpaint_cat_with_hat_fp16.npy' ) SCREAMING_SNAKE_CASE__ : List[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) SCREAMING_SNAKE_CASE__ : Any = np.ones((768, 768) , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = 0 SCREAMING_SNAKE_CASE__ : Optional[int] = 'a hat' SCREAMING_SNAKE_CASE__ : int = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(a_ ) SCREAMING_SNAKE_CASE__ : int = KandinskyVaaInpaintPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-decoder-inpaint' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipeline.to(a_ ) pipeline.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = pipe_prior( a_ , generator=a_ , num_inference_steps=5 , negative_prompt='' , ).to_tuple() SCREAMING_SNAKE_CASE__ : str = pipeline( image=a_ , mask_image=a_ , image_embeds=a_ , negative_image_embeds=a_ , generator=a_ , num_inference_steps=100 , height=768 , width=768 , output_type='np' , ) SCREAMING_SNAKE_CASE__ : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a_ , a_ )
636
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase__ ) , lowercase__ ) ] 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[:-1]: opened_file.write(int(lowercase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[int] = { "microsoft/layoutlmv3-base": "https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'layoutlmv3' def __init__( self : Dict , a_ : List[Any]=5_0265 , a_ : Optional[int]=768 , a_ : List[Any]=12 , a_ : Any=12 , a_ : List[str]=3072 , a_ : int="gelu" , a_ : Any=0.1 , a_ : int=0.1 , a_ : Optional[Any]=512 , a_ : Any=2 , a_ : Optional[int]=0.02 , a_ : Tuple=1e-5 , a_ : Any=1 , a_ : Tuple=0 , a_ : Union[str, Any]=2 , a_ : List[Any]=1024 , a_ : Dict=128 , a_ : Tuple=128 , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[Any]=128 , a_ : Union[str, Any]=64 , a_ : Tuple=256 , a_ : Union[str, Any]=True , a_ : Optional[Any]=True , a_ : List[Any]=True , a_ : List[str]=224 , a_ : Union[str, Any]=3 , a_ : Dict=16 , a_ : Tuple=None , **a_ : str , )-> Optional[int]: """simple docstring""" super().__init__( vocab_size=a_ , hidden_size=a_ , num_hidden_layers=a_ , num_attention_heads=a_ , intermediate_size=a_ , hidden_act=a_ , hidden_dropout_prob=a_ , attention_probs_dropout_prob=a_ , max_position_embeddings=a_ , type_vocab_size=a_ , initializer_range=a_ , layer_norm_eps=a_ , pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = max_ad_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] = coordinate_size SCREAMING_SNAKE_CASE__ : Optional[int] = shape_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = has_relative_attention_bias SCREAMING_SNAKE_CASE__ : str = rel_pos_bins SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rel_pos SCREAMING_SNAKE_CASE__ : Any = has_spatial_attention_bias SCREAMING_SNAKE_CASE__ : Tuple = rel_ad_pos_bins SCREAMING_SNAKE_CASE__ : int = max_rel_ad_pos SCREAMING_SNAKE_CASE__ : Optional[int] = text_embed SCREAMING_SNAKE_CASE__ : Optional[int] = visual_embed SCREAMING_SNAKE_CASE__ : Any = input_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : int = classifier_dropout class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.12' ) @property def __lowercase( self : int )-> Mapping[str, Mapping[int, str]]: """simple docstring""" # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) else: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels'}), ] ) @property def __lowercase( self : Union[str, Any] )-> float: """simple docstring""" return 1e-5 @property def __lowercase( self : Optional[int] )-> int: """simple docstring""" return 12 def __lowercase( self : Optional[int] , a_ : "ProcessorMixin" , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional["TensorType"] = None , a_ : int = 3 , a_ : int = 40 , a_ : int = 40 , )-> Mapping[str, Any]: """simple docstring""" setattr(processor.image_processor , 'apply_ocr' , a_ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Tuple = compute_effective_axis_dimension( a_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Dict = processor.tokenizer.num_special_tokens_to_add(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = compute_effective_axis_dimension( a_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=a_ ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE__ : List[str] = [[' '.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) SCREAMING_SNAKE_CASE__ : List[str] = self._generate_dummy_images(a_ , a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = dict( processor( a_ , text=a_ , boxes=a_ , return_tensors=a_ , ) ) return inputs
636
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
1
import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = 'AutoTokenizer' lowercase_ = ['tokenizer'] lowercase_ = { 'semantic_prompt': 1, 'coarse_prompt': 2, 'fine_prompt': 2, } def __init__( self : Union[str, Any] , a_ : List[Any] , a_ : Dict=None )-> Any: """simple docstring""" super().__init__(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = speaker_embeddings @classmethod def __lowercase( cls : List[str] , a_ : Union[str, Any] , a_ : Any="speaker_embeddings_path.json" , **a_ : int )-> List[str]: """simple docstring""" if speaker_embeddings_dict_path is not None: SCREAMING_SNAKE_CASE__ : Dict = get_file_from_repo( a_ , a_ , subfolder=kwargs.pop('subfolder' , a_ ) , cache_dir=kwargs.pop('cache_dir' , a_ ) , force_download=kwargs.pop('force_download' , a_ ) , proxies=kwargs.pop('proxies' , a_ ) , resume_download=kwargs.pop('resume_download' , a_ ) , local_files_only=kwargs.pop('local_files_only' , a_ ) , use_auth_token=kwargs.pop('use_auth_token' , a_ ) , revision=kwargs.pop('revision' , a_ ) , ) if speaker_embeddings_path is None: logger.warning( F'''`{os.path.join(a_ , a_ )}` does not exists , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`.''' ) SCREAMING_SNAKE_CASE__ : int = None else: with open(a_ ) as speaker_embeddings_json: SCREAMING_SNAKE_CASE__ : Union[str, Any] = json.load(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = None SCREAMING_SNAKE_CASE__ : Tuple = AutoTokenizer.from_pretrained(a_ , **a_ ) return cls(tokenizer=a_ , speaker_embeddings=a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple , a_ : Dict="speaker_embeddings_path.json" , a_ : int="speaker_embeddings" , a_ : bool = False , **a_ : Tuple , )-> Optional[Any]: """simple docstring""" if self.speaker_embeddings is not None: os.makedirs(os.path.join(a_ , a_ , 'v2' ) , exist_ok=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = {} SCREAMING_SNAKE_CASE__ : List[Any] = save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_voice_preset(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = {} for key in self.speaker_embeddings[prompt_key]: np.save( os.path.join( embeddings_dict['repo_or_path'] , a_ , F'''{prompt_key}_{key}''' ) , voice_preset[key] , allow_pickle=a_ , ) SCREAMING_SNAKE_CASE__ : int = os.path.join(a_ , F'''{prompt_key}_{key}.npy''' ) SCREAMING_SNAKE_CASE__ : str = tmp_dict with open(os.path.join(a_ , a_ ) , 'w' ) as fp: json.dump(a_ , a_ ) super().save_pretrained(a_ , a_ , **a_ ) def __lowercase( self : List[Any] , a_ : str = None , **a_ : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.speaker_embeddings[voice_preset] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset_paths: raise ValueError( F'''Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}].''' ) SCREAMING_SNAKE_CASE__ : Tuple = get_file_from_repo( self.speaker_embeddings.get('repo_or_path' , '/' ) , voice_preset_paths[key] , subfolder=kwargs.pop('subfolder' , a_ ) , cache_dir=kwargs.pop('cache_dir' , a_ ) , force_download=kwargs.pop('force_download' , a_ ) , proxies=kwargs.pop('proxies' , a_ ) , resume_download=kwargs.pop('resume_download' , a_ ) , local_files_only=kwargs.pop('local_files_only' , a_ ) , use_auth_token=kwargs.pop('use_auth_token' , a_ ) , revision=kwargs.pop('revision' , a_ ) , ) if path is None: raise ValueError( F'''`{os.path.join(self.speaker_embeddings.get('repo_or_path' , '/' ) , voice_preset_paths[key] )}` does not exists , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset} embeddings.''' ) SCREAMING_SNAKE_CASE__ : Tuple = np.load(a_ ) return voice_preset_dict def __lowercase( self : List[Any] , a_ : Optional[dict] = None )-> List[str]: """simple docstring""" for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset: raise ValueError(F'''Voice preset unrecognized, missing {key} as a key.''' ) if not isinstance(voice_preset[key] , np.ndarray ): raise ValueError(F'''{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.''' ) if len(voice_preset[key].shape ) != self.preset_shape[key]: raise ValueError(F'''{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.''' ) def __call__( self : Optional[Any] , a_ : Dict=None , a_ : Optional[Any]=None , a_ : Tuple="pt" , a_ : Union[str, Any]=256 , a_ : str=False , a_ : List[Any]=True , a_ : int=False , **a_ : List[str] , )-> Optional[Any]: """simple docstring""" if voice_preset is not None and not isinstance(a_ , a_ ): if ( isinstance(a_ , a_ ) and self.speaker_embeddings is not None and voice_preset in self.speaker_embeddings ): SCREAMING_SNAKE_CASE__ : int = self._load_voice_preset(a_ ) else: if isinstance(a_ , a_ ) and not voice_preset.endswith('.npz' ): SCREAMING_SNAKE_CASE__ : int = voice_preset + '.npz' SCREAMING_SNAKE_CASE__ : Tuple = np.load(a_ ) if voice_preset is not None: self._validate_voice_preset_dict(a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = BatchFeature(data=a_ , tensor_type=a_ ) SCREAMING_SNAKE_CASE__ : Any = self.tokenizer( a_ , return_tensors=a_ , padding='max_length' , max_length=a_ , return_attention_mask=a_ , return_token_type_ids=a_ , add_special_tokens=a_ , **a_ , ) if voice_preset is not None: SCREAMING_SNAKE_CASE__ : Dict = voice_preset return encoded_text
636
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
1
import os import sys import unittest SCREAMING_SNAKE_CASE__ : List[str] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) SCREAMING_SNAKE_CASE__ : str = os.path.join("tests", "models", "bert", "test_modeling_bert.py") SCREAMING_SNAKE_CASE__ : Dict = os.path.join("tests", "models", "blip", "test_modeling_blip.py") class snake_case ( unittest.TestCase ): def __lowercase( self : str )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = get_test_to_tester_mapping(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = get_test_to_tester_mapping(a_ ) SCREAMING_SNAKE_CASE__ : Any = {'BertModelTest': 'BertModelTester'} SCREAMING_SNAKE_CASE__ : int = { 'BlipModelTest': 'BlipModelTester', 'BlipTextImageModelTest': 'BlipTextImageModelsModelTester', 'BlipTextModelTest': 'BlipTextModelTester', 'BlipTextRetrievalModelTest': 'BlipTextRetrievalModelTester', 'BlipVQAModelTest': 'BlipVQAModelTester', 'BlipVisionModelTest': 'BlipVisionModelTester', } self.assertEqual(get_test_info.to_json(a_ ) , a_ ) self.assertEqual(get_test_info.to_json(a_ ) , a_ ) def __lowercase( self : Optional[int] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = get_model_to_test_mapping(a_ ) SCREAMING_SNAKE_CASE__ : Any = get_model_to_test_mapping(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = { 'BertForMaskedLM': ['BertModelTest'], 'BertForMultipleChoice': ['BertModelTest'], 'BertForNextSentencePrediction': ['BertModelTest'], 'BertForPreTraining': ['BertModelTest'], 'BertForQuestionAnswering': ['BertModelTest'], 'BertForSequenceClassification': ['BertModelTest'], 'BertForTokenClassification': ['BertModelTest'], 'BertLMHeadModel': ['BertModelTest'], 'BertModel': ['BertModelTest'], } SCREAMING_SNAKE_CASE__ : int = { 'BlipForConditionalGeneration': ['BlipTextImageModelTest'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTest'], 'BlipForQuestionAnswering': ['BlipVQAModelTest'], 'BlipModel': ['BlipModelTest'], 'BlipTextModel': ['BlipTextModelTest'], 'BlipVisionModel': ['BlipVisionModelTest'], } self.assertEqual(get_test_info.to_json(a_ ) , a_ ) self.assertEqual(get_test_info.to_json(a_ ) , a_ ) def __lowercase( self : List[str] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = get_model_to_tester_mapping(a_ ) SCREAMING_SNAKE_CASE__ : int = get_model_to_tester_mapping(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = { 'BertForMaskedLM': ['BertModelTester'], 'BertForMultipleChoice': ['BertModelTester'], 'BertForNextSentencePrediction': ['BertModelTester'], 'BertForPreTraining': ['BertModelTester'], 'BertForQuestionAnswering': ['BertModelTester'], 'BertForSequenceClassification': ['BertModelTester'], 'BertForTokenClassification': ['BertModelTester'], 'BertLMHeadModel': ['BertModelTester'], 'BertModel': ['BertModelTester'], } SCREAMING_SNAKE_CASE__ : Dict = { 'BlipForConditionalGeneration': ['BlipTextImageModelsModelTester'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTester'], 'BlipForQuestionAnswering': ['BlipVQAModelTester'], 'BlipModel': ['BlipModelTester'], 'BlipTextModel': ['BlipTextModelTester'], 'BlipVisionModel': ['BlipVisionModelTester'], } self.assertEqual(get_test_info.to_json(a_ ) , a_ ) self.assertEqual(get_test_info.to_json(a_ ) , a_ )
636
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
1
import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class snake_case : @staticmethod def __lowercase( *a_ : Union[str, Any] , **a_ : int )-> Tuple: """simple docstring""" pass @is_pipeline_test @require_vision @require_timm @require_torch class snake_case ( unittest.TestCase ): lowercase_ = MODEL_FOR_OBJECT_DETECTION_MAPPING def __lowercase( self : str , a_ : List[str] , a_ : int , a_ : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ObjectDetectionPipeline(model=a_ , image_processor=a_ ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def __lowercase( self : Any , a_ : Tuple , a_ : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = object_detector('./tests/fixtures/tests_samples/COCO/000000039769.png' , threshold=0.0 ) self.assertGreater(len(a_ ) , 0 ) for detected_object in outputs: self.assertEqual( a_ , { 'score': ANY(a_ ), 'label': ANY(a_ ), 'box': {'xmin': ANY(a_ ), 'ymin': ANY(a_ ), 'xmax': ANY(a_ ), 'ymax': ANY(a_ )}, } , ) import datasets SCREAMING_SNAKE_CASE__ : Tuple = datasets.load_dataset('hf-internal-testing/fixtures_image_utils' , 'image' , split='test' ) SCREAMING_SNAKE_CASE__ : List[str] = [ Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ), 'http://images.cocodataset.org/val2017/000000039769.jpg', # RGBA dataset[0]['file'], # LA dataset[1]['file'], # L dataset[2]['file'], ] SCREAMING_SNAKE_CASE__ : str = object_detector(a_ , threshold=0.0 ) self.assertEqual(len(a_ ) , len(a_ ) ) for outputs in batch_outputs: self.assertGreater(len(a_ ) , 0 ) for detected_object in outputs: self.assertEqual( a_ , { 'score': ANY(a_ ), 'label': ANY(a_ ), 'box': {'xmin': ANY(a_ ), 'ymin': ANY(a_ ), 'xmax': ANY(a_ ), 'ymax': ANY(a_ )}, } , ) @require_tf @unittest.skip('Object detection not implemented in TF' ) def __lowercase( self : Dict )-> Any: """simple docstring""" pass @require_torch def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = 'hf-internal-testing/tiny-detr-mobilenetsv3' SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoModelForObjectDetection.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Any = AutoFeatureExtractor.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : str = ObjectDetectionPipeline(model=a_ , feature_extractor=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' , threshold=0.0 ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ] , ) SCREAMING_SNAKE_CASE__ : List[str] = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] , threshold=0.0 , ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ [ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ], [ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ], ] , ) @require_torch @slow def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'facebook/detr-resnet-50' SCREAMING_SNAKE_CASE__ : List[str] = AutoModelForObjectDetection.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoFeatureExtractor.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = ObjectDetectionPipeline(model=a_ , feature_extractor=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], ] , ) @require_torch @slow def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'facebook/detr-resnet-50' SCREAMING_SNAKE_CASE__ : Optional[int] = pipeline('object-detection' , model=a_ ) SCREAMING_SNAKE_CASE__ : Dict = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], ] , ) @require_torch @slow def __lowercase( self : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 0.9985 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'facebook/detr-resnet-50' SCREAMING_SNAKE_CASE__ : Any = pipeline('object-detection' , model=a_ ) SCREAMING_SNAKE_CASE__ : Dict = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' , threshold=a_ ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] , ) @require_torch @require_pytesseract @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 'Narsil/layoutlmv3-finetuned-funsd' SCREAMING_SNAKE_CASE__ : str = 0.9993 SCREAMING_SNAKE_CASE__ : List[str] = pipeline('object-detection' , model=a_ , threshold=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = object_detector( 'https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png' ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [ {'score': 0.9993, 'label': 'I-ANSWER', 'box': {'xmin': 294, 'ymin': 254, 'xmax': 343, 'ymax': 264}}, {'score': 0.9993, 'label': 'I-ANSWER', 'box': {'xmin': 294, 'ymin': 254, 'xmax': 343, 'ymax': 264}}, ] , )
636
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
1
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): lowercase_ = [r'h\.\d+\.attn\.bias', r'h\.\d+\.attn\.masked_bias'] @register_to_config def __init__( self : Dict , a_ : int , a_ : int , a_ : Optional[int] = None , a_ : int = 5_0257 , a_ : int = 1024 , a_ : int = 768 , a_ : int = 12 , a_ : int = 12 , a_ : Optional[int] = None , a_ : str = "gelu_new" , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 0.1 , a_ : float = 1e-5 , a_ : float = 0.02 , a_ : bool = True , a_ : bool = True , a_ : bool = False , a_ : bool = False , )-> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Union[str, Any] = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( F'''`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and''' F''' `n_embd`: {n_embd} are not equal.''' ) SCREAMING_SNAKE_CASE__ : Tuple = prefix_inner_dim SCREAMING_SNAKE_CASE__ : Union[str, Any] = prefix_hidden_dim SCREAMING_SNAKE_CASE__ : List[Any] = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) SCREAMING_SNAKE_CASE__ : Optional[int] = ( nn.Linear(self.prefix_hidden_dim , a_ ) if self.prefix_hidden_dim is not None else nn.Identity() ) SCREAMING_SNAKE_CASE__ : Tuple = GPTaConfig( vocab_size=a_ , n_positions=a_ , n_embd=a_ , n_layer=a_ , n_head=a_ , n_inner=a_ , activation_function=a_ , resid_pdrop=a_ , embd_pdrop=a_ , attn_pdrop=a_ , layer_norm_epsilon=a_ , initializer_range=a_ , scale_attn_weights=a_ , use_cache=a_ , scale_attn_by_inverse_layer_idx=a_ , reorder_and_upcast_attn=a_ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = GPTaLMHeadModel(a_ ) def __lowercase( self : Any , a_ : torch.Tensor , a_ : torch.Tensor , a_ : Optional[torch.Tensor] = None , a_ : Optional[torch.Tensor] = None , )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.transformer.transformer.wte(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.encode_prefix(a_ ) SCREAMING_SNAKE_CASE__ : str = self.decode_prefix(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) SCREAMING_SNAKE_CASE__ : Tuple = torch.cat((dummy_token, input_ids) , dim=1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.transformer(inputs_embeds=a_ , labels=a_ , attention_mask=a_ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def __lowercase( self : Optional[int] , a_ : int , a_ : torch.device )-> torch.Tensor: """simple docstring""" return torch.zeros(a_ , self.prefix_length , dtype=torch.intaa , device=a_ ) def __lowercase( self : Tuple , a_ : Tuple )-> Dict: """simple docstring""" return self.encode_prefix(a_ ) @torch.no_grad() def __lowercase( self : Dict , a_ : Optional[int] , a_ : Optional[int] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = torch.split(a_ , 1 , dim=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Dict = [] for feature in features: SCREAMING_SNAKE_CASE__ : List[Any] = self.decode_prefix(feature.to(a_ ) ) # back to the clip feature # Only support beam search for now SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.generate_beam( input_embeds=a_ , device=a_ , eos_token_id=a_ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.stack(a_ ) SCREAMING_SNAKE_CASE__ : int = torch.stack(a_ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def __lowercase( self : Dict , a_ : List[str]=None , a_ : str=None , a_ : Union[str, Any]=None , a_ : int = 5 , a_ : int = 67 , a_ : float = 1.0 , a_ : Optional[int] = None , )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = eos_token_id SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : List[Any] = torch.ones(a_ , device=a_ , dtype=torch.int ) SCREAMING_SNAKE_CASE__ : Any = torch.zeros(a_ , device=a_ , dtype=torch.bool ) if input_embeds is not None: SCREAMING_SNAKE_CASE__ : List[Any] = input_embeds else: SCREAMING_SNAKE_CASE__ : Any = self.transformer.transformer.wte(a_ ) for i in range(a_ ): SCREAMING_SNAKE_CASE__ : Optional[Any] = self.transformer(inputs_embeds=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits SCREAMING_SNAKE_CASE__ : Any = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) SCREAMING_SNAKE_CASE__ : List[str] = logits.softmax(-1 ).log() if scores is None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = logits.topk(a_ , -1 ) SCREAMING_SNAKE_CASE__ : int = generated.expand(a_ , *generated.shape[1:] ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: SCREAMING_SNAKE_CASE__ : str = next_tokens else: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokens.expand(a_ , *tokens.shape[1:] ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat((tokens, next_tokens) , dim=1 ) else: SCREAMING_SNAKE_CASE__ : Any = -float(np.inf ) SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Dict = scores[:, None] + logits seq_lengths[~is_stopped] += 1 SCREAMING_SNAKE_CASE__ : List[str] = scores_sum / seq_lengths[:, None] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = scores_sum_average.view(-1 ).topk(a_ , -1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = next_tokens // scores_sum.shape[1] SCREAMING_SNAKE_CASE__ : Tuple = seq_lengths[next_tokens_source] SCREAMING_SNAKE_CASE__ : Tuple = next_tokens % scores_sum.shape[1] SCREAMING_SNAKE_CASE__ : Any = next_tokens.unsqueeze(1 ) SCREAMING_SNAKE_CASE__ : List[str] = tokens[next_tokens_source] SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat((tokens, next_tokens) , dim=1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = generated[next_tokens_source] SCREAMING_SNAKE_CASE__ : List[str] = scores_sum_average * seq_lengths SCREAMING_SNAKE_CASE__ : List[Any] = is_stopped[next_tokens_source] SCREAMING_SNAKE_CASE__ : int = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) SCREAMING_SNAKE_CASE__ : Tuple = torch.cat((generated, next_token_embed) , dim=1 ) SCREAMING_SNAKE_CASE__ : Tuple = is_stopped + next_tokens.eq(a_ ).squeeze() if is_stopped.all(): break SCREAMING_SNAKE_CASE__ : Union[str, Any] = scores / seq_lengths SCREAMING_SNAKE_CASE__ : List[str] = scores.argsort(descending=a_ ) # tokens tensors are already padded to max_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = [tokens[i] for i in order] SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.stack(a_ , dim=0 ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
636
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" 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 __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" 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=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
1
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
1
from __future__ import annotations import numpy as np def _a ( lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = np.shape(lowercase__ ) if rows != columns: SCREAMING_SNAKE_CASE__ : Dict = ( '\'table\' has to be of square shaped array but got a ' f'''{rows}x{columns} array:\n{table}''' ) raise ValueError(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((rows, columns) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((rows, columns) ) for i in range(lowercase__ ): for j in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = sum(lower[i][k] * upper[k][j] for k in range(lowercase__ ) ) if upper[j][j] == 0: raise ArithmeticError('No LU decomposition exists' ) SCREAMING_SNAKE_CASE__ : Optional[int] = (table[i][j] - total) / upper[j][j] SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 for j in range(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] = sum(lower[i][k] * upper[k][j] for k in range(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
636
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
1
def _a ( ): '''simple docstring''' return [list(range(10_00 - i , -10_00 - i , -1 ) ) for i in range(10_00 )] SCREAMING_SNAKE_CASE__ : Tuple = generate_large_matrix() SCREAMING_SNAKE_CASE__ : List[Any] = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def _a ( lowercase__ : list[list[int]] ): '''simple docstring''' assert all(row == sorted(lowercase__ , reverse=lowercase__ ) for row in grid ) assert all(list(lowercase__ ) == sorted(lowercase__ , reverse=lowercase__ ) for col in zip(*lowercase__ ) ) def _a ( lowercase__ : list[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: SCREAMING_SNAKE_CASE__ : str = (left + right) // 2 SCREAMING_SNAKE_CASE__ : str = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = mid + 1 else: SCREAMING_SNAKE_CASE__ : Any = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(lowercase__ ) def _a ( lowercase__ : list[list[int]] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Any = len(grid[0] ) for i in range(len(lowercase__ ) ): SCREAMING_SNAKE_CASE__ : Tuple = find_negative_index(grid[i][:bound] ) total += bound return (len(lowercase__ ) * len(grid[0] )) - total def _a ( lowercase__ : list[list[int]] ): '''simple docstring''' return len([number for row in grid for number in row if number < 0] ) def _a ( lowercase__ : list[list[int]] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = 0 for row in grid: for i, number in enumerate(lowercase__ ): if number < 0: total += len(lowercase__ ) - i break return total def _a ( ): '''simple docstring''' from timeit import timeit print('Running benchmarks' ) SCREAMING_SNAKE_CASE__ : int = ( 'from __main__ import count_negatives_binary_search, ' 'count_negatives_brute_force, count_negatives_brute_force_with_break, grid' ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): SCREAMING_SNAKE_CASE__ : List[str] = timeit(f'''{func}(grid=grid)''' , setup=lowercase__ , number=5_00 ) print(f'''{func}() took {time:0.4f} seconds''' ) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
636
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a_ , a_ ) def __call__( self : Any , a_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , a_ , ) return self.image_processor_class @property def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
1
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
636
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
1
# Copyright (c) 2021-, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def _a ( lowercase__ : Optional[int] , lowercase__ : Optional[int] , lowercase__ : Optional[int]=0 ): '''simple docstring''' if name is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None else: SCREAMING_SNAKE_CASE__ : str = '.' * max(0 , spaces - 2 ) + '# {:' + str(50 - spaces ) + 's}' SCREAMING_SNAKE_CASE__ : Optional[Any] = fmt.format(lowercase__ ) # Print and recurse (if needed). if isinstance(lowercase__ , lowercase__ ): if msg is not None: print(lowercase__ ) for k in val.keys(): recursive_print(lowercase__ , val[k] , spaces + 2 ) elif isinstance(lowercase__ , torch.Tensor ): print(lowercase__ , ':' , val.size() ) else: print(lowercase__ , ':' , lowercase__ ) def _a ( lowercase__ : Optional[Any] , lowercase__ : List[Any] , lowercase__ : Optional[int] , lowercase__ : List[Any] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] SCREAMING_SNAKE_CASE__ : int = (num_heads, hidden_size, num_splits) + input_shape[1:] SCREAMING_SNAKE_CASE__ : Union[str, Any] = param.view(*lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = param.transpose(0 , 2 ) SCREAMING_SNAKE_CASE__ : Any = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] SCREAMING_SNAKE_CASE__ : int = (num_heads, num_splits, hidden_size) + input_shape[1:] SCREAMING_SNAKE_CASE__ : List[str] = param.view(*lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = param.transpose(0 , 1 ).contiguous() SCREAMING_SNAKE_CASE__ : Tuple = param.view(*lowercase__ ) return param def _a ( lowercase__ : Optional[Any] , lowercase__ : Dict , lowercase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # old versions did not store training args SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_state_dict.get('args' , lowercase__ ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) SCREAMING_SNAKE_CASE__ : Tuple = ds_args.padded_vocab_size SCREAMING_SNAKE_CASE__ : List[str] = ds_args.max_position_embeddings SCREAMING_SNAKE_CASE__ : str = ds_args.hidden_size SCREAMING_SNAKE_CASE__ : Tuple = ds_args.num_layers SCREAMING_SNAKE_CASE__ : str = ds_args.num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple = ds_args.ffn_hidden_size # pprint(config) # The number of heads. SCREAMING_SNAKE_CASE__ : Union[str, Any] = config.n_head # The hidden_size per head. SCREAMING_SNAKE_CASE__ : Tuple = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): SCREAMING_SNAKE_CASE__ : List[Any] = input_state_dict['checkpoint_version'] else: SCREAMING_SNAKE_CASE__ : Dict = 0.0 # The model. SCREAMING_SNAKE_CASE__ : Tuple = input_state_dict['model'] # The language model. SCREAMING_SNAKE_CASE__ : Dict = model['language_model'] # The embeddings. SCREAMING_SNAKE_CASE__ : Union[str, Any] = lm['embedding'] # The word embeddings. SCREAMING_SNAKE_CASE__ : str = embeddings['word_embeddings']['weight'] # Truncate the embedding table to vocab_size rows. SCREAMING_SNAKE_CASE__ : List[str] = word_embeddings[: config.vocab_size, :] SCREAMING_SNAKE_CASE__ : List[Any] = word_embeddings # The position embeddings. SCREAMING_SNAKE_CASE__ : List[str] = embeddings['position_embeddings']['weight'] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] SCREAMING_SNAKE_CASE__ : int = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( f'''pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don\'t match''' ) # Store the position embeddings. SCREAMING_SNAKE_CASE__ : Dict = pos_embeddings # The transformer. SCREAMING_SNAKE_CASE__ : Any = lm['transformer'] if 'transformer' in lm.keys() else lm['encoder'] # The regex to extract layer names. SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r'layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)' ) # The simple map of names for "automated" rules. SCREAMING_SNAKE_CASE__ : Union[str, Any] = { 'attention.dense': '.attn.c_proj.', 'self_attention.dense': '.attn.c_proj.', 'mlp.dense_h_to_4h': '.mlp.c_fc.', 'mlp.dense_4h_to_h': '.mlp.c_proj.', } # Extract the layers. for key, val in transformer.items(): # Match the name. SCREAMING_SNAKE_CASE__ : Optional[int] = layer_re.match(lowercase__ ) # Stop if that's not a layer if m is None: break # The index of the layer. SCREAMING_SNAKE_CASE__ : List[Any] = int(m.group(1 ) ) # The name of the operation. SCREAMING_SNAKE_CASE__ : Union[str, Any] = m.group(2 ) # Is it a weight or a bias? SCREAMING_SNAKE_CASE__ : str = m.group(3 ) # The name of the layer. SCREAMING_SNAKE_CASE__ : List[Any] = f'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith('layernorm' ): SCREAMING_SNAKE_CASE__ : Dict = 'ln_1' if op_name.startswith('input' ) else 'ln_2' SCREAMING_SNAKE_CASE__ : Any = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. SCREAMING_SNAKE_CASE__ : Tuple = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = causal_mask # Insert a "dummy" tensor for masked_bias. SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor(-1E4 , dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Optional[Any] = masked_bias SCREAMING_SNAKE_CASE__ : Union[str, Any] = fix_query_key_value_ordering(lowercase__ , lowercase__ , 3 , lowercase__ , lowercase__ ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. SCREAMING_SNAKE_CASE__ : Optional[Any] = out_val.transpose(0 , 1 ).contiguous() # Store. SCREAMING_SNAKE_CASE__ : List[str] = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": SCREAMING_SNAKE_CASE__ : int = fix_query_key_value_ordering(lowercase__ , lowercase__ , 3 , lowercase__ , lowercase__ ) # Store. No change of shape. SCREAMING_SNAKE_CASE__ : Optional[int] = out_val # Transpose the weights. elif weight_or_bias == "weight": SCREAMING_SNAKE_CASE__ : List[str] = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : Union[str, Any] = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": SCREAMING_SNAKE_CASE__ : Optional[int] = megatron_to_transformers[op_name] SCREAMING_SNAKE_CASE__ : Tuple = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. SCREAMING_SNAKE_CASE__ : Optional[int] = transformer['final_layernorm.weight'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = transformer['final_layernorm.bias'] # For LM head, transformers' wants the matrix to weight embeddings. SCREAMING_SNAKE_CASE__ : List[Any] = word_embeddings # It should be done! return output_state_dict def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser() parser.add_argument('--print-checkpoint-structure' , action='store_true' ) parser.add_argument( 'path_to_checkpoint' , type=lowercase__ , help='Path to the checkpoint file (.zip archive or direct .pt file)' , ) parser.add_argument( '--config_file' , default='' , type=lowercase__ , help='An optional config json file describing the pre-trained model.' , ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() # Extract the basename. SCREAMING_SNAKE_CASE__ : str = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(f'''Extracting PyTorch state dictionary from {args.path_to_checkpoint}''' ) if args.path_to_checkpoint.endswith('.zip' ): with zipfile.ZipFile(args.path_to_checkpoint , 'r' ) as checkpoint: with checkpoint.open('release/mp_rank_00/model_optim_rng.pt' ) as pytorch_dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ , map_location='cpu' ) else: SCREAMING_SNAKE_CASE__ : Any = torch.load(args.path_to_checkpoint , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_state_dict.get('args' , lowercase__ ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: SCREAMING_SNAKE_CASE__ : List[Any] = 'gelu_fast' elif ds_args.openai_gelu: SCREAMING_SNAKE_CASE__ : Any = 'gelu_new' else: SCREAMING_SNAKE_CASE__ : Dict = 'gelu' else: # in the very early days this used to be "gelu_new" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'gelu_new' # Spell out all parameters in case the defaults change. SCREAMING_SNAKE_CASE__ : int = GPTaConfig( vocab_size=5_02_57 , n_positions=10_24 , n_embd=10_24 , n_layer=24 , n_head=16 , n_inner=40_96 , activation_function=lowercase__ , resid_pdrop=0.1 , embd_pdrop=0.1 , attn_pdrop=0.1 , layer_norm_epsilon=1E-5 , initializer_range=0.02 , summary_type='cls_index' , summary_use_proj=lowercase__ , summary_activation=lowercase__ , summary_proj_to_labels=lowercase__ , summary_first_dropout=0.1 , scale_attn_weights=lowercase__ , use_cache=lowercase__ , bos_token_id=5_02_56 , eos_token_id=5_02_56 , ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = GPTaConfig.from_json_file(args.config_file ) SCREAMING_SNAKE_CASE__ : Tuple = ['GPT2LMHeadModel'] # Convert. print('Converting' ) SCREAMING_SNAKE_CASE__ : Dict = convert_megatron_checkpoint(lowercase__ , lowercase__ , lowercase__ ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(lowercase__ , lowercase__ ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: SCREAMING_SNAKE_CASE__ : Any = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": SCREAMING_SNAKE_CASE__ : Optional[Any] = 'gpt2' elif tokenizer_type == "PretrainedFromHF": SCREAMING_SNAKE_CASE__ : str = ds_args.tokenizer_name_or_path else: raise ValueError(f'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: SCREAMING_SNAKE_CASE__ : Any = 'gpt2' SCREAMING_SNAKE_CASE__ : Optional[int] = AutoTokenizer.from_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = type(lowercase__ ).__name__ SCREAMING_SNAKE_CASE__ : Tuple = tokenizer_class # Store the config to file. print('Saving config' ) config.save_pretrained(lowercase__ ) # Save tokenizer based on args print(f'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(lowercase__ ) # Store the state_dict to file. SCREAMING_SNAKE_CASE__ : str = os.path.join(lowercase__ , 'pytorch_model.bin' ) print(f'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(lowercase__ , lowercase__ ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
636
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
1
from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput SCREAMING_SNAKE_CASE__ : List[Any] = 8 def _a ( lowercase__ : List[str] , lowercase__ : str=BITS ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = x.device SCREAMING_SNAKE_CASE__ : int = (x * 2_55).int().clamp(0 , 2_55 ) SCREAMING_SNAKE_CASE__ : int = 2 ** torch.arange(bits - 1 , -1 , -1 , device=lowercase__ ) SCREAMING_SNAKE_CASE__ : str = rearrange(lowercase__ , 'd -> d 1 1' ) SCREAMING_SNAKE_CASE__ : List[str] = rearrange(lowercase__ , 'b c h w -> b c 1 h w' ) SCREAMING_SNAKE_CASE__ : List[Any] = ((x & mask) != 0).float() SCREAMING_SNAKE_CASE__ : Dict = rearrange(lowercase__ , 'b c d h w -> b (c d) h w' ) SCREAMING_SNAKE_CASE__ : Any = bits * 2 - 1 return bits def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any]=BITS ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = x.device SCREAMING_SNAKE_CASE__ : List[Any] = (x > 0).int() SCREAMING_SNAKE_CASE__ : int = 2 ** torch.arange(bits - 1 , -1 , -1 , device=lowercase__ , dtype=torch.intaa ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = rearrange(lowercase__ , 'd -> d 1 1' ) SCREAMING_SNAKE_CASE__ : Optional[int] = rearrange(lowercase__ , 'b (c d) h w -> b c d h w' , d=8 ) SCREAMING_SNAKE_CASE__ : Dict = reduce(x * mask , 'b c d h w -> b c h w' , 'sum' ) return (dec / 2_55).clamp(0.0 , 1.0 ) def _a ( self : Any , lowercase__ : torch.FloatTensor , lowercase__ : int , lowercase__ : torch.FloatTensor , lowercase__ : float = 0.0 , lowercase__ : bool = True , lowercase__ : List[str]=None , lowercase__ : bool = True , ): '''simple docstring''' if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) SCREAMING_SNAKE_CASE__ : List[Any] = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.alphas_cumprod[timestep] SCREAMING_SNAKE_CASE__ : Dict = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod SCREAMING_SNAKE_CASE__ : Optional[int] = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Dict = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" SCREAMING_SNAKE_CASE__ : Optional[int] = self.bit_scale if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Any = torch.clamp(lowercase__ , -scale , lowercase__ ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) SCREAMING_SNAKE_CASE__ : Any = self._get_variance(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide SCREAMING_SNAKE_CASE__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : Any = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf SCREAMING_SNAKE_CASE__ : str = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 SCREAMING_SNAKE_CASE__ : Optional[Any] = model_output.device if torch.is_tensor(lowercase__ ) else 'cpu' SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.randn(model_output.shape , dtype=model_output.dtype , generator=lowercase__ ).to(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = self._get_variance(lowercase__ , lowercase__ ) ** 0.5 * eta * noise SCREAMING_SNAKE_CASE__ : str = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=lowercase__ , pred_original_sample=lowercase__ ) def _a ( self : List[Any] , lowercase__ : torch.FloatTensor , lowercase__ : int , lowercase__ : torch.FloatTensor , lowercase__ : Optional[int]="epsilon" , lowercase__ : Any=None , lowercase__ : bool = True , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = torch.split(lowercase__ , sample.shape[1] , dim=1 ) else: SCREAMING_SNAKE_CASE__ : Dict = None # 1. compute alphas, betas SCREAMING_SNAKE_CASE__ : Tuple = self.alphas_cumprod[t] SCREAMING_SNAKE_CASE__ : str = self.alphas_cumprod[t - 1] if t > 0 else self.one SCREAMING_SNAKE_CASE__ : int = 1 - alpha_prod_t SCREAMING_SNAKE_CASE__ : int = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": SCREAMING_SNAKE_CASE__ : Optional[Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": SCREAMING_SNAKE_CASE__ : List[str] = model_output else: raise ValueError(f'''Unsupported prediction_type {prediction_type}.''' ) # 3. Clip "predicted x_0" SCREAMING_SNAKE_CASE__ : str = self.bit_scale if self.config.clip_sample: SCREAMING_SNAKE_CASE__ : Any = torch.clamp(lowercase__ , -scale , lowercase__ ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf SCREAMING_SNAKE_CASE__ : str = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t SCREAMING_SNAKE_CASE__ : Dict = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf SCREAMING_SNAKE_CASE__ : Dict = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise SCREAMING_SNAKE_CASE__ : Tuple = 0 if t > 0: SCREAMING_SNAKE_CASE__ : Any = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=lowercase__ ).to(model_output.device ) SCREAMING_SNAKE_CASE__ : Any = (self._get_variance(lowercase__ , predicted_variance=lowercase__ ) ** 0.5) * noise SCREAMING_SNAKE_CASE__ : str = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=lowercase__ , pred_original_sample=lowercase__ ) class snake_case ( UpperCamelCase_ ): def __init__( self : List[Any] , a_ : UNetaDConditionModel , a_ : Union[DDIMScheduler, DDPMScheduler] , a_ : Optional[float] = 1.0 , )-> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[int] = bit_scale SCREAMING_SNAKE_CASE__ : List[str] = ( ddim_bit_scheduler_step if isinstance(a_ , a_ ) else ddpm_bit_scheduler_step ) self.register_modules(unet=a_ , scheduler=a_ ) @torch.no_grad() def __call__( self : int , a_ : Optional[int] = 256 , a_ : Optional[int] = 256 , a_ : Optional[int] = 50 , a_ : Optional[torch.Generator] = None , a_ : Optional[int] = 1 , a_ : Optional[str] = "pil" , a_ : bool = True , **a_ : Union[str, Any] , )-> Union[Tuple, ImagePipelineOutput]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = decimal_to_bits(a_ ) * self.bit_scale SCREAMING_SNAKE_CASE__ : Optional[int] = latents.to(self.device ) self.scheduler.set_timesteps(a_ ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual SCREAMING_SNAKE_CASE__ : Any = self.unet(a_ , a_ ).sample # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE__ : int = self.scheduler.step(a_ , a_ , a_ ).prev_sample SCREAMING_SNAKE_CASE__ : Any = bits_to_decimal(a_ ) if output_type == "pil": SCREAMING_SNAKE_CASE__ : str = self.numpy_to_pil(a_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a_ )
636
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
1
import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def _a ( lowercase__ : dict ): '''simple docstring''' return (data["data"], data["target"]) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = XGBClassifier() classifier.fit(lowercase__ , lowercase__ ) return classifier def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = load_iris() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = data_handling(lowercase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = train_test_split( lowercase__ , lowercase__ , test_size=0.25 ) SCREAMING_SNAKE_CASE__ : Tuple = iris['target_names'] # Create an XGBoost Classifier from the training data SCREAMING_SNAKE_CASE__ : Tuple = xgboost(lowercase__ , lowercase__ ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( lowercase__ , lowercase__ , lowercase__ , display_labels=lowercase__ , cmap='Blues' , normalize='true' , ) plt.title('Normalized Confusion Matrix - IRIS Dataset' ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
636
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
1
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) SCREAMING_SNAKE_CASE__ : int = str(bin(lowercase__ ) )[2:] # remove the leading "0b" SCREAMING_SNAKE_CASE__ : Union[str, Any] = str(bin(lowercase__ ) )[2:] SCREAMING_SNAKE_CASE__ : List[Any] = max(len(lowercase__ ) , len(lowercase__ ) ) return "0b" + "".join( str(int('1' in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(lowercase__ ) , b_binary.zfill(lowercase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
636
# Copyright 2023 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 torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
1
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : int )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) SCREAMING_SNAKE_CASE__ : Optional[int] = get_activation('gelu' ) self.assertTrue(torch.allclose(gelu_python(a_ ) , torch_builtin(a_ ) ) ) self.assertFalse(torch.allclose(gelu_python(a_ ) , gelu_new(a_ ) ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) SCREAMING_SNAKE_CASE__ : List[str] = get_activation('gelu' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_activation('gelu_10' ) SCREAMING_SNAKE_CASE__ : List[Any] = torch_builtin(a_ ) SCREAMING_SNAKE_CASE__ : Dict = geluaa(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(a_ ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def __lowercase( self : Optional[int] )-> List[Any]: """simple docstring""" get_activation('gelu' ) get_activation('gelu_10' ) get_activation('gelu_fast' ) get_activation('gelu_new' ) get_activation('gelu_python' ) get_activation('gelu_pytorch_tanh' ) get_activation('linear' ) get_activation('mish' ) get_activation('quick_gelu' ) get_activation('relu' ) get_activation('sigmoid' ) get_activation('silu' ) get_activation('swish' ) get_activation('tanh' ) with self.assertRaises(a_ ): get_activation('bogus' ) with self.assertRaises(a_ ): get_activation(a_ ) def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = get_activation('gelu' ) SCREAMING_SNAKE_CASE__ : Tuple = 1 SCREAMING_SNAKE_CASE__ : int = get_activation('gelu' ) self.assertEqual(acta.a , 1 ) with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Tuple = acta.a
636
import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[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 SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
1
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if isinstance(lowercase__ , collections.abc.Iterable ): return x return (x, x) @require_flax class snake_case : def __lowercase( self : Union[str, Any] , a_ : Optional[Any] , a_ : str )-> Tuple: """simple docstring""" pass def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" pass def __lowercase( self : str )-> Tuple: """simple docstring""" pass def __lowercase( self : int , a_ : np.ndarray , a_ : np.ndarray , a_ : float )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = np.abs((a - b) ).max() self.assertLessEqual(a_ , a_ , F'''Difference between torch and flax is {diff} (>= {tol}).''' ) def __lowercase( self : Union[str, Any] , a_ : str , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Any , a_ : str=None , **a_ : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxVisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : str = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], config.projection_dim) ) def __lowercase( self : Any , a_ : Any , a_ : str , a_ : Union[str, Any] , a_ : List[str] , a_ : Optional[Any]=None , **a_ : Optional[int] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.get_vision_text_model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = {'vision_model': vision_model, 'text_model': text_model} SCREAMING_SNAKE_CASE__ : List[str] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __lowercase( self : Union[str, Any] , a_ : int , a_ : Any , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any=None , **a_ : str )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.get_vision_text_model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = {'vision_model': vision_model, 'text_model': text_model} SCREAMING_SNAKE_CASE__ : Dict = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = FlaxVisionTextDualEncoderModel.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = after_output[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a_ , 1e-3 ) def __lowercase( self : List[Any] , a_ : int , a_ : Dict , a_ : str , a_ : Tuple , a_ : Any=None , **a_ : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.get_vision_text_model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'vision_model': vision_model, 'text_model': text_model} SCREAMING_SNAKE_CASE__ : int = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ ) SCREAMING_SNAKE_CASE__ : int = model( input_ids=a_ , pixel_values=a_ , attention_mask=a_ , output_attentions=a_ ) SCREAMING_SNAKE_CASE__ : str = output.vision_model_output.attentions self.assertEqual(len(a_ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : int = to_atuple(vision_model.config.image_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = to_atuple(vision_model.config.patch_size ) SCREAMING_SNAKE_CASE__ : List[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) SCREAMING_SNAKE_CASE__ : List[str] = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) SCREAMING_SNAKE_CASE__ : Dict = output.text_model_output.attentions self.assertEqual(len(a_ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __lowercase( self : List[Any] , a_ : Tuple , a_ : List[Any] , a_ : Optional[int] )-> Tuple: """simple docstring""" pt_model.to(a_ ) pt_model.eval() # prepare inputs SCREAMING_SNAKE_CASE__ : Optional[int] = inputs_dict SCREAMING_SNAKE_CASE__ : str = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = pt_model(**a_ ).to_tuple() SCREAMING_SNAKE_CASE__ : Optional[int] = fx_model(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(a_ , pt_output.numpy() , 4e-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : int = FlaxVisionTextDualEncoderModel.from_pretrained(a_ , from_pt=a_ ) SCREAMING_SNAKE_CASE__ : str = fx_model_loaded(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(a_ , pt_output.numpy() , 4e-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = VisionTextDualEncoderModel.from_pretrained(a_ , from_flax=a_ ) pt_model_loaded.to(a_ ) pt_model_loaded.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] = pt_model_loaded(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(a_ , pt_output_loaded.numpy() , 4e-2 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int , a_ : Dict )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = VisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = FlaxVisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : str = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , a_ ) SCREAMING_SNAKE_CASE__ : str = fx_state self.check_pt_flax_equivalence(a_ , a_ , a_ ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : str , a_ : Any )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = VisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxVisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = load_flax_weights_in_pytorch_model(a_ , fx_model.params ) self.check_pt_flax_equivalence(a_ , a_ , a_ ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**a_ ) def __lowercase( self : Union[str, Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**a_ ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() self.check_save_load(**a_ ) def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**a_ ) @is_pt_flax_cross_test def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = config_inputs_dict.pop('vision_config' ) SCREAMING_SNAKE_CASE__ : List[str] = config_inputs_dict.pop('text_config' ) SCREAMING_SNAKE_CASE__ : List[Any] = config_inputs_dict self.check_equivalence_pt_to_flax(a_ , a_ , a_ ) self.check_equivalence_flax_to_pt(a_ , a_ , a_ ) @slow def __lowercase( self : Union[str, Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.get_pretrained_model_and_inputs() SCREAMING_SNAKE_CASE__ : Dict = model_a(**a_ ) SCREAMING_SNAKE_CASE__ : Tuple = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = FlaxVisionTextDualEncoderModel.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : int = model_a(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = after_outputs[0] SCREAMING_SNAKE_CASE__ : int = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a_ , 1e-5 ) @require_flax class snake_case ( UpperCamelCase_ , unittest.TestCase ): def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-vit' , 'hf-internal-testing/tiny-bert' , vision_from_pt=a_ , text_from_pt=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = 13 SCREAMING_SNAKE_CASE__ : Dict = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) SCREAMING_SNAKE_CASE__ : int = random_attention_mask([batch_size, 4] ) SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def __lowercase( self : List[str] , a_ : Optional[Any] , a_ : Tuple )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = FlaxViTModel(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxBertModel(a_ ) return vision_model, text_model def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FlaxViTModelTester(self ) SCREAMING_SNAKE_CASE__ : int = FlaxBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple = vit_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : List[str] = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = vision_config_and_inputs SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-clip' , 'hf-internal-testing/tiny-bert' , vision_from_pt=a_ , text_from_pt=a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = 13 SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([batch_size, 4] ) SCREAMING_SNAKE_CASE__ : int = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def __lowercase( self : Union[str, Any] , a_ : Tuple , a_ : Dict )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = FlaxCLIPVisionModel(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = FlaxBertModel(a_ ) return vision_model, text_model def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FlaxCLIPVisionModelTester(self ) SCREAMING_SNAKE_CASE__ : Tuple = FlaxBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = clip_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = vision_config_and_inputs SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Optional[int] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian' , logit_scale_init_value=1.0 ) SCREAMING_SNAKE_CASE__ : Any = VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian' ) SCREAMING_SNAKE_CASE__ : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) SCREAMING_SNAKE_CASE__ : Any = processor( text=['una foto di un gatto', 'una foto di un cane'] , images=a_ , padding=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : str = model(**a_ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) SCREAMING_SNAKE_CASE__ : List[str] = np.array([[1.228_4727, 0.310_4122]] ) self.assertTrue(np.allclose(outputs.logits_per_image , a_ , atol=1e-3 ) )
636
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
1
import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): def __init__( self : List[Any] , *a_ : Tuple , **a_ : Tuple )-> None: """simple docstring""" warnings.warn( 'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use YolosImageProcessor instead.' , a_ , ) super().__init__(*a_ , **a_ )
636
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''simple docstring''' assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
636
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"configuration_sew": ["SEW_PRETRAINED_CONFIG_ARCHIVE_MAP", "SEWConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "SEW_PRETRAINED_MODEL_ARCHIVE_LIST", "SEWForCTC", "SEWForSequenceClassification", "SEWModel", "SEWPreTrainedModel", ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
636
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
636
1
from __future__ import annotations class snake_case : def __init__( self : Optional[int] , a_ : Dict=None )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = data SCREAMING_SNAKE_CASE__ : List[str] = None def __repr__( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self while temp: string_rep.append(F'''{temp.data}''' ) SCREAMING_SNAKE_CASE__ : List[str] = temp.next return "->".join(a_ ) def _a ( lowercase__ : list ): '''simple docstring''' if not elements_list: raise Exception('The Elements List is empty' ) SCREAMING_SNAKE_CASE__ : Optional[int] = Node(elements_list[0] ) for i in range(1 , len(lowercase__ ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = Node(elements_list[i] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = current.next return head def _a ( lowercase__ : Node ): '''simple docstring''' if head_node is not None and isinstance(lowercase__ , lowercase__ ): print_reverse(head_node.next ) print(head_node.data ) def _a ( ): '''simple docstring''' from doctest import testmod testmod() SCREAMING_SNAKE_CASE__ : Optional[Any] = make_linked_list([14, 52, 14, 12, 43] ) print('Linked List:' ) print(lowercase__ ) print('Elements in Reverse:' ) print_reverse(lowercase__ ) if __name__ == "__main__": main()
636
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
1
def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [0] * len(lowercase__ ) for i in range(1 , len(lowercase__ ) ): # use last results for better performance - dynamic programming SCREAMING_SNAKE_CASE__ : Union[str, Any] = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: SCREAMING_SNAKE_CASE__ : List[str] = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 SCREAMING_SNAKE_CASE__ : Tuple = j return prefix_result def _a ( lowercase__ : str ): '''simple docstring''' return max(prefix_function(lowercase__ ) ) if __name__ == "__main__": import doctest doctest.testmod()
636
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
1
import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): def __init__( self : List[Any] , *a_ : Optional[int] , **a_ : Optional[Any] )-> None: """simple docstring""" warnings.warn( 'The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use VideoMAEImageProcessor instead.' , a_ , ) super().__init__(*a_ , **a_ )
636
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( 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 __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[int] = { "configuration_mobilebert": [ "MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileBertConfig", "MobileBertOnnxConfig", ], "tokenization_mobilebert": ["MobileBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["MobileBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileBertForMaskedLM", "MobileBertForMultipleChoice", "MobileBertForNextSentencePrediction", "MobileBertForPreTraining", "MobileBertForQuestionAnswering", "MobileBertForSequenceClassification", "MobileBertForTokenClassification", "MobileBertLayer", "MobileBertModel", "MobileBertPreTrainedModel", "load_tf_weights_in_mobilebert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFMobileBertForMaskedLM", "TFMobileBertForMultipleChoice", "TFMobileBertForNextSentencePrediction", "TFMobileBertForPreTraining", "TFMobileBertForQuestionAnswering", "TFMobileBertForSequenceClassification", "TFMobileBertForTokenClassification", "TFMobileBertMainLayer", "TFMobileBertModel", "TFMobileBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
636
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
1
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name SCREAMING_SNAKE_CASE__ : str = "\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n >>> from diffusers.utils import load_image\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n ... )\n >>> pipe_prior.to(\"cuda\")\n\n >>> prompt = \"A red cartoon frog, 4k\"\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\n ... )\n >>> pipe.to(\"cuda\")\n\n >>> init_image = load_image(\n ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n ... \"/kandinsky/frog.png\"\n ... )\n\n >>> image = pipe(\n ... image=init_image,\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... strength=0.2,\n ... ).images\n\n >>> image[0].save(\"red_frog.png\")\n ```\n" def _a ( lowercase__ : Dict , lowercase__ : Union[str, Any] , lowercase__ : int=8 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE__ : List[str] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def _a ( lowercase__ : str , lowercase__ : List[str]=5_12 , lowercase__ : Dict=5_12 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) SCREAMING_SNAKE_CASE__ : Tuple = np.array(pil_image.convert('RGB' ) ) SCREAMING_SNAKE_CASE__ : Dict = arr.astype(np.floataa ) / 127.5 - 1 SCREAMING_SNAKE_CASE__ : str = np.transpose(lowercase__ , [2, 0, 1] ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.from_numpy(lowercase__ ).unsqueeze(0 ) return image class snake_case ( UpperCamelCase_ ): def __init__( self : Dict , a_ : UNetaDConditionModel , a_ : DDPMScheduler , a_ : VQModel , )-> List[Any]: """simple docstring""" super().__init__() self.register_modules( unet=a_ , scheduler=a_ , movq=a_ , ) SCREAMING_SNAKE_CASE__ : Any = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowercase( self : Tuple , a_ : List[Any] , a_ : int , a_ : Tuple )-> List[str]: """simple docstring""" # get the original timestep using init_timestep SCREAMING_SNAKE_CASE__ : Optional[int] = min(int(num_inference_steps * strength ) , a_ ) SCREAMING_SNAKE_CASE__ : Dict = max(num_inference_steps - init_timestep , 0 ) SCREAMING_SNAKE_CASE__ : Dict = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def __lowercase( self : Dict , a_ : Any , a_ : List[Any] , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : List[str] , a_ : int , a_ : List[Any]=None )-> List[str]: """simple docstring""" if not isinstance(a_ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(a_ )}''' ) SCREAMING_SNAKE_CASE__ : Dict = image.to(device=a_ , dtype=a_ ) SCREAMING_SNAKE_CASE__ : Dict = batch_size * num_images_per_prompt if image.shape[1] == 4: SCREAMING_SNAKE_CASE__ : Optional[int] = image else: if isinstance(a_ , a_ ) and len(a_ ) != batch_size: raise ValueError( F'''You have passed a list of generators of length {len(a_ )}, but requested an effective batch''' F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) elif isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(a_ ) ] SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat(a_ , dim=0 ) else: SCREAMING_SNAKE_CASE__ : str = self.movq.encode(a_ ).latent_dist.sample(a_ ) SCREAMING_SNAKE_CASE__ : int = self.movq.config.scaling_factor * init_latents SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cat([init_latents] , dim=0 ) SCREAMING_SNAKE_CASE__ : Dict = init_latents.shape SCREAMING_SNAKE_CASE__ : str = randn_tensor(a_ , generator=a_ , device=a_ , dtype=a_ ) # get latents SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler.add_noise(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = init_latents return latents def __lowercase( self : Union[str, Any] , a_ : List[Any]=0 )-> Dict: """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) SCREAMING_SNAKE_CASE__ : Any = torch.device(F'''cuda:{gpu_id}''' ) SCREAMING_SNAKE_CASE__ : List[str] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(a_ , a_ ) def __lowercase( self : List[Any] , a_ : Optional[int]=0 )-> List[str]: """simple docstring""" if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) SCREAMING_SNAKE_CASE__ : str = torch.device(F'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=a_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE__ : Optional[int] = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = cpu_offload_with_hook(a_ , a_ , prev_module_hook=a_ ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE__ : Union[str, Any] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(a_ , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(a_ ) def __call__( self : Any , a_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , a_ : Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] , a_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , a_ : int = 512 , a_ : int = 512 , a_ : int = 100 , a_ : float = 4.0 , a_ : float = 0.3 , a_ : int = 1 , a_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , a_ : Optional[str] = "pil" , a_ : bool = True , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._execution_device SCREAMING_SNAKE_CASE__ : Any = guidance_scale > 1.0 if isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat(a_ , dim=0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_embeds.shape[0] if isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[Any] = torch.cat(a_ , dim=0 ) if do_classifier_free_guidance: SCREAMING_SNAKE_CASE__ : Optional[int] = image_embeds.repeat_interleave(a_ , dim=0 ) SCREAMING_SNAKE_CASE__ : Dict = negative_image_embeds.repeat_interleave(a_ , dim=0 ) SCREAMING_SNAKE_CASE__ : Tuple = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=a_ ) if not isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : Optional[int] = [image] if not all(isinstance(a_ , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F'''Input is in incorrect format: {[type(a_ ) for i in image]}. Currently, we only support PIL image and pytorch tensor''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cat([prepare_image(a_ , a_ , a_ ) for i in image] , dim=0 ) SCREAMING_SNAKE_CASE__ : Tuple = image.to(dtype=image_embeds.dtype , device=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.movq.encode(a_ )['latents'] SCREAMING_SNAKE_CASE__ : str = latents.repeat_interleave(a_ , dim=0 ) self.scheduler.set_timesteps(a_ , device=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_timesteps(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = timesteps[:1].repeat(batch_size * num_images_per_prompt ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = downscale_height_and_width(a_ , a_ , self.movq_scale_factor ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_latents( a_ , a_ , a_ , a_ , image_embeds.dtype , a_ , a_ ) for i, t in enumerate(self.progress_bar(a_ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'image_embeds': image_embeds} SCREAMING_SNAKE_CASE__ : Tuple = self.unet( sample=a_ , timestep=a_ , encoder_hidden_states=a_ , added_cond_kwargs=a_ , return_dict=a_ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = noise_pred.split(latents.shape[1] , dim=1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE__ : Optional[int] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.scheduler.step( a_ , a_ , a_ , generator=a_ , )[0] # post-processing SCREAMING_SNAKE_CASE__ : List[str] = self.movq.decode(a_ , force_not_quantize=a_ )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE__ : Dict = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE__ : List[str] = image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ : Optional[int] = self.numpy_to_pil(a_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=a_ )
636
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase__ ) , lowercase__ ) ] 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[:-1]: opened_file.write(int(lowercase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class snake_case ( unittest.TestCase ): def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : List[str] = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '的', '价', '格', '是', '15', '便', 'alex', '##andra', ',', '。', '-', 't', 'shirt', ] SCREAMING_SNAKE_CASE__ : 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] ) ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'do_resize': True, 'size': {'height': 224, 'width': 224}, 'do_center_crop': True, 'crop_size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.4814_5466, 0.457_8275, 0.4082_1073], 'image_std': [0.2686_2954, 0.2613_0258, 0.2757_7711], 'do_convert_rgb': True, } SCREAMING_SNAKE_CASE__ : 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 __lowercase( self : Dict , **a_ : int )-> Optional[int]: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : List[str] , **a_ : int )-> int: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : str , **a_ : Any )-> Optional[Any]: """simple docstring""" return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : List[Any] = [Image.fromarray(np.moveaxis(a_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Optional[int] = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = ChineseCLIPProcessor.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 __lowercase( self : str )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizer(cls_token='(CLS)' , sep_token='(SEP)' ) SCREAMING_SNAKE_CASE__ : str = self.get_image_processor(do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : int = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='(CLS)' , sep_token='(SEP)' , 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 __lowercase( self : List[str] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Dict = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : 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 __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : Any = 'Alexandra,T-shirt的价格是15便士。' SCREAMING_SNAKE_CASE__ : int = processor(text=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer(a_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : Dict = 'Alexandra,T-shirt的价格是15便士。' SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = processor(text=a_ , images=a_ ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(a_ ): processor() def __lowercase( self : Tuple )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : str = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Any = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE__ : Tuple = processor.batch_decode(a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.batch_decode(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Optional[int] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : Any = 'Alexandra,T-shirt的价格是15便士。' SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = processor(text=a_ , images=a_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
636
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
1
def _a ( lowercase__ : list , lowercase__ : list , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) != len(lowercase__ ): raise ValueError('The length of profit and weight must be same.' ) if max_weight <= 0: raise ValueError('max_weight must greater than zero.' ) if any(p < 0 for p in profit ): raise ValueError('Profit can not be negative.' ) if any(w < 0 for w in weight ): raise ValueError('Weight can not be negative.' ) # List created to store profit gained for the 1kg in case of each weight # respectively. Calculate and append profit/weight for each element. SCREAMING_SNAKE_CASE__ : List[Any] = [p / w for p, w in zip(lowercase__ , lowercase__ )] # Creating a copy of the list and sorting profit/weight in ascending order SCREAMING_SNAKE_CASE__ : Tuple = sorted(lowercase__ ) # declaring useful variables SCREAMING_SNAKE_CASE__ : List[str] = len(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 # loop till the total weight do not reach max limit e.g. 15 kg and till i<length while limit <= max_weight and i < length: # flag value for encountered greatest element in sorted_profit_by_weight SCREAMING_SNAKE_CASE__ : str = sorted_profit_by_weight[length - i - 1] SCREAMING_SNAKE_CASE__ : Tuple = profit_by_weight.index(lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = -1 # check if the weight encountered is less than the total weight # encountered before. if max_weight - limit >= weight[index]: limit += weight[index] # Adding profit gained for the given weight 1 === # weight[index]/weight[index] gain += 1 * profit[index] else: # Since the weight encountered is greater than limit, therefore take the # required number of remaining kgs and calculate profit for it. # weight remaining / weight[index] gain += (max_weight - limit) / weight[index] * profit[index] break i += 1 return gain if __name__ == "__main__": print( "Input profits, weights, and then max_weight (all positive ints) separated by " "spaces." ) SCREAMING_SNAKE_CASE__ : List[str] = [int(x) for x in input("Input profits separated by spaces: ").split()] SCREAMING_SNAKE_CASE__ : Tuple = [int(x) for x in input("Input weights separated by spaces: ").split()] SCREAMING_SNAKE_CASE__ : str = int(input("Max weight allowed: ")) # Function Call calc_profit(profit, weight, max_weight)
636
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : str = { "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 snake_case ( UpperCamelCase_ ): lowercase_ = 'xlm' lowercase_ = { 'hidden_size': 'emb_dim', 'num_attention_heads': 'n_heads', 'num_hidden_layers': 'n_layers', 'n_words': 'vocab_size', # For backward compatibility } def __init__( self : List[Any] , a_ : Tuple=3_0145 , a_ : Union[str, Any]=2048 , a_ : int=12 , a_ : List[Any]=16 , a_ : str=0.1 , a_ : Union[str, Any]=0.1 , a_ : Optional[int]=True , a_ : Dict=False , a_ : Optional[Any]=False , a_ : Optional[Any]=False , a_ : List[Any]=1 , a_ : int=True , a_ : Dict=512 , a_ : List[str]=2048**-0.5 , a_ : Tuple=1e-1_2 , a_ : Optional[int]=0.02 , a_ : Any=0 , a_ : Optional[int]=1 , a_ : Union[str, Any]=2 , a_ : List[Any]=3 , a_ : List[str]=5 , a_ : Optional[int]=True , a_ : List[str]="first" , a_ : int=True , a_ : Union[str, Any]=None , a_ : Optional[int]=True , a_ : Tuple=0.1 , a_ : Any=5 , a_ : List[str]=5 , a_ : List[str]=0 , a_ : Any=0 , a_ : Dict=2 , a_ : List[Any]=0 , **a_ : Optional[int] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = emb_dim SCREAMING_SNAKE_CASE__ : Dict = n_layers SCREAMING_SNAKE_CASE__ : Any = n_heads SCREAMING_SNAKE_CASE__ : int = dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_dropout SCREAMING_SNAKE_CASE__ : Any = gelu_activation SCREAMING_SNAKE_CASE__ : List[Any] = sinusoidal_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = causal SCREAMING_SNAKE_CASE__ : Union[str, Any] = asm SCREAMING_SNAKE_CASE__ : int = n_langs SCREAMING_SNAKE_CASE__ : Any = use_lang_emb SCREAMING_SNAKE_CASE__ : int = layer_norm_eps SCREAMING_SNAKE_CASE__ : str = bos_index SCREAMING_SNAKE_CASE__ : Tuple = eos_index SCREAMING_SNAKE_CASE__ : str = pad_index SCREAMING_SNAKE_CASE__ : Union[str, Any] = unk_index SCREAMING_SNAKE_CASE__ : str = mask_index SCREAMING_SNAKE_CASE__ : Dict = is_encoder SCREAMING_SNAKE_CASE__ : str = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = embed_init_std SCREAMING_SNAKE_CASE__ : List[str] = init_std SCREAMING_SNAKE_CASE__ : Dict = summary_type SCREAMING_SNAKE_CASE__ : Optional[Any] = summary_use_proj SCREAMING_SNAKE_CASE__ : Optional[Any] = summary_activation SCREAMING_SNAKE_CASE__ : str = summary_proj_to_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = summary_first_dropout SCREAMING_SNAKE_CASE__ : Tuple = start_n_top SCREAMING_SNAKE_CASE__ : Tuple = end_n_top SCREAMING_SNAKE_CASE__ : List[Any] = mask_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] = lang_id if "n_words" in kwargs: SCREAMING_SNAKE_CASE__ : str = kwargs['n_words'] super().__init__(pad_token_id=a_ , bos_token_id=a_ , **a_ ) class snake_case ( UpperCamelCase_ ): @property def __lowercase( self : List[Any] )-> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: SCREAMING_SNAKE_CASE__ : Optional[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
636
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
1
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Optional[int] )-> List[Any]: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' ) SCREAMING_SNAKE_CASE__ : str = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) sd_pipe.set_scheduler('sample_euler' ) SCREAMING_SNAKE_CASE__ : Any = 'A painting of a squirrel eating a burger' SCREAMING_SNAKE_CASE__ : Tuple = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe([prompt] , generator=a_ , guidance_scale=9.0 , num_inference_steps=20 , output_type='np' ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0.0447, 0.0492, 0.0468, 0.0408, 0.0383, 0.0408, 0.0354, 0.0380, 0.0339] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowercase( self : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) SCREAMING_SNAKE_CASE__ : str = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) sd_pipe.set_scheduler('sample_euler' ) SCREAMING_SNAKE_CASE__ : Any = 'A painting of a squirrel eating a burger' SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe([prompt] , generator=a_ , guidance_scale=9.0 , num_inference_steps=20 , output_type='np' ) SCREAMING_SNAKE_CASE__ : Tuple = output.images SCREAMING_SNAKE_CASE__ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([0.1237, 0.1320, 0.1438, 0.1359, 0.1390, 0.1132, 0.1277, 0.1175, 0.1112] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-1 def __lowercase( self : int )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) SCREAMING_SNAKE_CASE__ : List[Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) sd_pipe.set_scheduler('sample_dpmpp_2m' ) SCREAMING_SNAKE_CASE__ : Optional[int] = 'A painting of a squirrel eating a burger' SCREAMING_SNAKE_CASE__ : Tuple = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : str = sd_pipe( [prompt] , generator=a_ , guidance_scale=7.5 , num_inference_steps=15 , output_type='np' , use_karras_sigmas=a_ , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array( [0.1138_1689, 0.1211_2921, 0.138_9457, 0.1254_9606, 0.124_4964, 0.1083_1517, 0.1156_2866, 0.1086_7816, 0.1049_9048] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
636
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
1
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = {"vocab_file": "spiece.model"} SCREAMING_SNAKE_CASE__ : int = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", } } SCREAMING_SNAKE_CASE__ : Optional[int] = { "xlnet-base-cased": None, "xlnet-large-cased": None, } # Segments (not really needed) SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Tuple = 4 class snake_case ( UpperCamelCase_ ): lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = 'left' def __init__( self : List[Any] , a_ : Union[str, Any] , a_ : int=False , a_ : Optional[Any]=True , a_ : Dict=False , a_ : str="<s>" , a_ : Optional[Any]="</s>" , a_ : int="<unk>" , a_ : Optional[Any]="<sep>" , a_ : Dict="<pad>" , a_ : Any="<cls>" , a_ : int="<mask>" , a_ : Optional[Any]=["<eop>", "<eod>"] , a_ : Optional[Dict[str, Any]] = None , **a_ : Tuple , )-> None: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : List[str] = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token SCREAMING_SNAKE_CASE__ : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , additional_special_tokens=a_ , sp_model_kwargs=self.sp_model_kwargs , **a_ , ) SCREAMING_SNAKE_CASE__ : Dict = 3 SCREAMING_SNAKE_CASE__ : int = do_lower_case SCREAMING_SNAKE_CASE__ : Optional[int] = remove_space SCREAMING_SNAKE_CASE__ : Tuple = keep_accents SCREAMING_SNAKE_CASE__ : Tuple = vocab_file SCREAMING_SNAKE_CASE__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(a_ ) @property def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return len(self.sp_model ) def __lowercase( self : Optional[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = {self.convert_ids_to_tokens(a_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : int = None return state def __setstate__( self : Dict , a_ : Tuple )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} SCREAMING_SNAKE_CASE__ : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowercase( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" if self.remove_space: SCREAMING_SNAKE_CASE__ : Dict = ' '.join(inputs.strip().split() ) else: SCREAMING_SNAKE_CASE__ : List[Any] = inputs SCREAMING_SNAKE_CASE__ : List[Any] = outputs.replace('``' , '"' ).replace('\'\'' , '"' ) if not self.keep_accents: SCREAMING_SNAKE_CASE__ : Any = unicodedata.normalize('NFKD' , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ''.join([c for c in outputs if not unicodedata.combining(a_ )] ) if self.do_lower_case: SCREAMING_SNAKE_CASE__ : Dict = outputs.lower() return outputs def __lowercase( self : Any , a_ : str )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.preprocess_text(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.sp_model.encode(a_ , out_type=a_ ) SCREAMING_SNAKE_CASE__ : Any = [] for piece in pieces: if len(a_ ) > 1 and piece[-1] == str(',' ) and piece[-2].isdigit(): SCREAMING_SNAKE_CASE__ : Dict = self.sp_model.EncodeAsPieces(piece[:-1].replace(a_ , '' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: SCREAMING_SNAKE_CASE__ : Dict = cur_pieces[1:] else: SCREAMING_SNAKE_CASE__ : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(a_ ) else: new_pieces.append(a_ ) return new_pieces def __lowercase( self : List[str] , a_ : Union[str, Any] )-> List[str]: """simple docstring""" return self.sp_model.PieceToId(a_ ) def __lowercase( self : Optional[Any] , a_ : Optional[Any] )-> Optional[Any]: """simple docstring""" return self.sp_model.IdToPiece(a_ ) def __lowercase( self : str , a_ : Any )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = ''.join(a_ ).replace(a_ , ' ' ).strip() return out_string def __lowercase( self : Dict , a_ : List[int] , a_ : bool = False , a_ : bool = None , a_ : bool = True , **a_ : Dict , )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = kwargs.pop('use_source_tokenizer' , a_ ) SCREAMING_SNAKE_CASE__ : int = self.convert_ids_to_tokens(a_ , skip_special_tokens=a_ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(a_ ) ) SCREAMING_SNAKE_CASE__ : Any = [] sub_texts.append(a_ ) else: current_sub_text.append(a_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(a_ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens SCREAMING_SNAKE_CASE__ : Optional[int] = ''.join(a_ ) SCREAMING_SNAKE_CASE__ : str = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: SCREAMING_SNAKE_CASE__ : List[str] = self.clean_up_tokenization(a_ ) return clean_text else: return text def __lowercase( self : Any , a_ : List[int] , a_ : Optional[List[int]] = None )-> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Dict = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __lowercase( self : str , a_ : List[int] , a_ : Optional[List[int]] = None , a_ : bool = False )-> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a_ , token_ids_a=a_ , already_has_special_tokens=a_ ) if token_ids_a is not None: return ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1, 1] return ([0] * len(a_ )) + [1, 1] def __lowercase( self : Union[str, Any] , a_ : List[int] , a_ : Optional[List[int]] = None )-> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Tuple = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __lowercase( self : Union[str, Any] , a_ : str , a_ : Optional[str] = None )-> Tuple[str]: """simple docstring""" if not os.path.isdir(a_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Any = os.path.join( a_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a_ ) elif not os.path.isfile(self.vocab_file ): with open(a_ , 'wb' ) as fi: SCREAMING_SNAKE_CASE__ : List[str] = self.sp_model.serialized_model_proto() fi.write(a_ ) return (out_vocab_file,)
636
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" 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 __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" 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=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
1
from copy import deepcopy class snake_case : def __init__( self : Tuple , a_ : list[int] | None = None , a_ : int | None = None )-> None: """simple docstring""" if arr is None and size is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = size SCREAMING_SNAKE_CASE__ : Optional[Any] = [0] * size elif arr is not None: self.init(a_ ) else: raise ValueError('Either arr or size must be specified' ) def __lowercase( self : Optional[Any] , a_ : list[int] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = len(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = deepcopy(a_ ) for i in range(1 , self.size ): SCREAMING_SNAKE_CASE__ : Optional[int] = self.next_(a_ ) if j < self.size: self.tree[j] += self.tree[i] def __lowercase( self : Dict )-> list[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): SCREAMING_SNAKE_CASE__ : List[Any] = self.next_(a_ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def __lowercase( a_ : int )-> int: """simple docstring""" return index + (index & (-index)) @staticmethod def __lowercase( a_ : int )-> int: """simple docstring""" return index - (index & (-index)) def __lowercase( self : Optional[Any] , a_ : int , a_ : int )-> None: """simple docstring""" if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value SCREAMING_SNAKE_CASE__ : Any = self.next_(a_ ) def __lowercase( self : Union[str, Any] , a_ : int , a_ : int )-> None: """simple docstring""" self.add(a_ , value - self.get(a_ ) ) def __lowercase( self : int , a_ : int )-> int: """simple docstring""" if right == 0: return 0 SCREAMING_SNAKE_CASE__ : List[str] = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] SCREAMING_SNAKE_CASE__ : str = self.prev(a_ ) return result def __lowercase( self : Any , a_ : int , a_ : int )-> int: """simple docstring""" return self.prefix(a_ ) - self.prefix(a_ ) def __lowercase( self : str , a_ : int )-> int: """simple docstring""" return self.query(a_ , index + 1 ) def __lowercase( self : Tuple , a_ : int )-> int: """simple docstring""" value -= self.tree[0] if value < 0: return -1 SCREAMING_SNAKE_CASE__ : List[Any] = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 SCREAMING_SNAKE_CASE__ : Optional[int] = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
636
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
1
from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class snake_case : def __init__( self : List[str] , a_ : Tuple , a_ : Any=13 , a_ : Any=7 , a_ : int=True , a_ : Tuple=True , a_ : Dict=True , a_ : str=True , a_ : str=99 , a_ : Tuple=32 , a_ : Dict=2 , a_ : Tuple=4 , a_ : List[Any]=37 , a_ : Optional[Any]="gelu" , a_ : Union[str, Any]=0.1 , a_ : Optional[Any]=0.1 , a_ : int=512 , a_ : List[Any]=16 , a_ : Tuple=2 , a_ : Union[str, Any]=0.02 , a_ : Union[str, Any]=False , a_ : List[str]=True , a_ : str="None" , a_ : Union[str, Any]=3 , a_ : List[Any]=4 , a_ : List[str]=None , )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = parent SCREAMING_SNAKE_CASE__ : str = batch_size SCREAMING_SNAKE_CASE__ : Tuple = seq_length SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[int] = use_token_type_ids SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_size SCREAMING_SNAKE_CASE__ : int = num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Any = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = num_choices SCREAMING_SNAKE_CASE__ : Any = relative_attention SCREAMING_SNAKE_CASE__ : List[str] = position_biased_input SCREAMING_SNAKE_CASE__ : List[str] = pos_att_type SCREAMING_SNAKE_CASE__ : Optional[int] = scope def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : List[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Any = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[Any] = DebertaVaConfig( 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 , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=a_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Any , a_ : Union[str, Any] , a_ : List[Any] , a_ : Dict , a_ : str , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFDebertaVaModel(config=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE__ : Optional[int] = [input_ids, input_mask] SCREAMING_SNAKE_CASE__ : Any = model(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : int , a_ : Optional[Any] , a_ : int , a_ : Dict , a_ : int , a_ : str , a_ : Any , a_ : Any )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = TFDebertaVaForMaskedLM(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : int , a_ : Optional[Any] , a_ : int , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : Tuple , a_ : str , a_ : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : List[Any] = TFDebertaVaForSequenceClassification(config=a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : int , a_ : Any , a_ : Optional[int] , a_ : Any , a_ : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.num_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFDebertaVaForTokenClassification(config=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE__ : Any = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Dict , a_ : Tuple , a_ : int , a_ : int , a_ : Union[str, Any] , a_ : str , a_ : Optional[int] , a_ : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFDebertaVaForQuestionAnswering(config=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Optional[int] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) lowercase_ = ( { 'feature-extraction': TFDebertaVaModel, 'fill-mask': TFDebertaVaForMaskedLM, 'question-answering': TFDebertaVaForQuestionAnswering, 'text-classification': TFDebertaVaForSequenceClassification, 'token-classification': TFDebertaVaForTokenClassification, 'zero-shot': TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) lowercase_ = False lowercase_ = False def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFDebertaVaModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a_ ) def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a_ ) def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) @slow def __lowercase( self : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) self.assertIsNotNone(a_ ) @require_tf class snake_case ( unittest.TestCase ): @unittest.skip(reason='Model not available yet' ) def __lowercase( self : str )-> List[str]: """simple docstring""" pass @slow def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) SCREAMING_SNAKE_CASE__ : Dict = tf.constant([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) SCREAMING_SNAKE_CASE__ : List[str] = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , a_ , atol=1e-4 )
636
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
1
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a_ , a_ ) def __call__( self : Any , a_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , a_ , ) return self.image_processor_class @property def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
1
import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case ( ctypes.Structure ): # _fields is a specific attr expected by ctypes lowercase_ = [('size', ctypes.c_int), ('visible', ctypes.c_byte)] def _a ( ): '''simple docstring''' if os.name == "nt": SCREAMING_SNAKE_CASE__ : Dict = CursorInfo() SCREAMING_SNAKE_CASE__ : Optional[int] = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowercase__ , ctypes.byref(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[str] = False ctypes.windll.kernelaa.SetConsoleCursorInfo(lowercase__ , ctypes.byref(lowercase__ ) ) elif os.name == "posix": sys.stdout.write('\033[?25l' ) sys.stdout.flush() def _a ( ): '''simple docstring''' if os.name == "nt": SCREAMING_SNAKE_CASE__ : Any = CursorInfo() SCREAMING_SNAKE_CASE__ : str = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowercase__ , ctypes.byref(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Dict = True ctypes.windll.kernelaa.SetConsoleCursorInfo(lowercase__ , ctypes.byref(lowercase__ ) ) elif os.name == "posix": sys.stdout.write('\033[?25h' ) sys.stdout.flush() @contextmanager def _a ( ): '''simple docstring''' try: hide_cursor() yield finally: show_cursor()
636
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
1
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 snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = ProphetNetTokenizer lowercase_ = False def __lowercase( self : str )-> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : str = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase( self : Union[str, Any] , a_ : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : str = 'unwanted, running' return input_text, output_text def __lowercase( self : Tuple )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : 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 __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def __lowercase( self : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 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 __lowercase( self : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = 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 __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 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 __lowercase( self : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 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 __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BasicTokenizer(do_lower_case=a_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def __lowercase( self : str )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BasicTokenizer(do_lower_case=a_ , strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def __lowercase( self : Tuple )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BasicTokenizer(do_lower_case=a_ , strip_accents=a_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def __lowercase( self : Tuple )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BasicTokenizer(do_lower_case=a_ , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] SCREAMING_SNAKE_CASE__ : str = {} for i, token in enumerate(a_ ): SCREAMING_SNAKE_CASE__ : List[str] = i SCREAMING_SNAKE_CASE__ : List[Any] = 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 __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) SCREAMING_SNAKE_CASE__ : Optional[int] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] SCREAMING_SNAKE_CASE__ : Optional[int] = [1037, 2146, 2_0423, 2005, 7680, 7849, 3989, 1012, 102] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer(a_ , padding=a_ , return_tensors='pt' ) self.assertIsInstance(a_ , a_ ) SCREAMING_SNAKE_CASE__ : 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 __lowercase( self : Union[str, Any] )-> str: """simple docstring""" self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def __lowercase( self : str )-> Dict: """simple docstring""" self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode('sequence builders' , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.build_inputs_with_special_tokens(a_ ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.build_inputs_with_special_tokens(a_ , a_ ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
636
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
1
import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Any = logging.getLogger(__name__) @dataclass(frozen=UpperCamelCase_ ) class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = None lowercase_ = None lowercase_ = None @dataclass(frozen=UpperCamelCase_ ) class snake_case : lowercase_ = 42 lowercase_ = None lowercase_ = None lowercase_ = None lowercase_ = None if is_torch_available(): import torch from torch.utils.data import Dataset class snake_case ( UpperCamelCase_ ): lowercase_ = 42 def __init__( self : int , a_ : str , a_ : PreTrainedTokenizer , a_ : str , a_ : Optional[int] = None , a_ : str=False , a_ : bool = False , )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = hans_processors[task]() SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join( a_ , 'cached_{}_{}_{}_{}'.format( 'dev' if evaluate else 'train' , tokenizer.__class__.__name__ , str(a_ ) , a_ , ) , ) SCREAMING_SNAKE_CASE__ : Tuple = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = label_list[2], label_list[1] SCREAMING_SNAKE_CASE__ : Optional[Any] = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. SCREAMING_SNAKE_CASE__ : Tuple = cached_features_file + '.lock' with FileLock(a_ ): if os.path.exists(a_ ) and not overwrite_cache: logger.info(F'''Loading features from cached file {cached_features_file}''' ) SCREAMING_SNAKE_CASE__ : Dict = torch.load(a_ ) else: logger.info(F'''Creating features from dataset file at {data_dir}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = ( processor.get_dev_examples(a_ ) if evaluate else processor.get_train_examples(a_ ) ) logger.info('Training examples: %s' , len(a_ ) ) SCREAMING_SNAKE_CASE__ : Tuple = hans_convert_examples_to_features(a_ , a_ , a_ , a_ ) logger.info('Saving features into cached file %s' , a_ ) torch.save(self.features , a_ ) def __len__( self : str )-> Union[str, Any]: """simple docstring""" return len(self.features ) def __getitem__( self : str , a_ : List[str] )-> InputFeatures: """simple docstring""" return self.features[i] def __lowercase( self : List[Any] )-> Any: """simple docstring""" return self.label_list if is_tf_available(): import tensorflow as tf class snake_case : lowercase_ = 42 def __init__( self : Optional[int] , a_ : str , a_ : PreTrainedTokenizer , a_ : str , a_ : Optional[int] = 128 , a_ : List[str]=False , a_ : bool = False , )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = hans_processors[task]() SCREAMING_SNAKE_CASE__ : Optional[int] = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = label_list[2], label_list[1] SCREAMING_SNAKE_CASE__ : Dict = label_list SCREAMING_SNAKE_CASE__ : Optional[Any] = processor.get_dev_examples(a_ ) if evaluate else processor.get_train_examples(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = hans_convert_examples_to_features(a_ , a_ , a_ , a_ ) def gen(): for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc='convert examples to features' ): if ex_index % 1_0000 == 0: logger.info('Writing example %d of %d' % (ex_index, len(a_ )) ) yield ( { "example_id": 0, "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label, ) SCREAMING_SNAKE_CASE__ : str = tf.data.Dataset.from_generator( a_ , ( { 'example_id': tf.intaa, 'input_ids': tf.intaa, 'attention_mask': tf.intaa, 'token_type_ids': tf.intaa, }, tf.intaa, ) , ( { 'example_id': tf.TensorShape([] ), 'input_ids': tf.TensorShape([None, None] ), 'attention_mask': tf.TensorShape([None, None] ), 'token_type_ids': tf.TensorShape([None, None] ), }, tf.TensorShape([] ), ) , ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" return self.dataset def __len__( self : Dict )-> Dict: """simple docstring""" return len(self.features ) def __getitem__( self : Optional[Any] , a_ : str )-> InputFeatures: """simple docstring""" return self.features[i] def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return self.label_list class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : Dict )-> Tuple: """simple docstring""" return self._create_examples(self._read_tsv(os.path.join(a_ , 'heuristics_train_set.txt' ) ) , 'train' ) def __lowercase( self : Dict , a_ : str )-> Optional[int]: """simple docstring""" return self._create_examples(self._read_tsv(os.path.join(a_ , 'heuristics_evaluation_set.txt' ) ) , 'dev' ) def __lowercase( self : int )-> Any: """simple docstring""" return ["contradiction", "entailment", "neutral"] def __lowercase( self : Any , a_ : Optional[Any] , a_ : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = [] for i, line in enumerate(a_ ): if i == 0: continue SCREAMING_SNAKE_CASE__ : List[str] = '%s-%s' % (set_type, line[0]) SCREAMING_SNAKE_CASE__ : Any = line[5] SCREAMING_SNAKE_CASE__ : Optional[int] = line[6] SCREAMING_SNAKE_CASE__ : int = line[7][2:] if line[7].startswith('ex' ) else line[7] SCREAMING_SNAKE_CASE__ : Any = line[0] examples.append(InputExample(guid=a_ , text_a=a_ , text_b=a_ , label=a_ , pairID=a_ ) ) return examples def _a ( lowercase__ : List[InputExample] , lowercase__ : List[str] , lowercase__ : int , lowercase__ : PreTrainedTokenizer , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {label: i for i, label in enumerate(lowercase__ )} SCREAMING_SNAKE_CASE__ : Dict = [] for ex_index, example in tqdm.tqdm(enumerate(lowercase__ ) , desc='convert examples to features' ): if ex_index % 1_00_00 == 0: logger.info('Writing example %d' % (ex_index) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer( example.text_a , example.text_b , add_special_tokens=lowercase__ , max_length=lowercase__ , padding='max_length' , truncation=lowercase__ , return_overflowing_tokens=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = label_map[example.label] if example.label in label_map else 0 SCREAMING_SNAKE_CASE__ : Any = int(example.pairID ) features.append(InputFeatures(**lowercase__ , label=lowercase__ , pairID=lowercase__ ) ) for i, example in enumerate(examples[:5] ): logger.info('*** Example ***' ) logger.info(f'''guid: {example}''' ) logger.info(f'''features: {features[i]}''' ) return features SCREAMING_SNAKE_CASE__ : str = { "hans": 3, } SCREAMING_SNAKE_CASE__ : Tuple = { "hans": HansProcessor, }
636
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Dict = { "alibaba-damo/mgp-str-base": "https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'mgp-str' def __init__( self : Dict , a_ : Optional[int]=[32, 128] , a_ : List[str]=4 , a_ : List[Any]=3 , a_ : Union[str, Any]=27 , a_ : Optional[Any]=38 , a_ : Any=5_0257 , a_ : Tuple=3_0522 , a_ : Any=768 , a_ : Union[str, Any]=12 , a_ : List[Any]=12 , a_ : Tuple=4.0 , a_ : Union[str, Any]=True , a_ : Optional[Any]=False , a_ : Tuple=1e-5 , a_ : List[Any]=0.0 , a_ : Any=0.0 , a_ : int=0.0 , a_ : Optional[int]=False , a_ : int=0.02 , **a_ : List[str] , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = image_size SCREAMING_SNAKE_CASE__ : List[Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_channels SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_token_length SCREAMING_SNAKE_CASE__ : Tuple = num_character_labels SCREAMING_SNAKE_CASE__ : List[Any] = num_bpe_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_wordpiece_labels SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = mlp_ratio SCREAMING_SNAKE_CASE__ : Dict = distilled SCREAMING_SNAKE_CASE__ : str = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = drop_rate SCREAMING_SNAKE_CASE__ : List[str] = qkv_bias SCREAMING_SNAKE_CASE__ : Dict = attn_drop_rate SCREAMING_SNAKE_CASE__ : List[str] = drop_path_rate SCREAMING_SNAKE_CASE__ : Optional[Any] = output_aa_attentions SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range
636
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
1
from collections import defaultdict def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = True for v in tree[start]: if v not in visited: ret += dfs(lowercase__ ) if ret % 2 == 0: cuts.append(lowercase__ ) return ret def _a ( ): '''simple docstring''' dfs(1 ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = 10, 9 SCREAMING_SNAKE_CASE__ : int = defaultdict(list) SCREAMING_SNAKE_CASE__ : dict[int, bool] = {} SCREAMING_SNAKE_CASE__ : list[int] = [] SCREAMING_SNAKE_CASE__ : int = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
636
# Copyright 2023 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 torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
1
import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class snake_case ( unittest.TestCase ): def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ['a', 'b', 'c'] # Defaults to last layer if both are None SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_aligned_output_features_output_indices(a_ , a_ , a_ ) self.assertEqual(a_ , ['c'] ) self.assertEqual(a_ , [2] ) # Out indices set to match out features SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = get_aligned_output_features_output_indices(['a', 'c'] , a_ , a_ ) self.assertEqual(a_ , ['a', 'c'] ) self.assertEqual(a_ , [0, 2] ) # Out features set to match out indices SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = get_aligned_output_features_output_indices(a_ , [0, 2] , a_ ) self.assertEqual(a_ , ['a', 'c'] ) self.assertEqual(a_ , [0, 2] ) # Out features selected from negative indices SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = get_aligned_output_features_output_indices(a_ , [-3, -1] , a_ ) self.assertEqual(a_ , ['a', 'c'] ) self.assertEqual(a_ , [-3, -1] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" # Stage names must be set with self.assertRaises(a_ ): verify_out_features_out_indices(['a', 'b'] , (0, 1) , a_ ) # Out features must be a list with self.assertRaises(a_ ): verify_out_features_out_indices(('a', 'b') , (0, 1) , ['a', 'b'] ) # Out features must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(['a', 'b'] , (0, 1) , ['a'] ) # Out indices must be a list or tuple with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , 0 , ['a', 'b'] ) # Out indices must be a subset of stage names with self.assertRaises(a_ ): verify_out_features_out_indices(a_ , (0, 1) , ['a'] ) # Out features and out indices must be the same length with self.assertRaises(a_ ): verify_out_features_out_indices(['a', 'b'] , (0,) , ['a', 'b', 'c'] ) # Out features should match out indices with self.assertRaises(a_ ): verify_out_features_out_indices(['a', 'b'] , (0, 2) , ['a', 'b', 'c'] ) # Out features and out indices should be in order with self.assertRaises(a_ ): verify_out_features_out_indices(['b', 'a'] , (0, 1) , ['a', 'b'] ) # Check passes with valid inputs verify_out_features_out_indices(['a', 'b', 'd'] , (0, 1, -1) , ['a', 'b', 'c', 'd'] ) def __lowercase( self : List[str] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BackboneMixin() SCREAMING_SNAKE_CASE__ : int = ['a', 'b', 'c'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = ['a', 'c'] SCREAMING_SNAKE_CASE__ : Any = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['a', 'c'] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly SCREAMING_SNAKE_CASE__ : Optional[int] = ['a', 'b'] self.assertEqual(backbone.out_features , ['a', 'b'] ) self.assertEqual(backbone.out_indices , [0, 1] ) SCREAMING_SNAKE_CASE__ : Dict = [-3, -1] self.assertEqual(backbone.out_features , ['a', 'c'] ) self.assertEqual(backbone.out_indices , [-3, -1] )
636
import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[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 SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
1
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" 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 __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" 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=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
1
import gc import threading import time import psutil import torch class snake_case : def __init__( self : Dict )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = psutil.Process() SCREAMING_SNAKE_CASE__ : Optional[Any] = False def __lowercase( self : Dict )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = -1 while True: SCREAMING_SNAKE_CASE__ : Optional[int] = max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : Optional[int] = threading.Thread(target=self.peak_monitor ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = True self.thread.start() def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = False self.thread.join() return self.cpu_memory_peak SCREAMING_SNAKE_CASE__ : Union[str, Any] = PeakCPUMemory() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = {'time': time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem SCREAMING_SNAKE_CASE__ : Tuple = psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): SCREAMING_SNAKE_CASE__ : Dict = torch.cuda.memory_allocated(lowercase__ ) torch.cuda.reset_peak_memory_stats() return measures def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = {'time': time.time() - start_measures['time']} gc.collect() torch.cuda.empty_cache() # CPU mem SCREAMING_SNAKE_CASE__ : Union[str, Any] = (psutil.Process().memory_info().rss - start_measures['cpu']) / 2**20 SCREAMING_SNAKE_CASE__ : int = (cpu_peak_tracker.stop() - start_measures['cpu']) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): SCREAMING_SNAKE_CASE__ : Dict = (torch.cuda.memory_allocated(lowercase__ ) - start_measures[str(lowercase__ )]) / 2**20 SCREAMING_SNAKE_CASE__ : List[Any] = (torch.cuda.max_memory_allocated(lowercase__ ) - start_measures[str(lowercase__ )]) / 2**20 return measures def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' print(f'''{description}:''' ) print(f'''- Time: {measures['time']:.2f}s''' ) for i in range(torch.cuda.device_count() ): print(f'''- GPU {i} allocated: {measures[str(lowercase__ )]:.2f}MiB''' ) SCREAMING_SNAKE_CASE__ : Any = measures[f'''{i}-peak'''] print(f'''- GPU {i} peak: {peak:.2f}MiB''' ) print(f'''- CPU RAM allocated: {measures['cpu']:.2f}MiB''' ) print(f'''- CPU RAM peak: {measures['cpu-peak']:.2f}MiB''' )
636
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''simple docstring''' assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
636
1
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[str] = { "google/owlvit-base-patch32": "https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json", "google/owlvit-base-patch16": "https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json", "google/owlvit-large-patch14": "https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'owlvit_text_model' def __init__( self : str , a_ : Optional[int]=4_9408 , a_ : int=512 , a_ : Dict=2048 , a_ : Dict=12 , a_ : List[str]=8 , a_ : Dict=16 , a_ : Optional[Any]="quick_gelu" , a_ : List[Any]=1e-5 , a_ : Any=0.0 , a_ : Optional[Any]=0.02 , a_ : List[str]=1.0 , a_ : Any=0 , a_ : List[str]=4_9406 , a_ : Optional[Any]=4_9407 , **a_ : Dict , )-> int: """simple docstring""" super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : str = layer_norm_eps SCREAMING_SNAKE_CASE__ : Dict = attention_dropout SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = initializer_factor @classmethod def __lowercase( cls : Dict , a_ : Union[str, os.PathLike] , **a_ : Any )-> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = cls.get_config_dict(a_ , **a_ ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get('model_type' ) == "owlvit": SCREAMING_SNAKE_CASE__ : Any = config_dict['text_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(a_ , **a_ ) class snake_case ( UpperCamelCase_ ): lowercase_ = 'owlvit_vision_model' def __init__( self : Optional[int] , a_ : Union[str, Any]=768 , a_ : Optional[Any]=3072 , a_ : Optional[Any]=12 , a_ : Tuple=12 , a_ : int=3 , a_ : int=768 , a_ : Optional[int]=32 , a_ : str="quick_gelu" , a_ : int=1e-5 , a_ : List[Any]=0.0 , a_ : Union[str, Any]=0.02 , a_ : Optional[int]=1.0 , **a_ : Dict , )-> Optional[int]: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : Dict = image_size SCREAMING_SNAKE_CASE__ : Any = patch_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Dict = layer_norm_eps SCREAMING_SNAKE_CASE__ : Tuple = attention_dropout SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Tuple = initializer_factor @classmethod def __lowercase( cls : Optional[Any] , a_ : Union[str, os.PathLike] , **a_ : str )-> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = cls.get_config_dict(a_ , **a_ ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get('model_type' ) == "owlvit": SCREAMING_SNAKE_CASE__ : Dict = config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(a_ , **a_ ) class snake_case ( UpperCamelCase_ ): lowercase_ = 'owlvit' lowercase_ = True def __init__( self : Tuple , a_ : Union[str, Any]=None , a_ : Any=None , a_ : Dict=512 , a_ : int=2.6592 , a_ : int=True , **a_ : int , )-> str: """simple docstring""" super().__init__(**a_ ) if text_config is None: SCREAMING_SNAKE_CASE__ : Any = {} logger.info('text_config is None. Initializing the OwlViTTextConfig with default values.' ) if vision_config is None: SCREAMING_SNAKE_CASE__ : Optional[int] = {} logger.info('vision_config is None. initializing the OwlViTVisionConfig with default values.' ) SCREAMING_SNAKE_CASE__ : str = OwlViTTextConfig(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = OwlViTVisionConfig(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = projection_dim SCREAMING_SNAKE_CASE__ : Optional[int] = logit_scale_init_value SCREAMING_SNAKE_CASE__ : str = return_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1.0 @classmethod def __lowercase( cls : int , a_ : Union[str, os.PathLike] , **a_ : str )-> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = cls.get_config_dict(a_ , **a_ ) if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(a_ , **a_ ) @classmethod def __lowercase( cls : int , a_ : Dict , a_ : Dict , **a_ : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = {} SCREAMING_SNAKE_CASE__ : str = text_config SCREAMING_SNAKE_CASE__ : int = vision_config return cls.from_dict(a_ , **a_ ) def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ : List[str] = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.__class__.model_type return output class snake_case ( UpperCamelCase_ ): @property def __lowercase( self : Optional[Any] )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ] ) @property def __lowercase( self : List[Any] )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('logits_per_image', {0: 'batch'}), ('logits_per_text', {0: 'batch'}), ('text_embeds', {0: 'batch'}), ('image_embeds', {0: 'batch'}), ] ) @property def __lowercase( self : int )-> float: """simple docstring""" return 1e-4 def __lowercase( self : Union[str, Any] , a_ : "ProcessorMixin" , a_ : int = -1 , a_ : int = -1 , a_ : Optional["TensorType"] = None , )-> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = super().generate_dummy_inputs( processor.tokenizer , batch_size=a_ , seq_length=a_ , framework=a_ ) SCREAMING_SNAKE_CASE__ : Any = super().generate_dummy_inputs( processor.image_processor , batch_size=a_ , framework=a_ ) return {**text_input_dict, **image_input_dict} @property def __lowercase( self : int )-> int: """simple docstring""" return 14
636
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
636
1
from typing import Any import numpy as np def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return np.array_equal(lowercase__ , matrix.conjugate().T ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = v.conjugate().T SCREAMING_SNAKE_CASE__ : Dict = v_star.dot(lowercase__ ) assert isinstance(lowercase__ , np.ndarray ) return (v_star_dot.dot(lowercase__ )) / (v_star.dot(lowercase__ )) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[1], [2], [3]] ) assert is_hermitian(lowercase__ ), f'''{a} is not hermitian.''' print(rayleigh_quotient(lowercase__ , lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(lowercase__ ), f'''{a} is not hermitian.''' assert rayleigh_quotient(lowercase__ , lowercase__ ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
636
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
1
import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def _a ( lowercase__ : int ): '''simple docstring''' random.seed(lowercase__ ) np.random.seed(lowercase__ ) torch.manual_seed(lowercase__ ) torch.cuda.manual_seed_all(lowercase__ ) # ^^ safe to call this function even if cuda is not available class snake_case : def __init__( self : Any , a_ : Iterable[torch.nn.Parameter] , a_ : float = 0.9999 , a_ : float = 0.0 , a_ : int = 0 , a_ : bool = False , a_ : Union[float, int] = 1.0 , a_ : Union[float, int] = 2 / 3 , a_ : Optional[Any] = None , a_ : Dict[str, Any] = None , **a_ : Optional[int] , )-> Dict: """simple docstring""" if isinstance(a_ , torch.nn.Module ): SCREAMING_SNAKE_CASE__ : str = ( 'Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. ' 'Please pass the parameters of the module instead.' ) deprecate( 'passing a `torch.nn.Module` to `ExponentialMovingAverage`' , '1.0.0' , a_ , standard_warn=a_ , ) SCREAMING_SNAKE_CASE__ : Dict = parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility SCREAMING_SNAKE_CASE__ : Any = True if kwargs.get('max_value' , a_ ) is not None: SCREAMING_SNAKE_CASE__ : Any = 'The `max_value` argument is deprecated. Please use `decay` instead.' deprecate('max_value' , '1.0.0' , a_ , standard_warn=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs['max_value'] if kwargs.get('min_value' , a_ ) is not None: SCREAMING_SNAKE_CASE__ : List[str] = 'The `min_value` argument is deprecated. Please use `min_decay` instead.' deprecate('min_value' , '1.0.0' , a_ , standard_warn=a_ ) SCREAMING_SNAKE_CASE__ : int = kwargs['min_value'] SCREAMING_SNAKE_CASE__ : Optional[int] = list(a_ ) SCREAMING_SNAKE_CASE__ : Dict = [p.clone().detach() for p in parameters] if kwargs.get('device' , a_ ) is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'The `device` argument is deprecated. Please use `to` instead.' deprecate('device' , '1.0.0' , a_ , standard_warn=a_ ) self.to(device=kwargs['device'] ) SCREAMING_SNAKE_CASE__ : Tuple = None SCREAMING_SNAKE_CASE__ : Optional[int] = decay SCREAMING_SNAKE_CASE__ : Optional[Any] = min_decay SCREAMING_SNAKE_CASE__ : int = update_after_step SCREAMING_SNAKE_CASE__ : Optional[Any] = use_ema_warmup SCREAMING_SNAKE_CASE__ : Union[str, Any] = inv_gamma SCREAMING_SNAKE_CASE__ : str = power SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : List[str] = None # set in `step()` SCREAMING_SNAKE_CASE__ : Tuple = model_cls SCREAMING_SNAKE_CASE__ : Optional[Any] = model_config @classmethod def __lowercase( cls : Any , a_ : List[Any] , a_ : str )-> "EMAModel": """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = model_cls.load_config(a_ , return_unused_kwargs=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model_cls.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = cls(model.parameters() , model_cls=a_ , model_config=model.config ) ema_model.load_state_dict(a_ ) return ema_model def __lowercase( self : List[str] , a_ : List[Any] )-> List[Any]: """simple docstring""" if self.model_cls is None: raise ValueError('`save_pretrained` can only be used if `model_cls` was defined at __init__.' ) if self.model_config is None: raise ValueError('`save_pretrained` can only be used if `model_config` was defined at __init__.' ) SCREAMING_SNAKE_CASE__ : Tuple = self.model_cls.from_config(self.model_config ) SCREAMING_SNAKE_CASE__ : List[str] = self.state_dict() state_dict.pop('shadow_params' , a_ ) model.register_to_config(**a_ ) self.copy_to(model.parameters() ) model.save_pretrained(a_ ) def __lowercase( self : Optional[int] , a_ : int )-> float: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = max(0 , optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: SCREAMING_SNAKE_CASE__ : int = 1 - (1 + step / self.inv_gamma) ** -self.power else: SCREAMING_SNAKE_CASE__ : List[Any] = (1 + step) / (10 + step) SCREAMING_SNAKE_CASE__ : str = min(a_ , self.decay ) # make sure decay is not smaller than min_decay SCREAMING_SNAKE_CASE__ : int = max(a_ , self.min_decay ) return cur_decay_value @torch.no_grad() def __lowercase( self : int , a_ : Iterable[torch.nn.Parameter] )-> Optional[Any]: """simple docstring""" if isinstance(a_ , torch.nn.Module ): SCREAMING_SNAKE_CASE__ : Any = ( 'Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. ' 'Please pass the parameters of the module instead.' ) deprecate( 'passing a `torch.nn.Module` to `ExponentialMovingAverage.step`' , '1.0.0' , a_ , standard_warn=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = parameters.parameters() SCREAMING_SNAKE_CASE__ : Optional[Any] = list(a_ ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. SCREAMING_SNAKE_CASE__ : Dict = self.get_decay(self.optimization_step ) SCREAMING_SNAKE_CASE__ : Optional[int] = decay SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 - decay SCREAMING_SNAKE_CASE__ : str = contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params , a_ ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): SCREAMING_SNAKE_CASE__ : Optional[int] = deepspeed.zero.GatheredParameters(a_ , modifier_rank=a_ ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(a_ ) def __lowercase( self : Union[str, Any] , a_ : Iterable[torch.nn.Parameter] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = list(a_ ) for s_param, param in zip(self.shadow_params , a_ ): param.data.copy_(s_param.to(param.device ).data ) def __lowercase( self : Optional[int] , a_ : Any=None , a_ : Dict=None )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ p.to(device=a_ , dtype=a_ ) if p.is_floating_point() else p.to(device=a_ ) for p in self.shadow_params ] def __lowercase( self : Union[str, Any] )-> dict: """simple docstring""" return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def __lowercase( self : Optional[Any] , a_ : Iterable[torch.nn.Parameter] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = [param.detach().cpu().clone() for param in parameters] def __lowercase( self : Dict , a_ : Iterable[torch.nn.Parameter] )-> None: """simple docstring""" if self.temp_stored_params is None: raise RuntimeError('This ExponentialMovingAverage has no `store()`ed weights ' 'to `restore()`' ) for c_param, param in zip(self.temp_stored_params , a_ ): param.data.copy_(c_param.data ) # Better memory-wise. SCREAMING_SNAKE_CASE__ : Optional[int] = None def __lowercase( self : Any , a_ : dict )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = copy.deepcopy(a_ ) SCREAMING_SNAKE_CASE__ : int = state_dict.get('decay' , self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError('Decay must be between 0 and 1' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.get('min_decay' , self.min_decay ) if not isinstance(self.min_decay , a_ ): raise ValueError('Invalid min_decay' ) SCREAMING_SNAKE_CASE__ : int = state_dict.get('optimization_step' , self.optimization_step ) if not isinstance(self.optimization_step , a_ ): raise ValueError('Invalid optimization_step' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.get('update_after_step' , self.update_after_step ) if not isinstance(self.update_after_step , a_ ): raise ValueError('Invalid update_after_step' ) SCREAMING_SNAKE_CASE__ : int = state_dict.get('use_ema_warmup' , self.use_ema_warmup ) if not isinstance(self.use_ema_warmup , a_ ): raise ValueError('Invalid use_ema_warmup' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.get('inv_gamma' , self.inv_gamma ) if not isinstance(self.inv_gamma , (float, int) ): raise ValueError('Invalid inv_gamma' ) SCREAMING_SNAKE_CASE__ : str = state_dict.get('power' , self.power ) if not isinstance(self.power , (float, int) ): raise ValueError('Invalid power' ) SCREAMING_SNAKE_CASE__ : str = state_dict.get('shadow_params' , a_ ) if shadow_params is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = shadow_params if not isinstance(self.shadow_params , a_ ): raise ValueError('shadow_params must be a list' ) if not all(isinstance(a_ , torch.Tensor ) for p in self.shadow_params ): raise ValueError('shadow_params must all be Tensors' )
636
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
1
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Tuple = 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 , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : Optional[int] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : Optional[Any] , a_ : Union[str, Any] , a_ : List[str]=0 )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : str = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : str = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : Any )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Tuple = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = 'french fries' SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : str = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Optional[int] = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : str = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : str )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Any = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : List[Any] = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : int )-> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : List[Any] = components['vae'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Optional[Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Optional[int] )-> Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : int , a_ : Union[str, Any]=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : str = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_inputs() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_inputs() SCREAMING_SNAKE_CASE__ : int = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : List[str] = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : str = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Any = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Tuple = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Optional[int] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : str = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : Any = False SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : Optional[Any] )-> Optional[Any]: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : int = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : int )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : int = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = output.images[0] SCREAMING_SNAKE_CASE__ : Optional[int] = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
636
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( 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 __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
1
import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def _a ( lowercase__ : bytes , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = f'''{sampling_rate}''' SCREAMING_SNAKE_CASE__ : Optional[int] = '1' SCREAMING_SNAKE_CASE__ : int = 'f32le' SCREAMING_SNAKE_CASE__ : int = [ 'ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] try: with subprocess.Popen(lowercase__ , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: SCREAMING_SNAKE_CASE__ : Dict = ffmpeg_process.communicate(lowercase__ ) except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to load audio files from filename' ) from error SCREAMING_SNAKE_CASE__ : Tuple = output_stream[0] SCREAMING_SNAKE_CASE__ : Any = np.frombuffer(lowercase__ , np.floataa ) if audio.shape[0] == 0: raise ValueError('Malformed soundfile' ) return audio def _a ( lowercase__ : int , lowercase__ : float , lowercase__ : str = "f32le" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = f'''{sampling_rate}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '1' if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE__ : Optional[Any] = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE__ : List[str] = 4 else: raise ValueError(f'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''' ) SCREAMING_SNAKE_CASE__ : List[str] = platform.system() if system == "Linux": SCREAMING_SNAKE_CASE__ : Any = 'alsa' SCREAMING_SNAKE_CASE__ : int = 'default' elif system == "Darwin": SCREAMING_SNAKE_CASE__ : str = 'avfoundation' SCREAMING_SNAKE_CASE__ : Dict = ':0' elif system == "Windows": SCREAMING_SNAKE_CASE__ : Any = 'dshow' SCREAMING_SNAKE_CASE__ : Any = 'default' SCREAMING_SNAKE_CASE__ : List[str] = [ 'ffmpeg', '-f', format_, '-i', input_, '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-fflags', 'nobuffer', '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] SCREAMING_SNAKE_CASE__ : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample SCREAMING_SNAKE_CASE__ : List[Any] = _ffmpeg_stream(lowercase__ , lowercase__ ) for item in iterator: yield item def _a ( lowercase__ : int , lowercase__ : float , lowercase__ : Optional[int] = None , lowercase__ : Optional[Union[Tuple[float, float], float]] = None , lowercase__ : str = "f32le" , ): '''simple docstring''' if stream_chunk_s is not None: SCREAMING_SNAKE_CASE__ : Dict = stream_chunk_s else: SCREAMING_SNAKE_CASE__ : Optional[Any] = chunk_length_s SCREAMING_SNAKE_CASE__ : Union[str, Any] = ffmpeg_microphone(lowercase__ , lowercase__ , format_for_conversion=lowercase__ ) if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE__ : Tuple = np.intaa SCREAMING_SNAKE_CASE__ : Any = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE__ : Any = np.floataa SCREAMING_SNAKE_CASE__ : int = 4 else: raise ValueError(f'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''' ) if stride_length_s is None: SCREAMING_SNAKE_CASE__ : str = chunk_length_s / 6 SCREAMING_SNAKE_CASE__ : str = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(lowercase__ , (int, float) ): SCREAMING_SNAKE_CASE__ : Optional[Any] = [stride_length_s, stride_length_s] SCREAMING_SNAKE_CASE__ : Optional[int] = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample SCREAMING_SNAKE_CASE__ : str = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample SCREAMING_SNAKE_CASE__ : Any = datetime.datetime.now() SCREAMING_SNAKE_CASE__ : Any = datetime.timedelta(seconds=lowercase__ ) for item in chunk_bytes_iter(lowercase__ , lowercase__ , stride=(stride_left, stride_right) , stream=lowercase__ ): # Put everything back in numpy scale SCREAMING_SNAKE_CASE__ : Any = np.frombuffer(item['raw'] , dtype=lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = ( item['stride'][0] // size_of_sample, item['stride'][1] // size_of_sample, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def _a ( lowercase__ : Any , lowercase__ : int , lowercase__ : Tuple[int, int] , lowercase__ : bool = False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = b'' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = stride if stride_left + stride_right >= chunk_len: raise ValueError( f'''Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for raw in iterator: acc += raw if stream and len(lowercase__ ) < chunk_len: SCREAMING_SNAKE_CASE__ : Dict = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(lowercase__ ) >= chunk_len: # We are flushing the accumulator SCREAMING_SNAKE_CASE__ : List[Any] = (_stride_left, stride_right) SCREAMING_SNAKE_CASE__ : List[str] = {'raw': acc[:chunk_len], 'stride': stride} if stream: SCREAMING_SNAKE_CASE__ : List[str] = False yield item SCREAMING_SNAKE_CASE__ : Optional[Any] = stride_left SCREAMING_SNAKE_CASE__ : Tuple = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(lowercase__ ) > stride_left: SCREAMING_SNAKE_CASE__ : Tuple = {'raw': acc, 'stride': (_stride_left, 0)} if stream: SCREAMING_SNAKE_CASE__ : Tuple = False yield item def _a ( lowercase__ : List[Any] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2**24 # 16Mo try: with subprocess.Popen(lowercase__ , stdout=subprocess.PIPE , bufsize=lowercase__ ) as ffmpeg_process: while True: SCREAMING_SNAKE_CASE__ : int = ffmpeg_process.stdout.read(lowercase__ ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to stream audio files from filename' ) from error
636
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
1
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. SCREAMING_SNAKE_CASE__ : Optional[Any] = abspath(join(dirname(__file__), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def _a ( lowercase__ : Tuple ): '''simple docstring''' config.addinivalue_line( 'markers' , 'is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested' ) config.addinivalue_line( 'markers' , 'is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested' ) config.addinivalue_line('markers' , 'is_pipeline_test: mark test to run only when pipelines are tested' ) config.addinivalue_line('markers' , 'is_staging_test: mark test to run only in the staging environment' ) config.addinivalue_line('markers' , 'accelerate_tests: mark test that require accelerate' ) config.addinivalue_line('markers' , 'tool_tests: mark the tool tests that are run on their specific schedule' ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase__ ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' from transformers.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE__ : str = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(lowercase__ , id=lowercase__ ) def _a ( lowercase__ : Dict , lowercase__ : str ): '''simple docstring''' if exitstatus == 5: SCREAMING_SNAKE_CASE__ : List[str] = 0 # Doctest custom flag to ignore output. SCREAMING_SNAKE_CASE__ : Any = doctest.register_optionflag("IGNORE_RESULT") SCREAMING_SNAKE_CASE__ : Any = doctest.OutputChecker class snake_case ( UpperCamelCase_ ): def __lowercase( self : Any , a_ : str , a_ : Dict , a_ : List[Any] )-> Dict: """simple docstring""" if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = CustomOutputChecker SCREAMING_SNAKE_CASE__ : Tuple = HfDoctestModule SCREAMING_SNAKE_CASE__ : Union[str, Any] = HfDocTestParser
636
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase__ ) , lowercase__ ) ] 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[:-1]: opened_file.write(int(lowercase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
1
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_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : int , a_ : bool = True , a_ : Dict[str, int] = None , a_ : int = 0.9 , a_ : PILImageResampling = PILImageResampling.BICUBIC , a_ : bool = True , a_ : Dict[str, int] = None , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : bool = True , a_ : Optional[Union[float, List[float]]] = None , a_ : Optional[Union[float, List[float]]] = None , **a_ : List[Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'shortest_edge': 224} SCREAMING_SNAKE_CASE__ : Tuple = get_size_dict(a_ , default_to_square=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = crop_size if crop_size is not None else {'height': 224, 'width': 224} SCREAMING_SNAKE_CASE__ : str = get_size_dict(a_ , param_name='crop_size' ) SCREAMING_SNAKE_CASE__ : List[Any] = do_resize SCREAMING_SNAKE_CASE__ : Optional[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = crop_pct SCREAMING_SNAKE_CASE__ : Union[str, Any] = resample SCREAMING_SNAKE_CASE__ : Tuple = do_center_crop SCREAMING_SNAKE_CASE__ : Optional[Any] = crop_size SCREAMING_SNAKE_CASE__ : Any = do_rescale SCREAMING_SNAKE_CASE__ : List[Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE__ : List[str] = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN SCREAMING_SNAKE_CASE__ : Any = image_std if image_std is not None else IMAGENET_DEFAULT_STD def __lowercase( self : Union[str, Any] , a_ : np.ndarray , a_ : Dict[str, int] , a_ : Optional[float] = None , a_ : PILImageResampling = PILImageResampling.BICUBIC , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Dict , )-> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = get_size_dict(a_ , default_to_square=a_ ) if "shortest_edge" not in size and ("height" not in size or "width" not in size): raise ValueError(F'''size must contain \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' ) if crop_pct is not None: if "shortest_edge" in size: SCREAMING_SNAKE_CASE__ : Dict = int(size['shortest_edge'] / crop_pct ) elif "height" in size and "width" in size: if size["height"] == size["width"]: SCREAMING_SNAKE_CASE__ : Optional[Any] = int(size['height'] / crop_pct ) else: SCREAMING_SNAKE_CASE__ : Any = (int(size['height'] / crop_pct ), int(size['width'] / crop_pct )) else: raise ValueError('Invalid size for resize: {}'.format(a_ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = get_resize_output_image_size(a_ , size=a_ , default_to_square=a_ ) else: if "shortest_edge" in size: SCREAMING_SNAKE_CASE__ : str = get_resize_output_image_size(a_ , size=size['shortest_edge'] , default_to_square=a_ ) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE__ : Union[str, Any] = (size['height'], size['width']) else: raise ValueError('Invalid size for resize: {}'.format(a_ ) ) return resize(a_ , size=a_ , resample=a_ , data_format=a_ , **a_ ) def __lowercase( self : List[str] , a_ : np.ndarray , a_ : Dict[str, int] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : Dict , )-> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = get_size_dict(a_ ) if "height" not in size or "width" not in size: raise ValueError(F'''size must contain \'height\' and \'width\' as keys. Got {size.keys()}''' ) return center_crop(a_ , size=(size['height'], size['width']) , data_format=a_ , **a_ ) def __lowercase( self : str , a_ : np.ndarray , a_ : Union[int, float] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : List[Any] , )-> str: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : List[Any] , a_ : np.ndarray , a_ : Union[float, List[float]] , a_ : Union[float, List[float]] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : List[Any] , )-> np.ndarray: """simple docstring""" return normalize(a_ , mean=a_ , std=a_ , data_format=a_ , **a_ ) def __lowercase( self : Optional[int] , a_ : ImageInput , a_ : bool = None , a_ : Dict[str, int] = None , a_ : int = None , a_ : PILImageResampling = None , a_ : bool = None , a_ : Dict[str, int] = None , a_ : bool = None , a_ : float = None , a_ : bool = None , a_ : Optional[Union[float, List[float]]] = None , a_ : Optional[Union[float, List[float]]] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : ChannelDimension = ChannelDimension.FIRST , **a_ : str , )-> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ : str = crop_pct if crop_pct is not None else self.crop_pct SCREAMING_SNAKE_CASE__ : Optional[Any] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE__ : Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE__ : List[Any] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : int = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE__ : Any = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE__ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE__ : List[str] = get_size_dict(a_ , default_to_square=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE__ : Any = get_size_dict(a_ , param_name='crop_size' ) SCREAMING_SNAKE_CASE__ : int = make_list_of_images(a_ ) if not valid_images(a_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_center_crop and crop_pct is None: raise ValueError('Crop_pct 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. SCREAMING_SNAKE_CASE__ : Optional[Any] = [to_numpy_array(a_ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE__ : int = [self.resize(image=a_ , size=a_ , crop_pct=a_ , resample=a_ ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE__ : str = [self.center_crop(image=a_ , size=a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Any = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE__ : Optional[Any] = [self.normalize(image=a_ , mean=a_ , std=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Optional[int] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Any = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
636
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
1
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( 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 __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
1
from manim import * class snake_case ( UpperCamelCase_ ): def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = Rectangle(height=0.5 , width=0.5 ) SCREAMING_SNAKE_CASE__ : str = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : int = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : List[str] = VGroup(*a_ ).arrange(a_ , buff=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = VGroup(*a_ ).arrange(a_ , buff=0 ) SCREAMING_SNAKE_CASE__ : int = VGroup(a_ , a_ ).arrange(a_ , buff=0 ) SCREAMING_SNAKE_CASE__ : Tuple = Text('CPU' , font_size=24 ) SCREAMING_SNAKE_CASE__ : Dict = Group(a_ , a_ ).arrange(a_ , buff=0.5 , aligned_edge=a_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(a_ ) SCREAMING_SNAKE_CASE__ : str = [mem.copy() for i in range(4 )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = VGroup(*a_ ).arrange(a_ , buff=0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Text('GPU' , font_size=24 ) SCREAMING_SNAKE_CASE__ : Dict = Group(a_ , a_ ).arrange(a_ , buff=0.5 , aligned_edge=a_ ) gpu.move_to([-1, -1, 0] ) self.add(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : Optional[int] = VGroup(*a_ ).arrange(a_ , buff=0 ) SCREAMING_SNAKE_CASE__ : int = Text('Model' , font_size=24 ) SCREAMING_SNAKE_CASE__ : str = Group(a_ , a_ ).arrange(a_ , buff=0.5 , aligned_edge=a_ ) model.move_to([3, -1.0, 0] ) self.add(a_ ) SCREAMING_SNAKE_CASE__ : int = [] for i, rect in enumerate(a_ ): rect.set_stroke(a_ ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) SCREAMING_SNAKE_CASE__ : Optional[Any] = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(a_ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=a_ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=a_ , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=a_ , buff=0.0 ) self.add(a_ ) cpu_targs.append(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = [mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE__ : Optional[Any] = VGroup(*a_ ).arrange(a_ , buff=0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Text('Loaded Checkpoint' , font_size=24 ) SCREAMING_SNAKE_CASE__ : Dict = Group(a_ , a_ ).arrange(a_ , aligned_edge=a_ , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) SCREAMING_SNAKE_CASE__ : str = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) SCREAMING_SNAKE_CASE__ : str = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = MarkupText( F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=18 , ) blue_text.next_to(a_ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) SCREAMING_SNAKE_CASE__ : int = MarkupText( F'''Next, a <i><span fgcolor="{BLUE}">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor="{BLUE}">single shard</span>.''' , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(a_ ) , Write(a_ ) ) self.play(Write(a_ , run_time=1 ) , Create(a_ , run_time=1 ) ) SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : str = [] for i, rect in enumerate(a_ ): SCREAMING_SNAKE_CASE__ : List[str] = fill.copy().set_fill(a_ , opacity=0.7 ) target.move_to(a_ ) first_animations.append(GrowFromCenter(a_ , run_time=1 ) ) SCREAMING_SNAKE_CASE__ : List[str] = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(a_ , run_time=1.5 ) ) self.play(*a_ ) self.play(*a_ ) self.wait()
636
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
1
from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "deepmind/language-perceiver": "https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json", # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class snake_case ( UpperCamelCase_ ): lowercase_ = 'perceiver' def __init__( self : Tuple , a_ : int=256 , a_ : Dict=1280 , a_ : Optional[int]=768 , a_ : Union[str, Any]=1 , a_ : Optional[Any]=26 , a_ : Union[str, Any]=8 , a_ : Dict=8 , a_ : Union[str, Any]=None , a_ : Tuple=None , a_ : List[Any]="kv" , a_ : Dict=1 , a_ : Union[str, Any]=1 , a_ : Tuple="gelu" , a_ : Any=0.1 , a_ : Tuple=0.02 , a_ : Dict=1e-1_2 , a_ : Tuple=True , a_ : List[Any]=262 , a_ : Any=2048 , a_ : Optional[int]=56 , a_ : Dict=[368, 496] , a_ : List[Any]=16 , a_ : int=1920 , a_ : Tuple=16 , a_ : Optional[int]=[1, 16, 224, 224] , **a_ : str , )-> int: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : str = num_latents SCREAMING_SNAKE_CASE__ : Optional[int] = d_latents SCREAMING_SNAKE_CASE__ : Union[str, Any] = d_model SCREAMING_SNAKE_CASE__ : Any = num_blocks SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_self_attends_per_block SCREAMING_SNAKE_CASE__ : Tuple = num_self_attention_heads SCREAMING_SNAKE_CASE__ : int = num_cross_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = qk_channels SCREAMING_SNAKE_CASE__ : Tuple = v_channels SCREAMING_SNAKE_CASE__ : str = cross_attention_shape_for_attention SCREAMING_SNAKE_CASE__ : Union[str, Any] = self_attention_widening_factor SCREAMING_SNAKE_CASE__ : str = cross_attention_widening_factor SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Dict = use_query_residual # masked language modeling attributes SCREAMING_SNAKE_CASE__ : Dict = vocab_size SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings # image classification attributes SCREAMING_SNAKE_CASE__ : str = image_size # flow attributes SCREAMING_SNAKE_CASE__ : int = train_size # multimodal autoencoding attributes SCREAMING_SNAKE_CASE__ : Optional[int] = num_frames SCREAMING_SNAKE_CASE__ : int = audio_samples_per_frame SCREAMING_SNAKE_CASE__ : int = samples_per_patch SCREAMING_SNAKE_CASE__ : List[str] = output_shape class snake_case ( UpperCamelCase_ ): @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : Union[str, Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: SCREAMING_SNAKE_CASE__ : Any = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('inputs', dynamic_axis), ('attention_mask', dynamic_axis), ] ) @property def __lowercase( self : Tuple )-> float: """simple docstring""" return 1e-4 def __lowercase( self : List[str] , a_ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , a_ : int = -1 , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional[TensorType] = None , a_ : int = 3 , a_ : int = 40 , a_ : int = 40 , )-> Mapping[str, Any]: """simple docstring""" # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(a_ , a_ ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Union[str, Any] = compute_effective_axis_dimension( a_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Union[str, Any] = preprocessor.num_special_tokens_to_add(a_ ) SCREAMING_SNAKE_CASE__ : str = compute_effective_axis_dimension( a_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=a_ ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE__ : Dict = [' '.join(['a'] ) * seq_length] * batch_size SCREAMING_SNAKE_CASE__ : Any = dict(preprocessor(a_ , return_tensors=a_ ) ) SCREAMING_SNAKE_CASE__ : int = inputs.pop('input_ids' ) return inputs elif isinstance(a_ , a_ ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Union[str, Any] = compute_effective_axis_dimension(a_ , fixed_dimension=OnnxConfig.default_fixed_batch ) SCREAMING_SNAKE_CASE__ : List[str] = self._generate_dummy_images(a_ , a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = dict(preprocessor(images=a_ , return_tensors=a_ ) ) SCREAMING_SNAKE_CASE__ : int = inputs.pop('pixel_values' ) return inputs else: raise ValueError( 'Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.' )
636
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Tuple = { "configuration_lxmert": ["LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LxmertConfig"], "tokenization_lxmert": ["LxmertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = ["LxmertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Dict = [ "LxmertEncoder", "LxmertForPreTraining", "LxmertForQuestionAnswering", "LxmertModel", "LxmertPreTrainedModel", "LxmertVisualFeatureEncoder", "LxmertXLayer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLxmertForPreTraining", "TFLxmertMainLayer", "TFLxmertModel", "TFLxmertPreTrainedModel", "TFLxmertVisualFeatureEncoder", ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys SCREAMING_SNAKE_CASE__ : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
636
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" 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 __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" 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=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
1
from ..utils import DummyObject, requires_backends class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : List[Any] , *a_ : int , **a_ : Any )-> Dict: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : str , **a_ : int )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Union[str, Any] , *a_ : Union[str, Any] , **a_ : Tuple )-> str: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : str , *a_ : List[Any] , **a_ : Dict )-> Optional[Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : List[Any] , **a_ : Union[str, Any] )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : str , *a_ : str , **a_ : List[Any] )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : str , *a_ : List[str] , **a_ : Dict )-> str: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : str , *a_ : Tuple , **a_ : Optional[int] )-> Optional[int]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Any , *a_ : Any , **a_ : Tuple )-> List[str]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Any , *a_ : Union[str, Any] , **a_ : Union[str, Any] )-> List[Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Any , *a_ : int , **a_ : List[Any] )-> Any: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Union[str, Any] , *a_ : List[Any] , **a_ : List[str] )-> Optional[int]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : List[Any] , *a_ : List[str] , **a_ : Dict )-> int: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Tuple , *a_ : Dict , **a_ : List[Any] )-> Any: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : List[str] , *a_ : Tuple , **a_ : int )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Any , *a_ : Any , **a_ : Dict )-> List[str]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Union[str, Any] , *a_ : Optional[int] , **a_ : Optional[int] )-> Any: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Any , *a_ : List[Any] , **a_ : Dict )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Optional[int] , *a_ : Optional[Any] , **a_ : Dict )-> Optional[int]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : Any , **a_ : List[Any] )-> Dict: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Union[str, Any] , *a_ : List[Any] , **a_ : Union[str, Any] )-> Union[str, Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Tuple , *a_ : Optional[Any] , **a_ : Optional[Any] )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : List[Any] , **a_ : List[Any] )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : List[str] , *a_ : Union[str, Any] , **a_ : str )-> Tuple: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : Tuple , **a_ : Optional[int] )-> int: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Tuple , *a_ : List[str] , **a_ : List[Any] )-> Optional[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Tuple , *a_ : Union[str, Any] , **a_ : Any )-> str: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : str , *a_ : List[Any] , **a_ : int )-> int: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : str , **a_ : str )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Union[str, Any] , *a_ : Optional[int] , **a_ : Dict )-> List[Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Tuple , *a_ : Optional[int] , **a_ : Optional[Any] )-> List[str]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : List[Any] , **a_ : Optional[Any] )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) def _a ( *lowercase__ : Optional[int] , **lowercase__ : List[str] ): '''simple docstring''' requires_backends(lowercase__ , ['torch'] ) def _a ( *lowercase__ : str , **lowercase__ : Optional[int] ): '''simple docstring''' requires_backends(lowercase__ , ['torch'] ) def _a ( *lowercase__ : List[Any] , **lowercase__ : Dict ): '''simple docstring''' requires_backends(lowercase__ , ['torch'] ) def _a ( *lowercase__ : List[Any] , **lowercase__ : List[Any] ): '''simple docstring''' requires_backends(lowercase__ , ['torch'] ) def _a ( *lowercase__ : List[Any] , **lowercase__ : Any ): '''simple docstring''' requires_backends(lowercase__ , ['torch'] ) def _a ( *lowercase__ : List[Any] , **lowercase__ : Dict ): '''simple docstring''' requires_backends(lowercase__ , ['torch'] ) def _a ( *lowercase__ : List[Any] , **lowercase__ : Union[str, Any] ): '''simple docstring''' requires_backends(lowercase__ , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : int , *a_ : Any , **a_ : List[str] )-> List[str]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : Tuple , **a_ : str )-> List[str]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : List[str] , *a_ : Tuple , **a_ : List[str] )-> Optional[int]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Union[str, Any] , *a_ : Tuple , **a_ : Optional[Any] )-> Tuple: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : Dict , **a_ : int )-> Optional[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : Any , **a_ : Optional[int] )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : int , *a_ : Union[str, Any] , **a_ : List[Any] )-> str: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : Tuple , **a_ : Dict )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Any , *a_ : List[str] , **a_ : Optional[Any] )-> Optional[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Optional[Any] , *a_ : int , **a_ : int )-> List[Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : int , **a_ : Union[str, Any] )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : Optional[int] , **a_ : Union[str, Any] )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : int , *a_ : Optional[Any] , **a_ : str )-> Union[str, Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Optional[Any] , *a_ : Tuple , **a_ : Dict )-> str: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : List[Any] , *a_ : Any , **a_ : str )-> Dict: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Any , *a_ : str , **a_ : List[Any] )-> Optional[Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : int , **a_ : Tuple )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Union[str, Any] , *a_ : Tuple , **a_ : Dict )-> Dict: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Union[str, Any] , *a_ : Optional[Any] , **a_ : Optional[int] )-> List[str]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : Union[str, Any] , **a_ : str )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : Optional[Any] , **a_ : Optional[int] )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : str , *a_ : int , **a_ : Optional[Any] )-> Dict: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : Optional[Any] , **a_ : Any )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : List[str] , **a_ : Optional[int] )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Dict , *a_ : Any , **a_ : Dict )-> int: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : Optional[int] , **a_ : List[str] )-> int: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[Any] , *a_ : List[str] , **a_ : Tuple )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Tuple , *a_ : Any , **a_ : Optional[Any] )-> Any: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : List[str] , *a_ : int , **a_ : Union[str, Any] )-> Optional[int]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Union[str, Any] , *a_ : Optional[Any] , **a_ : Dict )-> Optional[int]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Optional[int] , *a_ : Any , **a_ : Tuple )-> Union[str, Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Union[str, Any] , *a_ : Tuple , **a_ : List[Any] )-> Optional[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : Optional[int] , **a_ : Tuple )-> Dict: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Optional[int] , *a_ : Any , **a_ : Optional[Any] )-> Union[str, Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Union[str, Any] , *a_ : Tuple , **a_ : List[str] )-> Any: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : Tuple , **a_ : str )-> Optional[int]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Tuple , *a_ : List[Any] , **a_ : Union[str, Any] )-> Tuple: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : str , **a_ : Any )-> int: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : List[str] , *a_ : List[Any] , **a_ : List[Any] )-> Optional[int]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : int , *a_ : Union[str, Any] , **a_ : int )-> Union[str, Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : Dict , **a_ : List[str] )-> int: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : Any , **a_ : List[Any] )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Dict , *a_ : Optional[Any] , **a_ : Optional[Any] )-> Union[str, Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : List[str] , *a_ : str , **a_ : int )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Tuple , *a_ : str , **a_ : Dict )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Optional[Any] , *a_ : Dict , **a_ : List[Any] )-> int: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : Optional[Any] , **a_ : Tuple )-> Any: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Any , *a_ : Union[str, Any] , **a_ : Optional[Any] )-> List[str]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Dict , *a_ : str , **a_ : Dict )-> Union[str, Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Any , *a_ : str , **a_ : Tuple )-> Optional[int]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Tuple , *a_ : Any , **a_ : str )-> str: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : str , *a_ : Dict , **a_ : Union[str, Any] )-> Optional[Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Union[str, Any] , *a_ : Tuple , **a_ : Dict )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : List[Any] , *a_ : int , **a_ : Dict )-> str: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Dict , *a_ : str , **a_ : List[str] )-> Any: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : str , *a_ : Union[str, Any] , **a_ : List[str] )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[Any] , *a_ : Tuple , **a_ : List[str] )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Tuple , *a_ : Optional[int] , **a_ : Any )-> Optional[int]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Tuple , *a_ : List[str] , **a_ : Optional[int] )-> List[str]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Tuple , *a_ : Union[str, Any] , **a_ : int )-> Optional[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Any , *a_ : int , **a_ : List[str] )-> Tuple: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Tuple , *a_ : Dict , **a_ : List[Any] )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : List[str] , *a_ : int , **a_ : Any )-> Any: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Tuple , *a_ : str , **a_ : Dict )-> int: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Union[str, Any] , *a_ : Dict , **a_ : Tuple )-> Optional[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : Optional[int] , **a_ : Tuple )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Any , *a_ : Optional[int] , **a_ : int )-> List[str]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Optional[Any] , *a_ : Optional[int] , **a_ : Any )-> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : List[str] , **a_ : Optional[Any] )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Optional[Any] , *a_ : List[str] , **a_ : Optional[int] )-> Tuple: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : List[str] , *a_ : Optional[int] , **a_ : List[str] )-> Dict: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : List[str] , *a_ : Dict , **a_ : Tuple )-> Any: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Optional[int] , *a_ : List[str] , **a_ : List[str] )-> Optional[int]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : List[Any] , *a_ : str , **a_ : List[Any] )-> List[str]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Union[str, Any] , *a_ : int , **a_ : str )-> str: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : int , *a_ : int , **a_ : int )-> Optional[Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : List[Any] , *a_ : Tuple , **a_ : str )-> List[str]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[Any] , *a_ : Any , **a_ : Dict )-> str: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Optional[Any] , *a_ : Optional[int] , **a_ : Optional[int] )-> str: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : List[str] , **a_ : Any )-> Any: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : int , **a_ : Dict )-> Optional[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : List[Any] , *a_ : Any , **a_ : Any )-> Optional[Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Tuple , *a_ : Tuple , **a_ : Tuple )-> int: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : List[str] , **a_ : Tuple )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Dict , *a_ : Dict , **a_ : Optional[Any] )-> int: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : str , **a_ : Optional[Any] )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Any , *a_ : Any , **a_ : Optional[int] )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : int , *a_ : List[Any] , **a_ : Optional[Any] )-> List[str]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : List[str] , *a_ : Tuple , **a_ : Optional[int] )-> Optional[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : Optional[Any] , **a_ : Union[str, Any] )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Dict , *a_ : Dict , **a_ : Any )-> Tuple: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Tuple , *a_ : int , **a_ : Tuple )-> Any: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[Any] , *a_ : Union[str, Any] , **a_ : Dict )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : int , *a_ : Optional[Any] , **a_ : Any )-> Dict: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Optional[Any] , *a_ : Any , **a_ : int )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : Union[str, Any] , **a_ : List[Any] )-> Dict: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Dict , *a_ : int , **a_ : int )-> Dict: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : Optional[Any] , **a_ : Optional[Any] )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : List[str] , *a_ : Any , **a_ : Dict )-> Optional[int]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Dict , *a_ : int , **a_ : Tuple )-> List[str]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : str , *a_ : str , **a_ : Any )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : Tuple , **a_ : Union[str, Any] )-> Optional[int]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : int , *a_ : Dict , **a_ : Optional[Any] )-> Tuple: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Dict , *a_ : Tuple , **a_ : Optional[int] )-> Tuple: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Any , *a_ : List[str] , **a_ : List[Any] )-> str: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Optional[int] , *a_ : List[Any] , **a_ : Any )-> List[str]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : List[Any] , *a_ : str , **a_ : Union[str, Any] )-> Dict: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : List[Any] , *a_ : List[Any] , **a_ : int )-> int: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Union[str, Any] , *a_ : str , **a_ : Tuple )-> List[str]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : int , *a_ : Any , **a_ : Union[str, Any] )-> Dict: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Optional[int] , *a_ : Any , **a_ : Tuple )-> Any: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : str , *a_ : List[str] , **a_ : Union[str, Any] )-> List[Any]: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : str , *a_ : Union[str, Any] , **a_ : Optional[Any] )-> Dict: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : Any , *a_ : List[Any] , **a_ : int )-> List[Any]: """simple docstring""" requires_backends(cls , ['torch'] ) class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch'] def __init__( self : Optional[Any] , *a_ : Union[str, Any] , **a_ : Optional[Any] )-> int: """simple docstring""" requires_backends(self , ['torch'] ) @classmethod def __lowercase( cls : Union[str, Any] , *a_ : Union[str, Any] , **a_ : List[str] )-> int: """simple docstring""" requires_backends(cls , ['torch'] ) @classmethod def __lowercase( cls : List[str] , *a_ : int , **a_ : List[str] )-> Any: """simple docstring""" requires_backends(cls , ['torch'] )
636
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
1
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
1
from ..utils import DummyObject, requires_backends class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['onnx'] def __init__( self : str , *a_ : Tuple , **a_ : Dict )-> Union[str, Any]: """simple docstring""" requires_backends(self , ['onnx'] ) @classmethod def __lowercase( cls : Any , *a_ : List[Any] , **a_ : int )-> Optional[int]: """simple docstring""" requires_backends(cls , ['onnx'] ) @classmethod def __lowercase( cls : List[Any] , *a_ : int , **a_ : List[str] )-> List[str]: """simple docstring""" requires_backends(cls , ['onnx'] )
636
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a_ , a_ ) def __call__( self : Any , a_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , a_ , ) return self.image_processor_class @property def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
1
from math import isclose, sqrt def _a ( lowercase__ : float , lowercase__ : float , lowercase__ : float ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = point_y / 4 / point_x SCREAMING_SNAKE_CASE__ : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) SCREAMING_SNAKE_CASE__ : List[str] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) SCREAMING_SNAKE_CASE__ : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 SCREAMING_SNAKE_CASE__ : Optional[int] = outgoing_gradient**2 + 4 SCREAMING_SNAKE_CASE__ : Any = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) SCREAMING_SNAKE_CASE__ : List[str] = (point_y - outgoing_gradient * point_x) ** 2 - 1_00 SCREAMING_SNAKE_CASE__ : Tuple = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) SCREAMING_SNAKE_CASE__ : int = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point SCREAMING_SNAKE_CASE__ : List[Any] = x_minus if isclose(lowercase__ , lowercase__ ) else x_plus SCREAMING_SNAKE_CASE__ : List[str] = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _a ( lowercase__ : float = 1.4 , lowercase__ : float = -9.6 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = 0 SCREAMING_SNAKE_CASE__ : float = first_x_coord SCREAMING_SNAKE_CASE__ : float = first_y_coord SCREAMING_SNAKE_CASE__ : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = next_point(lowercase__ , lowercase__ , lowercase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
636
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
1
def _a ( lowercase__ : int = 4_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [0, 1] SCREAMING_SNAKE_CASE__ : Any = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 SCREAMING_SNAKE_CASE__ : Any = 0 for j in range(len(lowercase__ ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(F"""{solution() = }""")
636
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
1
# Copyright 2023 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 torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
1
from __future__ import annotations import math import numpy as np from numpy.linalg import norm def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' return math.sqrt(sum(pow(a - b , 2 ) for a, b in zip(lowercase__ , lowercase__ ) ) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' if dataset.ndim != value_array.ndim: SCREAMING_SNAKE_CASE__ : Dict = ( 'Wrong input data\'s dimensions... ' f'''dataset : {dataset.ndim}, value_array : {value_array.ndim}''' ) raise ValueError(lowercase__ ) try: if dataset.shape[1] != value_array.shape[1]: SCREAMING_SNAKE_CASE__ : str = ( 'Wrong input data\'s shape... ' f'''dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}''' ) raise ValueError(lowercase__ ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError('Wrong shape' ) if dataset.dtype != value_array.dtype: SCREAMING_SNAKE_CASE__ : List[Any] = ( 'Input data have different datatype... ' f'''dataset : {dataset.dtype}, value_array : {value_array.dtype}''' ) raise TypeError(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = [] for value in value_array: SCREAMING_SNAKE_CASE__ : List[Any] = euclidean(lowercase__ , dataset[0] ) SCREAMING_SNAKE_CASE__ : str = dataset[0].tolist() for dataset_value in dataset[1:]: SCREAMING_SNAKE_CASE__ : Any = euclidean(lowercase__ , lowercase__ ) if dist > temp_dist: SCREAMING_SNAKE_CASE__ : List[str] = temp_dist SCREAMING_SNAKE_CASE__ : List[Any] = dataset_value.tolist() answer.append([vector, dist] ) return answer def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' return np.dot(lowercase__ , lowercase__ ) / (norm(lowercase__ ) * norm(lowercase__ )) if __name__ == "__main__": import doctest doctest.testmod()
636
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
1
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class snake_case ( UpperCamelCase_ ): lowercase_ = 'Speech2TextFeatureExtractor' lowercase_ = 'Speech2TextTokenizer' def __init__( self : Union[str, Any] , a_ : Optional[int] , a_ : Any )-> List[str]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.feature_extractor SCREAMING_SNAKE_CASE__ : Dict = False def __call__( self : Tuple , *a_ : Optional[Any] , **a_ : Dict )-> Optional[int]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*a_ , **a_ ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) SCREAMING_SNAKE_CASE__ : Any = kwargs.pop('raw_speech' ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop('audio' , a_ ) SCREAMING_SNAKE_CASE__ : int = kwargs.pop('sampling_rate' , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs.pop('text' , a_ ) if len(a_ ) > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = args[0] SCREAMING_SNAKE_CASE__ : List[Any] = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: SCREAMING_SNAKE_CASE__ : int = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ ) if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer(a_ , **a_ ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE__ : List[str] = encodings['input_ids'] return inputs def __lowercase( self : int , *a_ : List[Any] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @contextmanager def __lowercase( self : Dict )-> List[Any]: """simple docstring""" warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer yield SCREAMING_SNAKE_CASE__ : Dict = self.feature_extractor SCREAMING_SNAKE_CASE__ : Optional[int] = False
636
# Copyright 2023 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 torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
1
# Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Any] , lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = { 'en': 'Machine learning is great, isn\'t it?', 'ru': 'Машинное обучение - это здорово, не так ли?', 'de': 'Maschinelles Lernen ist großartig, nicht wahr?', } # BLUE scores as follows: # "pair": [fairseq, transformers] SCREAMING_SNAKE_CASE__ : str = { 'wmt16-en-de-dist-12-1': [28.3, 27.52], 'wmt16-en-de-dist-6-1': [27.4, 27.11], 'wmt16-en-de-12-1': [26.9, 25.75], } SCREAMING_SNAKE_CASE__ : Dict = f'''{src_lang}-{tgt_lang}''' SCREAMING_SNAKE_CASE__ : Tuple = f''' --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt16 - allenai license: apache-2.0 datasets: - wmt16 metrics: - bleu --- # FSMT ## Model description This is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}. For more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369). All 3 models are available: * [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1) * [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1) * [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = "allenai/{model_name}" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = "{texts[src_lang]}" input_ids = tokenizer.encode(input, return_tensors="pt") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias ## Training data Pretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369). ## Eval results Here are the BLEU scores: model | fairseq | transformers -------|---------|---------- {model_name} | {scores[model_name][0]} | {scores[model_name][1]} The score is slightly below the score reported in the paper, as the researchers don\'t use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs. The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=5 mkdir -p $DATA_DIR sacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` ## Data Sources - [training, etc.](http://www.statmt.org/wmt16/) - [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372) ### BibTeX entry and citation info ``` @misc{{kasai2020deep, title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}}, author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}}, year={{2020}}, eprint={{2006.10369}}, archivePrefix={{arXiv}}, primaryClass={{cs.CL}} }} ``` ''' model_card_dir.mkdir(parents=lowercase__ , exist_ok=lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(lowercase__ , 'README.md' ) print(f'''Generating {path}''' ) with open(lowercase__ , 'w' , encoding='utf-8' ) as f: f.write(lowercase__ ) # make sure we are under the root of the project SCREAMING_SNAKE_CASE__ : str = Path(__file__).resolve().parent.parent.parent SCREAMING_SNAKE_CASE__ : Any = repo_dir / "model_cards" for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: SCREAMING_SNAKE_CASE__ : Tuple = model_cards_dir / "allenai" / model_name write_model_card(model_card_dir, src_lang="en", tgt_lang="de", model_name=model_name)
636
import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[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 SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
1
import os import pytest from transformers.dynamic_module_utils import get_imports SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\nimport os\n" SCREAMING_SNAKE_CASE__ : List[Any] = "\ndef foo():\n import os\n return False\n" SCREAMING_SNAKE_CASE__ : str = "\ndef foo():\n def bar():\n if True:\n import os\n return False\n return bar()\n" SCREAMING_SNAKE_CASE__ : Any = "\nimport os\n\ntry:\n import bar\nexcept ImportError:\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : int = "\nimport os\n\ndef foo():\n try:\n import bar\n except ImportError:\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : Dict = "\nimport os\n\ntry:\n import bar\nexcept (ImportError, AttributeError):\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : Dict = "\nimport os\n\ntry:\n import bar\nexcept ImportError as e:\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : List[str] = "\nimport os\n\ntry:\n import bar\nexcept:\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : List[str] = "\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : Optional[int] = "\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n x = 1\n raise ValueError()\n" SCREAMING_SNAKE_CASE__ : int = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize('case' , lowercase__ ) def _a ( lowercase__ : Optional[Any] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(lowercase__ , 'test_file.py' ) with open(lowercase__ , 'w' ) as _tmp_file: _tmp_file.write(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = get_imports(lowercase__ ) assert parsed_imports == ["os"]
636
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
1
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''simple docstring''' assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
636
1
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) class snake_case : lowercase_ = None @experimental def _a ( lowercase__ : Any , lowercase__ : str , lowercase__ : Dict , lowercase__ : Any , lowercase__ : Union[str, Any] , lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if ParallelBackendConfig.backend_name is None: return _map_with_multiprocessing_pool( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) return _map_with_joblib(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : Optional[int] , lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : int , lowercase__ : Union[str, Any] , lowercase__ : str , lowercase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = num_proc if num_proc <= len(lowercase__ ) else len(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = [] # We organize the splits ourselve (contiguous splits) for index in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = len(lowercase__ ) // num_proc SCREAMING_SNAKE_CASE__ : Any = len(lowercase__ ) % num_proc SCREAMING_SNAKE_CASE__ : Dict = div * index + min(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = start + div + (1 if index < mod else 0) split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc) ) if len(lowercase__ ) != sum(len(i[1] ) for i in split_kwds ): raise ValueError( f'''Error dividing inputs iterable among processes. ''' f'''Total number of objects {len(lowercase__ )}, ''' f'''length: {sum(len(i[1] ) for i in split_kwds )}''' ) logger.info( f'''Spawning {num_proc} processes for {len(lowercase__ )} objects in slices of {[len(i[1] ) for i in split_kwds]}''' ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = None, None if not disable_tqdm: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = (RLock(),), tqdm.set_lock with Pool(lowercase__ , initargs=lowercase__ , initializer=lowercase__ ) as pool: SCREAMING_SNAKE_CASE__ : Any = pool.map(lowercase__ , lowercase__ ) logger.info(f'''Finished {num_proc} processes''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [obj for proc_res in mapped for obj in proc_res] logger.info(f'''Unpacked {len(lowercase__ )} objects''' ) return mapped def _a ( lowercase__ : Dict , lowercase__ : List[str] , lowercase__ : List[Any] , lowercase__ : Any , lowercase__ : Tuple , lowercase__ : Optional[int] , lowercase__ : str ): '''simple docstring''' import joblib with joblib.parallel_backend(ParallelBackendConfig.backend_name , n_jobs=lowercase__ ): return joblib.Parallel()( joblib.delayed(lowercase__ )((function, obj, types, None, True, None) ) for obj in iterable ) @experimental @contextlib.contextmanager def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = backend_name if backend_name == "spark": from joblibspark import register_spark register_spark() # TODO: call create_cache_and_write_probe if "download" in steps # TODO: raise NotImplementedError when Dataset.map etc is called try: yield finally: SCREAMING_SNAKE_CASE__ : Tuple = None
636
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
636
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json", # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class snake_case ( UpperCamelCase_ ): lowercase_ = 'gpt_neox' def __init__( self : Any , a_ : Optional[int]=5_0432 , a_ : int=6144 , a_ : List[str]=44 , a_ : int=64 , a_ : str=2_4576 , a_ : Dict="gelu" , a_ : Any=0.25 , a_ : Any=1_0000 , a_ : Tuple=0.0 , a_ : str=0.0 , a_ : int=0.1 , a_ : List[Any]=2048 , a_ : List[Any]=0.02 , a_ : Dict=1e-5 , a_ : Optional[int]=True , a_ : Optional[int]=0 , a_ : Any=2 , a_ : int=False , a_ : Tuple=True , a_ : Dict=None , **a_ : List[Any] , )-> Tuple: """simple docstring""" super().__init__(bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Any = rotary_pct SCREAMING_SNAKE_CASE__ : Optional[int] = rotary_emb_base SCREAMING_SNAKE_CASE__ : Any = attention_dropout SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout SCREAMING_SNAKE_CASE__ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE__ : Dict = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : int = use_cache SCREAMING_SNAKE_CASE__ : Tuple = tie_word_embeddings SCREAMING_SNAKE_CASE__ : List[str] = use_parallel_residual SCREAMING_SNAKE_CASE__ : List[Any] = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( 'The hidden size is not divisble by the number of attention heads! Make sure to update them!' ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , a_ ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' F'''got {self.rope_scaling}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rope_scaling.get('type' , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.rope_scaling.get('factor' , a_ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(a_ , a_ ) or rope_scaling_factor <= 1.0: raise ValueError(F'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
636
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/config.json", "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/config.json" # See all FNet models at https://huggingface.co/models?filter=fnet } class snake_case ( UpperCamelCase_ ): lowercase_ = 'fnet' def __init__( self : Optional[Any] , a_ : List[str]=3_2000 , a_ : Dict=768 , a_ : int=12 , a_ : List[Any]=3072 , a_ : List[str]="gelu_new" , a_ : List[Any]=0.1 , a_ : str=512 , a_ : str=4 , a_ : List[str]=0.02 , a_ : Optional[Any]=1e-1_2 , a_ : int=False , a_ : Optional[int]=512 , a_ : Optional[int]=3 , a_ : List[str]=1 , a_ : Any=2 , **a_ : Optional[Any] , )-> Any: """simple docstring""" super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : Any = num_hidden_layers SCREAMING_SNAKE_CASE__ : int = intermediate_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_act SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : str = type_vocab_size SCREAMING_SNAKE_CASE__ : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = use_tpu_fourier_optimizations SCREAMING_SNAKE_CASE__ : Optional[Any] = tpu_short_seq_length
636
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
1
class snake_case : def __init__( self : Tuple , a_ : int )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = size SCREAMING_SNAKE_CASE__ : Dict = [0] * size SCREAMING_SNAKE_CASE__ : Union[str, Any] = [0] * size @staticmethod def __lowercase( a_ : int )-> int: """simple docstring""" return index | (index + 1) @staticmethod def __lowercase( a_ : int )-> int: """simple docstring""" return (index & (index + 1)) - 1 def __lowercase( self : List[str] , a_ : int , a_ : int )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = value while index < self.size: SCREAMING_SNAKE_CASE__ : Tuple = self.get_prev(a_ ) + 1 if current_left_border == index: SCREAMING_SNAKE_CASE__ : str = value else: SCREAMING_SNAKE_CASE__ : Any = max(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_next(a_ ) def __lowercase( self : int , a_ : int , a_ : int )-> int: """simple docstring""" right -= 1 # Because of right is exclusive SCREAMING_SNAKE_CASE__ : Dict = 0 while left <= right: SCREAMING_SNAKE_CASE__ : Tuple = self.get_prev(a_ ) if left <= current_left: SCREAMING_SNAKE_CASE__ : List[str] = max(a_ , self.tree[right] ) SCREAMING_SNAKE_CASE__ : Optional[int] = current_left else: SCREAMING_SNAKE_CASE__ : Any = max(a_ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
636
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( 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 __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
1
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class snake_case ( UpperCamelCase_ , UpperCamelCase_ ): @register_to_config def __init__( self : Tuple , a_ : int = 128 , a_ : int = 256 , a_ : float = 2000.0 , a_ : int = 768 , a_ : int = 12 , a_ : int = 12 , a_ : int = 64 , a_ : int = 2048 , a_ : float = 0.1 , )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Union[str, Any] = nn.Sequential( nn.Linear(a_ , d_model * 4 , bias=a_ ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=a_ ) , nn.SiLU() , ) SCREAMING_SNAKE_CASE__ : Any = nn.Embedding(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.Linear(a_ , a_ , bias=a_ ) SCREAMING_SNAKE_CASE__ : int = nn.Dropout(p=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.ModuleList() for lyr_num in range(a_ ): # FiLM conditional T5 decoder SCREAMING_SNAKE_CASE__ : Optional[int] = DecoderLayer(d_model=a_ , d_kv=a_ , num_heads=a_ , d_ff=a_ , dropout_rate=a_ ) self.decoders.append(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = TaLayerNorm(a_ ) SCREAMING_SNAKE_CASE__ : Any = nn.Dropout(p=a_ ) SCREAMING_SNAKE_CASE__ : str = nn.Linear(a_ , a_ , bias=a_ ) def __lowercase( self : Dict , a_ : List[str] , a_ : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : Optional[Any] , a_ : Tuple )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. SCREAMING_SNAKE_CASE__ : Dict = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.conditioning_emb(a_ ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) SCREAMING_SNAKE_CASE__ : Tuple = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. SCREAMING_SNAKE_CASE__ : List[Any] = torch.broadcast_to( torch.arange(a_ , device=decoder_input_tokens.device ) , (batch, seq_length) , ) SCREAMING_SNAKE_CASE__ : str = self.position_encoding(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.continuous_inputs_projection(a_ ) inputs += position_encodings SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dropout(a_ ) # decoder: No padding present. SCREAMING_SNAKE_CASE__ : Optional[int] = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. SCREAMING_SNAKE_CASE__ : Union[str, Any] = [(x, self.encoder_decoder_mask(a_ , a_ )) for x, y in encodings_and_masks] # cross attend style: concat encodings SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: SCREAMING_SNAKE_CASE__ : Union[str, Any] = lyr( a_ , conditioning_emb=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , )[0] SCREAMING_SNAKE_CASE__ : Tuple = self.decoder_norm(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.post_dropout(a_ ) SCREAMING_SNAKE_CASE__ : Any = self.spec_out(a_ ) return spec_out class snake_case ( nn.Module ): def __init__( self : int , a_ : Any , a_ : int , a_ : Optional[int] , a_ : int , a_ : int , a_ : str=1e-6 )-> Any: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[int] = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=a_ , d_kv=a_ , num_heads=a_ , dropout_rate=a_ ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=a_ , d_kv=a_ , num_heads=a_ , dropout_rate=a_ , layer_norm_epsilon=a_ , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=a_ , d_ff=a_ , dropout_rate=a_ , layer_norm_epsilon=a_ ) ) def __lowercase( self : Tuple , a_ : Union[str, Any] , a_ : Tuple=None , a_ : int=None , a_ : List[Any]=None , a_ : Any=None , a_ : Any=None , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.layer[0]( a_ , conditioning_emb=a_ , attention_mask=a_ , ) if encoder_hidden_states is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.where(encoder_attention_mask > 0 , 0 , -1e1_0 ).to( encoder_hidden_states.dtype ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.layer[1]( a_ , key_value_states=a_ , attention_mask=a_ , ) # Apply Film Conditional Feed Forward layer SCREAMING_SNAKE_CASE__ : List[Any] = self.layer[-1](a_ , a_ ) return (hidden_states,) class snake_case ( nn.Module ): def __init__( self : Union[str, Any] , a_ : Tuple , a_ : Dict , a_ : Union[str, Any] , a_ : int )-> str: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Union[str, Any] = TaLayerNorm(a_ ) SCREAMING_SNAKE_CASE__ : Any = TaFiLMLayer(in_features=d_model * 4 , out_features=a_ ) SCREAMING_SNAKE_CASE__ : str = Attention(query_dim=a_ , heads=a_ , dim_head=a_ , out_bias=a_ , scale_qk=a_ ) SCREAMING_SNAKE_CASE__ : Dict = nn.Dropout(a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] , a_ : str=None , a_ : Tuple=None , )-> List[Any]: """simple docstring""" # pre_self_attention_layer_norm SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.layer_norm(a_ ) if conditioning_emb is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.FiLMLayer(a_ , a_ ) # Self-attention block SCREAMING_SNAKE_CASE__ : str = self.attention(a_ ) SCREAMING_SNAKE_CASE__ : int = hidden_states + self.dropout(a_ ) return hidden_states class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : str , a_ : int , a_ : str , a_ : Union[str, Any] , a_ : Optional[int] )-> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Dict = Attention(query_dim=a_ , heads=a_ , dim_head=a_ , out_bias=a_ , scale_qk=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = TaLayerNorm(a_ , eps=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = nn.Dropout(a_ ) def __lowercase( self : List[Any] , a_ : Dict , a_ : List[str]=None , a_ : Tuple=None , )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.layer_norm(a_ ) SCREAMING_SNAKE_CASE__ : int = self.attention( a_ , encoder_hidden_states=a_ , attention_mask=attention_mask.squeeze(1 ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = hidden_states + self.dropout(a_ ) return layer_output class snake_case ( nn.Module ): def __init__( self : List[str] , a_ : str , a_ : List[Any] , a_ : List[Any] , a_ : Any )-> Optional[int]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[Any] = TaDenseGatedActDense(d_model=a_ , d_ff=a_ , dropout_rate=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = TaFiLMLayer(in_features=d_model * 4 , out_features=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = TaLayerNorm(a_ , eps=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = nn.Dropout(a_ ) def __lowercase( self : Tuple , a_ : Dict , a_ : Any=None )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.layer_norm(a_ ) if conditioning_emb is not None: SCREAMING_SNAKE_CASE__ : Dict = self.film(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.DenseReluDense(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_states + self.dropout(a_ ) return hidden_states class snake_case ( nn.Module ): def __init__( self : Optional[Any] , a_ : Tuple , a_ : int , a_ : Optional[int] )-> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[int] = nn.Linear(a_ , a_ , bias=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.Linear(a_ , a_ , bias=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.Linear(a_ , a_ , bias=a_ ) SCREAMING_SNAKE_CASE__ : Any = nn.Dropout(a_ ) SCREAMING_SNAKE_CASE__ : Any = NewGELUActivation() def __lowercase( self : Optional[Any] , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.act(self.wi_a(a_ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.wi_a(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = hidden_gelu * hidden_linear SCREAMING_SNAKE_CASE__ : List[str] = self.dropout(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.wo(a_ ) return hidden_states class snake_case ( nn.Module ): def __init__( self : str , a_ : Union[str, Any] , a_ : Optional[int]=1e-6 )-> Any: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Any] = nn.Parameter(torch.ones(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = eps def __lowercase( self : Union[str, Any] , a_ : int )-> Optional[Any]: """simple docstring""" # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for # half-precision inputs is done in fp32 SCREAMING_SNAKE_CASE__ : int = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : str = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: SCREAMING_SNAKE_CASE__ : List[str] = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class snake_case ( nn.Module ): def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.04_4715 * torch.pow(a_ , 3.0 )) )) class snake_case ( nn.Module ): def __init__( self : Union[str, Any] , a_ : Tuple , a_ : Tuple )-> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Any] = nn.Linear(a_ , out_features * 2 , bias=a_ ) def __lowercase( self : int , a_ : List[Any] , a_ : Dict )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.scale_bias(a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = torch.chunk(a_ , 2 , -1 ) SCREAMING_SNAKE_CASE__ : int = x * (1 + scale) + shift return x
636
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
1
import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger("transformers.models.encodec") SCREAMING_SNAKE_CASE__ : Tuple = { "quantizer.vq.layers.*._codebook.inited": "quantizer.layers.*.codebook.inited", "quantizer.vq.layers.*._codebook.cluster_size": "quantizer.layers.*.codebook.cluster_size", "quantizer.vq.layers.*._codebook.embed": "quantizer.layers.*.codebook.embed", "quantizer.vq.layers.*._codebook.embed_avg": "quantizer.layers.*.codebook.embed_avg", } SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "encoder.model.0.conv.conv": "encoder.layers.0.conv", "encoder.model.1.block.1.conv.conv": "encoder.layers.1.block.1.conv", "encoder.model.1.block.3.conv.conv": "encoder.layers.1.block.3.conv", "encoder.model.1.shortcut.conv.conv": "encoder.layers.1.shortcut.conv", "encoder.model.3.conv.conv": "encoder.layers.3.conv", "encoder.model.4.block.1.conv.conv": "encoder.layers.4.block.1.conv", "encoder.model.4.block.3.conv.conv": "encoder.layers.4.block.3.conv", "encoder.model.4.shortcut.conv.conv": "encoder.layers.4.shortcut.conv", "encoder.model.6.conv.conv": "encoder.layers.6.conv", "encoder.model.7.block.1.conv.conv": "encoder.layers.7.block.1.conv", "encoder.model.7.block.3.conv.conv": "encoder.layers.7.block.3.conv", "encoder.model.7.shortcut.conv.conv": "encoder.layers.7.shortcut.conv", "encoder.model.9.conv.conv": "encoder.layers.9.conv", "encoder.model.10.block.1.conv.conv": "encoder.layers.10.block.1.conv", "encoder.model.10.block.3.conv.conv": "encoder.layers.10.block.3.conv", "encoder.model.10.shortcut.conv.conv": "encoder.layers.10.shortcut.conv", "encoder.model.12.conv.conv": "encoder.layers.12.conv", "encoder.model.13.lstm": "encoder.layers.13.lstm", "encoder.model.15.conv.conv": "encoder.layers.15.conv", } SCREAMING_SNAKE_CASE__ : str = { "encoder.model.0.conv.norm": "encoder.layers.0.norm", "encoder.model.1.block.1.conv.norm": "encoder.layers.1.block.1.norm", "encoder.model.1.block.3.conv.norm": "encoder.layers.1.block.3.norm", "encoder.model.1.shortcut.conv.norm": "encoder.layers.1.shortcut.norm", "encoder.model.3.conv.norm": "encoder.layers.3.norm", "encoder.model.4.block.1.conv.norm": "encoder.layers.4.block.1.norm", "encoder.model.4.block.3.conv.norm": "encoder.layers.4.block.3.norm", "encoder.model.4.shortcut.conv.norm": "encoder.layers.4.shortcut.norm", "encoder.model.6.conv.norm": "encoder.layers.6.norm", "encoder.model.7.block.1.conv.norm": "encoder.layers.7.block.1.norm", "encoder.model.7.block.3.conv.norm": "encoder.layers.7.block.3.norm", "encoder.model.7.shortcut.conv.norm": "encoder.layers.7.shortcut.norm", "encoder.model.9.conv.norm": "encoder.layers.9.norm", "encoder.model.10.block.1.conv.norm": "encoder.layers.10.block.1.norm", "encoder.model.10.block.3.conv.norm": "encoder.layers.10.block.3.norm", "encoder.model.10.shortcut.conv.norm": "encoder.layers.10.shortcut.norm", "encoder.model.12.conv.norm": "encoder.layers.12.norm", "encoder.model.15.conv.norm": "encoder.layers.15.norm", } SCREAMING_SNAKE_CASE__ : Any = { "decoder.model.0.conv.conv": "decoder.layers.0.conv", "decoder.model.1.lstm": "decoder.layers.1.lstm", "decoder.model.3.convtr.convtr": "decoder.layers.3.conv", "decoder.model.4.block.1.conv.conv": "decoder.layers.4.block.1.conv", "decoder.model.4.block.3.conv.conv": "decoder.layers.4.block.3.conv", "decoder.model.4.shortcut.conv.conv": "decoder.layers.4.shortcut.conv", "decoder.model.6.convtr.convtr": "decoder.layers.6.conv", "decoder.model.7.block.1.conv.conv": "decoder.layers.7.block.1.conv", "decoder.model.7.block.3.conv.conv": "decoder.layers.7.block.3.conv", "decoder.model.7.shortcut.conv.conv": "decoder.layers.7.shortcut.conv", "decoder.model.9.convtr.convtr": "decoder.layers.9.conv", "decoder.model.10.block.1.conv.conv": "decoder.layers.10.block.1.conv", "decoder.model.10.block.3.conv.conv": "decoder.layers.10.block.3.conv", "decoder.model.10.shortcut.conv.conv": "decoder.layers.10.shortcut.conv", "decoder.model.12.convtr.convtr": "decoder.layers.12.conv", "decoder.model.13.block.1.conv.conv": "decoder.layers.13.block.1.conv", "decoder.model.13.block.3.conv.conv": "decoder.layers.13.block.3.conv", "decoder.model.13.shortcut.conv.conv": "decoder.layers.13.shortcut.conv", "decoder.model.15.conv.conv": "decoder.layers.15.conv", } SCREAMING_SNAKE_CASE__ : str = { "decoder.model.0.conv.norm": "decoder.layers.0.norm", "decoder.model.3.convtr.norm": "decoder.layers.3.norm", "decoder.model.4.block.1.conv.norm": "decoder.layers.4.block.1.norm", "decoder.model.4.block.3.conv.norm": "decoder.layers.4.block.3.norm", "decoder.model.4.shortcut.conv.norm": "decoder.layers.4.shortcut.norm", "decoder.model.6.convtr.norm": "decoder.layers.6.norm", "decoder.model.7.block.1.conv.norm": "decoder.layers.7.block.1.norm", "decoder.model.7.block.3.conv.norm": "decoder.layers.7.block.3.norm", "decoder.model.7.shortcut.conv.norm": "decoder.layers.7.shortcut.norm", "decoder.model.9.convtr.norm": "decoder.layers.9.norm", "decoder.model.10.block.1.conv.norm": "decoder.layers.10.block.1.norm", "decoder.model.10.block.3.conv.norm": "decoder.layers.10.block.3.norm", "decoder.model.10.shortcut.conv.norm": "decoder.layers.10.shortcut.norm", "decoder.model.12.convtr.norm": "decoder.layers.12.norm", "decoder.model.13.block.1.conv.norm": "decoder.layers.13.block.1.norm", "decoder.model.13.block.3.conv.norm": "decoder.layers.13.block.3.norm", "decoder.model.13.shortcut.conv.norm": "decoder.layers.13.shortcut.norm", "decoder.model.15.conv.norm": "decoder.layers.15.norm", } SCREAMING_SNAKE_CASE__ : str = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } SCREAMING_SNAKE_CASE__ : Union[str, Any] = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : Dict = [] def _a ( lowercase__ : Union[str, Any] , lowercase__ : int , lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Any] ): '''simple docstring''' for attribute in key.split('.' ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr(lowercase__ , lowercase__ ) if weight_type is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr(lowercase__ , lowercase__ ).shape else: SCREAMING_SNAKE_CASE__ : Optional[int] = 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": SCREAMING_SNAKE_CASE__ : int = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE__ : Optional[int] = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE__ : List[Any] = value elif weight_type == "bias": SCREAMING_SNAKE_CASE__ : Optional[int] = value elif weight_type == "running_mean": SCREAMING_SNAKE_CASE__ : List[Any] = value elif weight_type == "running_var": SCREAMING_SNAKE_CASE__ : List[Any] = value elif weight_type == "num_batches_tracked": SCREAMING_SNAKE_CASE__ : Dict = value elif weight_type == "weight_ih_l0": SCREAMING_SNAKE_CASE__ : str = value elif weight_type == "weight_hh_l0": SCREAMING_SNAKE_CASE__ : Dict = value elif weight_type == "bias_ih_l0": SCREAMING_SNAKE_CASE__ : Tuple = value elif weight_type == "bias_hh_l0": SCREAMING_SNAKE_CASE__ : int = value elif weight_type == "weight_ih_l1": SCREAMING_SNAKE_CASE__ : str = value elif weight_type == "weight_hh_l1": SCREAMING_SNAKE_CASE__ : Any = value elif weight_type == "bias_ih_l1": SCREAMING_SNAKE_CASE__ : Optional[int] = value elif weight_type == "bias_hh_l1": SCREAMING_SNAKE_CASE__ : str = value else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = value logger.info(f'''{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.''' ) def _a ( lowercase__ : Tuple , lowercase__ : Tuple ): '''simple docstring''' for key in ignore_keys: if key.endswith('.*' ): if name.startswith(key[:-1] ): return True elif ".*." in key: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = key.split('.*.' ) if prefix in name and suffix in name: return True elif key in name: return True return False def _a ( lowercase__ : Union[str, Any] , lowercase__ : Optional[Any] , lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = [] if model_name == "encodec_24khz" or "encodec_32khz": SCREAMING_SNAKE_CASE__ : Tuple = MAPPING_24K elif model_name == "encodec_48khz": SCREAMING_SNAKE_CASE__ : str = MAPPING_48K else: raise ValueError(f'''Unsupported model: {model_name}''' ) for name, value in orig_dict.items(): if should_ignore(lowercase__ , lowercase__ ): logger.info(f'''{name} was ignored''' ) continue SCREAMING_SNAKE_CASE__ : Any = False for key, mapped_key in MAPPING.items(): if "*" in key: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = key.split('.*.' ) if prefix in name and suffix in name: SCREAMING_SNAKE_CASE__ : Dict = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('embed' ) and name.endswith('embed_avg' ): continue SCREAMING_SNAKE_CASE__ : int = True if "*" in mapped_key: SCREAMING_SNAKE_CASE__ : str = name.split(lowercase__ )[0].split('.' )[-2] SCREAMING_SNAKE_CASE__ : Union[str, Any] = mapped_key.replace('*' , lowercase__ ) if "weight_g" in name: SCREAMING_SNAKE_CASE__ : Optional[int] = 'weight_g' elif "weight_v" in name: SCREAMING_SNAKE_CASE__ : Tuple = 'weight_v' elif "weight_ih_l0" in name: SCREAMING_SNAKE_CASE__ : List[Any] = 'weight_ih_l0' elif "weight_hh_l0" in name: SCREAMING_SNAKE_CASE__ : List[Any] = 'weight_hh_l0' elif "bias_ih_l0" in name: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'bias_ih_l0' elif "bias_hh_l0" in name: SCREAMING_SNAKE_CASE__ : Optional[int] = 'bias_hh_l0' elif "weight_ih_l1" in name: SCREAMING_SNAKE_CASE__ : Dict = 'weight_ih_l1' elif "weight_hh_l1" in name: SCREAMING_SNAKE_CASE__ : Tuple = 'weight_hh_l1' elif "bias_ih_l1" in name: SCREAMING_SNAKE_CASE__ : Optional[int] = 'bias_ih_l1' elif "bias_hh_l1" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'bias_hh_l1' elif "bias" in name: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'bias' elif "weight" in name: SCREAMING_SNAKE_CASE__ : Optional[int] = 'weight' elif "running_mean" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'running_mean' elif "running_var" in name: SCREAMING_SNAKE_CASE__ : List[str] = 'running_var' elif "num_batches_tracked" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'num_batches_tracked' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = None set_recursively(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) continue if not is_used: unused_weights.append(lowercase__ ) logger.warning(f'''Unused weights: {unused_weights}''' ) @torch.no_grad() def _a ( lowercase__ : Tuple , lowercase__ : Union[str, Any] , lowercase__ : List[str] , lowercase__ : Optional[Any]=None , lowercase__ : List[Any]=None , ): '''simple docstring''' if config_path is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = EncodecConfig.from_pretrained(lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": SCREAMING_SNAKE_CASE__ : Optional[int] = [8, 5, 4, 4] SCREAMING_SNAKE_CASE__ : List[Any] = [2.2] SCREAMING_SNAKE_CASE__ : Dict = 64 SCREAMING_SNAKE_CASE__ : Dict = 3_20_00 SCREAMING_SNAKE_CASE__ : Optional[Any] = 20_48 SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : Union[str, Any] = False SCREAMING_SNAKE_CASE__ : Optional[Any] = False elif model_name == "encodec_48khz": SCREAMING_SNAKE_CASE__ : Optional[Any] = [8, 5, 4, 2] SCREAMING_SNAKE_CASE__ : Any = [3.0, 6.0, 12.0, 24.0] SCREAMING_SNAKE_CASE__ : int = 4_80_00 SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Tuple = 'time_group_norm' SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : List[str] = 1.0 SCREAMING_SNAKE_CASE__ : Tuple = 0.01 else: raise ValueError(f'''Unknown model name: {model_name}''' ) SCREAMING_SNAKE_CASE__ : Any = EncodecModel(lowercase__ ) SCREAMING_SNAKE_CASE__ : int = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights SCREAMING_SNAKE_CASE__ : str = original_checkpoint['best_state'] recursively_load_weights(lowercase__ , lowercase__ , lowercase__ ) model.save_pretrained(lowercase__ ) if repo_id: print('Pushing to the hub...' ) feature_extractor.push_to_hub(lowercase__ ) model.push_to_hub(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser() parser.add_argument( "--model", default="encodec_24khz", type=str, help="The model to convert. Should be one of 'encodec_24khz', 'encodec_32khz', 'encodec_48khz'.", ) parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model." ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
636
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase__ ) , lowercase__ ) ] 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[:-1]: opened_file.write(int(lowercase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
1
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : Optional[int] = logging.get_logger(__name__) @dataclass class snake_case ( UpperCamelCase_ ): lowercase_ = [ 'no_inference', 'no_cuda', 'no_tpu', 'no_speed', 'no_memory', 'no_env_print', 'no_multi_process', ] def __init__( self : List[Any] , **a_ : Optional[int] )-> List[str]: """simple docstring""" for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: SCREAMING_SNAKE_CASE__ : Any = deprecated_arg[3:] SCREAMING_SNAKE_CASE__ : str = not kwargs.pop(a_ ) logger.warning( F'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or''' F''' {positive_arg}={kwargs[positive_arg]}''' ) SCREAMING_SNAKE_CASE__ : str = kwargs.pop('tpu_name' , self.tpu_name ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('device_idx' , self.device_idx ) SCREAMING_SNAKE_CASE__ : Dict = kwargs.pop('eager_mode' , self.eager_mode ) SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs.pop('use_xla' , self.use_xla ) super().__init__(**a_ ) lowercase_ = field( default=UpperCamelCase_ , metadata={'help': 'Name of TPU'} , ) lowercase_ = field( default=0 , metadata={'help': 'CPU / GPU device index. Defaults to 0.'} , ) lowercase_ = field(default=UpperCamelCase_ , metadata={'help': 'Benchmark models in eager model.'} ) lowercase_ = field( default=UpperCamelCase_ , metadata={ 'help': 'Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.' } , ) @cached_property def __lowercase( self : int )-> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: """simple docstring""" requires_backends(self , ['tf'] ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.tpu: try: if self.tpu_name: SCREAMING_SNAKE_CASE__ : Optional[int] = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: SCREAMING_SNAKE_CASE__ : Dict = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: SCREAMING_SNAKE_CASE__ : Optional[int] = None return tpu @cached_property def __lowercase( self : Any )-> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: """simple docstring""" requires_backends(self , ['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) SCREAMING_SNAKE_CASE__ : Any = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , 'GPU' ) SCREAMING_SNAKE_CASE__ : Tuple = tf.distribute.OneDeviceStrategy(device=F'''/gpu:{self.device_idx}''' ) else: tf.config.set_visible_devices([] , 'GPU' ) # disable GPU SCREAMING_SNAKE_CASE__ : int = tf.distribute.OneDeviceStrategy(device=F'''/cpu:{self.device_idx}''' ) return strategy @property def __lowercase( self : List[str] )-> bool: """simple docstring""" requires_backends(self , ['tf'] ) return self._setup_tpu is not None @property def __lowercase( self : List[Any] )-> "tf.distribute.Strategy": """simple docstring""" requires_backends(self , ['tf'] ) return self._setup_strategy @property def __lowercase( self : Any )-> Optional[Any]: """simple docstring""" requires_backends(self , ['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def __lowercase( self : Optional[Any] )-> int: """simple docstring""" requires_backends(self , ['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def __lowercase( self : Optional[Any] )-> bool: """simple docstring""" return self.n_gpu > 0
636
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
1
SCREAMING_SNAKE_CASE__ : Union[str, Any] = "Input must be a string of 8 numbers plus letter" SCREAMING_SNAKE_CASE__ : Optional[Any] = "TRWAGMYFPDXBNJZSQVHLCKE" def _a ( lowercase__ : str ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = f'''Expected string as input, found {type(lowercase__ ).__name__}''' raise TypeError(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = spanish_id.replace('-' , '' ).upper() if len(lowercase__ ) != 9: raise ValueError(lowercase__ ) try: SCREAMING_SNAKE_CASE__ : List[str] = int(spanish_id_clean[0:8] ) SCREAMING_SNAKE_CASE__ : int = spanish_id_clean[8] except ValueError as ex: raise ValueError(lowercase__ ) from ex if letter.isdigit(): raise ValueError(lowercase__ ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
636
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
1
import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class snake_case ( unittest.TestCase ): def __lowercase( self : Union[str, Any] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Vector([1, 2, 3] ) self.assertEqual(x.component(0 ) , 1 ) self.assertEqual(x.component(2 ) , 3 ) SCREAMING_SNAKE_CASE__ : int = Vector() def __lowercase( self : Any )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = Vector([0, 0, 0, 0, 0, 1] ) self.assertEqual(str(a_ ) , '(0,0,0,0,0,1)' ) def __lowercase( self : Tuple )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = Vector([1, 2, 3, 4] ) self.assertEqual(len(a_ ) , 4 ) def __lowercase( self : Dict )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = Vector([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Vector([1, 2, 3, 4, 5] ) SCREAMING_SNAKE_CASE__ : int = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = Vector([1, -1, 1, -1, 2, -3, 4, -5] ) self.assertAlmostEqual(x.euclidean_length() , 2.236 , 3 ) self.assertAlmostEqual(y.euclidean_length() , 7.416 , 3 ) self.assertEqual(z.euclidean_length() , 0 ) self.assertAlmostEqual(w.euclidean_length() , 7.616 , 3 ) def __lowercase( self : List[Any] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = Vector([1, 2, 3] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Vector([1, 1, 1] ) self.assertEqual((x + y).component(0 ) , 2 ) self.assertEqual((x + y).component(1 ) , 3 ) self.assertEqual((x + y).component(2 ) , 4 ) def __lowercase( self : Dict )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = Vector([1, 2, 3] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Vector([1, 1, 1] ) self.assertEqual((x - y).component(0 ) , 0 ) self.assertEqual((x - y).component(1 ) , 1 ) self.assertEqual((x - y).component(2 ) , 2 ) def __lowercase( self : Union[str, Any] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = Vector([1, 2, 3] ) SCREAMING_SNAKE_CASE__ : Dict = Vector([2, -1, 4] ) # for test of dot product SCREAMING_SNAKE_CASE__ : Tuple = Vector([1, -2, -1] ) self.assertEqual(str(x * 3.0 ) , '(3.0,6.0,9.0)' ) self.assertEqual((a * b) , 0 ) def __lowercase( self : Optional[Any] )-> None: """simple docstring""" self.assertEqual(str(zero_vector(10 ) ).count('0' ) , 10 ) def __lowercase( self : Union[str, Any] )-> None: """simple docstring""" self.assertEqual(str(unit_basis_vector(3 , 1 ) ) , '(0,1,0)' ) def __lowercase( self : Optional[Any] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = Vector([1, 2, 3] ) SCREAMING_SNAKE_CASE__ : str = Vector([1, 0, 1] ) self.assertEqual(str(axpy(2 , a_ , a_ ) ) , '(3,4,7)' ) def __lowercase( self : int )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = Vector([1, 0, 0, 0, 0, 0] ) SCREAMING_SNAKE_CASE__ : List[Any] = x.copy() self.assertEqual(str(a_ ) , str(a_ ) ) def __lowercase( self : List[str] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = Vector([1, 0, 0] ) x.change_component(0 , 0 ) x.change_component(1 , 1 ) self.assertEqual(str(a_ ) , '(0,1,0)' ) def __lowercase( self : Tuple )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual('|1,2,3|\n|2,4,5|\n|6,7,8|\n' , str(a_ ) ) def __lowercase( self : Optional[Any] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) SCREAMING_SNAKE_CASE__ : Dict = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(minors[x][y] , a.minor(a_ , a_ ) ) def __lowercase( self : str )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) SCREAMING_SNAKE_CASE__ : Dict = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(cofactors[x][y] , a.cofactor(a_ , a_ ) ) def __lowercase( self : int )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(-5 , a.determinant() ) def __lowercase( self : int )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3 ) SCREAMING_SNAKE_CASE__ : Tuple = Vector([1, 2, 3] ) self.assertEqual('(14,32,50)' , str(a * x ) ) self.assertEqual('|2,4,6|\n|8,10,12|\n|14,16,18|\n' , str(a * 2 ) ) def __lowercase( self : int )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) a.change_component(0 , 2 , 5 ) self.assertEqual('|1,2,5|\n|2,4,5|\n|6,7,8|\n' , str(a_ ) ) def __lowercase( self : Optional[Any] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(7 , a.component(2 , 1 ) , 0.01 ) def __lowercase( self : Tuple )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) SCREAMING_SNAKE_CASE__ : Any = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual('|2,4,10|\n|4,8,10|\n|12,14,18|\n' , str(a + b ) ) def __lowercase( self : Optional[Any] )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) SCREAMING_SNAKE_CASE__ : Dict = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual('|0,0,-4|\n|0,0,0|\n|0,0,-2|\n' , str(a - b ) ) def __lowercase( self : List[str] )-> None: """simple docstring""" self.assertEqual( '|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n' , str(square_zero_matrix(5 ) ) , ) if __name__ == "__main__": unittest.main()
636
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
1
from __future__ import annotations def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[list[int]] = [] create_all_state(1 , lowercase__ , lowercase__ , [] , lowercase__ ) return result def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : list[int] , lowercase__ : list[list[int]] , ): '''simple docstring''' if level == 0: total_list.append(current_list[:] ) return for i in range(lowercase__ , total_number - level + 2 ): current_list.append(lowercase__ ) create_all_state(i + 1 , lowercase__ , level - 1 , lowercase__ , lowercase__ ) current_list.pop() def _a ( lowercase__ : list[list[int]] ): '''simple docstring''' for i in total_list: print(*lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Union[str, Any] = 4 SCREAMING_SNAKE_CASE__ : Dict = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_all_combinations(n, k) print_all_state(total_list)
636
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = 3_84 if "tiny" in model_name: SCREAMING_SNAKE_CASE__ : List[str] = [3, 3, 9, 3] SCREAMING_SNAKE_CASE__ : Optional[Any] = [96, 1_92, 3_84, 7_68] if "small" in model_name: SCREAMING_SNAKE_CASE__ : Dict = [3, 3, 27, 3] SCREAMING_SNAKE_CASE__ : Dict = [96, 1_92, 3_84, 7_68] if "base" in model_name: SCREAMING_SNAKE_CASE__ : Tuple = [3, 3, 27, 3] SCREAMING_SNAKE_CASE__ : Any = [1_28, 2_56, 5_12, 10_24] SCREAMING_SNAKE_CASE__ : List[Any] = 5_12 if "large" in model_name: SCREAMING_SNAKE_CASE__ : List[Any] = [3, 3, 27, 3] SCREAMING_SNAKE_CASE__ : Any = [1_92, 3_84, 7_68, 15_36] SCREAMING_SNAKE_CASE__ : List[str] = 7_68 if "xlarge" in model_name: SCREAMING_SNAKE_CASE__ : Any = [3, 3, 27, 3] SCREAMING_SNAKE_CASE__ : Dict = [2_56, 5_12, 10_24, 20_48] SCREAMING_SNAKE_CASE__ : Union[str, Any] = 10_24 # set label information SCREAMING_SNAKE_CASE__ : Optional[Any] = 1_50 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = 'ade20k-id2label.json' SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Optional[Any] = ConvNextConfig( depths=lowercase__ , hidden_sizes=lowercase__ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = UperNetConfig( backbone_config=lowercase__ , auxiliary_in_channels=lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ , ) return config def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = [] # fmt: off # stem rename_keys.append(('backbone.downsample_layers.0.0.weight', 'backbone.embeddings.patch_embeddings.weight') ) rename_keys.append(('backbone.downsample_layers.0.0.bias', 'backbone.embeddings.patch_embeddings.bias') ) rename_keys.append(('backbone.downsample_layers.0.1.weight', 'backbone.embeddings.layernorm.weight') ) rename_keys.append(('backbone.downsample_layers.0.1.bias', 'backbone.embeddings.layernorm.bias') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.stages.{i}.{j}.gamma''', f'''backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias''') ) if i > 0: rename_keys.append((f'''backbone.downsample_layers.{i}.0.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.0.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.bias''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ('decode_head.conv_seg.weight', 'decode_head.classifier.weight'), ('decode_head.conv_seg.bias', 'decode_head.classifier.bias'), ('auxiliary_head.conv_seg.weight', 'auxiliary_head.classifier.weight'), ('auxiliary_head.conv_seg.bias', 'auxiliary_head.classifier.bias'), ] ) # fmt: on return rename_keys def _a ( lowercase__ : Dict , lowercase__ : Union[str, Any] , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = val def _a ( lowercase__ : int , lowercase__ : List[str] , lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = { 'upernet-convnext-tiny': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth', 'upernet-convnext-small': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth', 'upernet-convnext-base': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth', 'upernet-convnext-large': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth', 'upernet-convnext-xlarge': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth', } SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_name_to_url[model_name] SCREAMING_SNAKE_CASE__ : List[Any] = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : List[Any] = get_upernet_config(lowercase__ ) SCREAMING_SNAKE_CASE__ : int = UperNetForSemanticSegmentation(lowercase__ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(lowercase__ ) if "bn" in key: SCREAMING_SNAKE_CASE__ : int = key.replace('bn' , 'batch_norm' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = val # rename keys SCREAMING_SNAKE_CASE__ : List[Any] = create_rename_keys(lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) model.load_state_dict(lowercase__ ) # verify on image SCREAMING_SNAKE_CASE__ : List[Any] = 'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg' SCREAMING_SNAKE_CASE__ : int = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ).convert('RGB' ) SCREAMING_SNAKE_CASE__ : List[str] = SegformerImageProcessor() SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , return_tensors='pt' ).pixel_values with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(lowercase__ ) if model_name == "upernet-convnext-tiny": SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] ) elif model_name == "upernet-convnext-small": SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor( [[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]] ) elif model_name == "upernet-convnext-base": SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor( [[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]] ) elif model_name == "upernet-convnext-large": SCREAMING_SNAKE_CASE__ : Dict = torch.tensor( [[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]] ) elif model_name == "upernet-convnext-xlarge": SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]] ) print('Logits:' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , lowercase__ , atol=1E-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(lowercase__ ) if push_to_hub: print(f'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(f'''openmmlab/{model_name}''' ) processor.push_to_hub(f'''openmmlab/{model_name}''' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="upernet-convnext-tiny", type=str, choices=[F"""upernet-convnext-{size}""" for size in ["tiny", "small", "base", "large", "xlarge"]], help="Name of the ConvNext UperNet 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 or not to push the converted model to the 🤗 hub." ) SCREAMING_SNAKE_CASE__ : int = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
636
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" 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 __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" 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=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
1
import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[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 SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
1
import os def _a ( lowercase__ : str = "input.txt" ): '''simple docstring''' with open(os.path.join(os.path.dirname(lowercase__ ) , lowercase__ ) ) as input_file: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ [int(lowercase__ ) for element in line.split(',' )] for line in input_file.readlines() ] SCREAMING_SNAKE_CASE__ : List[Any] = len(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = len(matrix[0] ) SCREAMING_SNAKE_CASE__ : int = [[-1 for _ in range(lowercase__ )] for _ in range(lowercase__ )] for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Dict = matrix[i][0] for j in range(1 , lowercase__ ): for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : str = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1 , lowercase__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = min( minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2 , -1 , -1 ): SCREAMING_SNAKE_CASE__ : int = min( minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums ) if __name__ == "__main__": print(F"""{solution() = }""")
636
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
1
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a_ , a_ ) def __call__( self : Any , a_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , a_ , ) return self.image_processor_class @property def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[int] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'deta' lowercase_ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : List[str] , a_ : Tuple=None , a_ : Any=900 , a_ : Tuple=2048 , a_ : Union[str, Any]=6 , a_ : List[str]=2048 , a_ : int=8 , a_ : Tuple=6 , a_ : List[Any]=1024 , a_ : Dict=8 , a_ : Any=0.0 , a_ : Union[str, Any]=True , a_ : List[Any]="relu" , a_ : Optional[Any]=256 , a_ : Any=0.1 , a_ : str=0.0 , a_ : Union[str, Any]=0.0 , a_ : Tuple=0.02 , a_ : Union[str, Any]=1.0 , a_ : Tuple=True , a_ : Dict=False , a_ : int="sine" , a_ : str=5 , a_ : Any=4 , a_ : int=4 , a_ : List[Any]=True , a_ : List[Any]=300 , a_ : Dict=True , a_ : str=True , a_ : Optional[int]=1 , a_ : str=5 , a_ : Tuple=2 , a_ : List[Any]=1 , a_ : Dict=1 , a_ : Any=5 , a_ : Any=2 , a_ : Optional[int]=0.1 , a_ : str=0.25 , **a_ : Optional[int] , )-> List[Any]: """simple docstring""" if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : Optional[int] = backbone_config.pop('model_type' ) SCREAMING_SNAKE_CASE__ : List[Any] = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE__ : Dict = config_class.from_dict(a_ ) SCREAMING_SNAKE_CASE__ : Dict = backbone_config SCREAMING_SNAKE_CASE__ : Optional[int] = num_queries SCREAMING_SNAKE_CASE__ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE__ : str = d_model SCREAMING_SNAKE_CASE__ : Any = encoder_ffn_dim SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_layers SCREAMING_SNAKE_CASE__ : Dict = encoder_attention_heads SCREAMING_SNAKE_CASE__ : Any = decoder_ffn_dim SCREAMING_SNAKE_CASE__ : List[str] = decoder_layers SCREAMING_SNAKE_CASE__ : List[str] = decoder_attention_heads SCREAMING_SNAKE_CASE__ : Any = dropout SCREAMING_SNAKE_CASE__ : str = attention_dropout SCREAMING_SNAKE_CASE__ : Any = activation_dropout SCREAMING_SNAKE_CASE__ : Any = activation_function SCREAMING_SNAKE_CASE__ : Dict = init_std SCREAMING_SNAKE_CASE__ : Any = init_xavier_std SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_layerdrop SCREAMING_SNAKE_CASE__ : Optional[Any] = auxiliary_loss SCREAMING_SNAKE_CASE__ : Dict = position_embedding_type # deformable attributes SCREAMING_SNAKE_CASE__ : str = num_feature_levels SCREAMING_SNAKE_CASE__ : str = encoder_n_points SCREAMING_SNAKE_CASE__ : Any = decoder_n_points SCREAMING_SNAKE_CASE__ : Optional[int] = two_stage SCREAMING_SNAKE_CASE__ : Dict = two_stage_num_proposals SCREAMING_SNAKE_CASE__ : List[str] = with_box_refine SCREAMING_SNAKE_CASE__ : Any = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher SCREAMING_SNAKE_CASE__ : Optional[Any] = class_cost SCREAMING_SNAKE_CASE__ : Dict = bbox_cost SCREAMING_SNAKE_CASE__ : Dict = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE__ : Union[str, Any] = mask_loss_coefficient SCREAMING_SNAKE_CASE__ : str = dice_loss_coefficient SCREAMING_SNAKE_CASE__ : str = bbox_loss_coefficient SCREAMING_SNAKE_CASE__ : Optional[Any] = giou_loss_coefficient SCREAMING_SNAKE_CASE__ : int = eos_coefficient SCREAMING_SNAKE_CASE__ : int = focal_alpha super().__init__(is_encoder_decoder=a_ , **a_ ) @property def __lowercase( self : Optional[Any] )-> int: """simple docstring""" return self.encoder_attention_heads @property def __lowercase( self : str )-> int: """simple docstring""" return self.d_model def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE__ : Optional[int] = self.__class__.model_type return output
636
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
1
import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [ '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(lowercase__ , lowercase__ ) def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: SCREAMING_SNAKE_CASE__ : List[Any] = s_dict.pop(lowercase__ ) elif "subsample" in key: SCREAMING_SNAKE_CASE__ : Optional[Any] = s_dict.pop(lowercase__ ) def _a ( lowercase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = emb.weight.shape SCREAMING_SNAKE_CASE__ : int = nn.Linear(lowercase__ , lowercase__ , bias=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = emb.weight.data return lin_layer def _a ( lowercase__ : List[str] , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = torch.load(lowercase__ , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = mam_aaa['args'] SCREAMING_SNAKE_CASE__ : Dict = mam_aaa['model'] SCREAMING_SNAKE_CASE__ : List[str] = state_dict['decoder.output_projection.weight'] remove_ignore_keys_(lowercase__ ) rename_keys(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict['decoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE__ : Optional[int] = args.share_decoder_input_output_embed SCREAMING_SNAKE_CASE__ : Optional[int] = [int(lowercase__ ) for i in args.conv_kernel_sizes.split(',' )] SCREAMING_SNAKE_CASE__ : Union[str, Any] = SpeechaTextConfig( vocab_size=lowercase__ , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , num_conv_layers=len(lowercase__ ) , conv_channels=args.conv_channels , conv_kernel_sizes=lowercase__ , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=lowercase__ , num_beams=5 , max_length=2_00 , use_cache=lowercase__ , decoder_start_token_id=2 , early_stopping=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Any = SpeechaTextForConditionalGeneration(lowercase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.model.load_state_dict(lowercase__ , strict=lowercase__ ) if len(lowercase__ ) > 0 and not set(lowercase__ ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( 'Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,' f''' but all the following weights are missing {missing}''' ) if tie_embeds: SCREAMING_SNAKE_CASE__ : Optional[int] = make_linear_from_emb(model.model.decoder.embed_tokens ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = lm_head_weights model.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument("--fairseq_path", type=str, help="Path to the fairseq model (.pt) file.") parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
636
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
1
from __future__ import annotations def _a ( lowercase__ : float , lowercase__ : float , lowercase__ : float ): '''simple docstring''' if days_between_payments <= 0: raise ValueError('days_between_payments must be > 0' ) if daily_interest_rate < 0: raise ValueError('daily_interest_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * daily_interest_rate * days_between_payments def _a ( lowercase__ : float , lowercase__ : float , lowercase__ : float , ): '''simple docstring''' if number_of_compounding_periods <= 0: raise ValueError('number_of_compounding_periods must be > 0' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('nominal_annual_interest_rate_percentage must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def _a ( lowercase__ : float , lowercase__ : float , lowercase__ : float , ): '''simple docstring''' if number_of_years <= 0: raise ValueError('number_of_years must be > 0' ) if nominal_annual_percentage_rate < 0: raise ValueError('nominal_annual_percentage_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return compound_interest( lowercase__ , nominal_annual_percentage_rate / 3_65 , number_of_years * 3_65 ) if __name__ == "__main__": import doctest doctest.testmod()
636
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
1
import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration SCREAMING_SNAKE_CASE__ : Optional[Any] = pytest.mark.integration SCREAMING_SNAKE_CASE__ : int = {"comet"} SCREAMING_SNAKE_CASE__ : Optional[int] = importlib.util.find_spec("fairseq") is not None SCREAMING_SNAKE_CASE__ : List[str] = {"code_eval"} SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.name == "nt" SCREAMING_SNAKE_CASE__ : Optional[Any] = {"bertscore", "frugalscore", "perplexity"} SCREAMING_SNAKE_CASE__ : Tuple = importlib.util.find_spec("transformers") is not None def _a ( lowercase__ : Union[str, Any] ): '''simple docstring''' @wraps(lowercase__ ) def wrapper(self : Any , lowercase__ : List[Any] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('"test requires Fairseq"' ) else: test_case(self , lowercase__ ) return wrapper def _a ( lowercase__ : Tuple ): '''simple docstring''' @wraps(lowercase__ ) def wrapper(self : Optional[Any] , lowercase__ : int ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('"test requires transformers"' ) else: test_case(self , lowercase__ ) return wrapper def _a ( lowercase__ : str ): '''simple docstring''' @wraps(lowercase__ ) def wrapper(self : Any , lowercase__ : Dict ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('"test not supported on Windows"' ) else: test_case(self , lowercase__ ) return wrapper def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('./metrics/*/' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) @local class snake_case ( parameterized.TestCase ): lowercase_ = {} lowercase_ = None @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning' ) @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning' ) def __lowercase( self : List[Any] , a_ : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '[...]' SCREAMING_SNAKE_CASE__ : List[Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , a_ ) ).module_path ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = datasets.load.import_main_class(metric_module.__name__ , dataset=a_ ) # check parameters SCREAMING_SNAKE_CASE__ : List[str] = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(a_ , metric_module.__name__ ): with self.use_local_metrics(): try: SCREAMING_SNAKE_CASE__ : Optional[int] = doctest.testmod(a_ , verbose=a_ , raise_on_error=a_ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __lowercase( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = '[...]' SCREAMING_SNAKE_CASE__ : str = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , a_ ) ).module_path ) # run doctest with self.use_local_metrics(): SCREAMING_SNAKE_CASE__ : List[Any] = doctest.testmod(a_ , verbose=a_ , raise_on_error=a_ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __lowercase( self : List[Any] , a_ : Optional[Any] , a_ : Tuple )-> Union[str, Any]: """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](a_ ): yield else: yield @contextmanager def __lowercase( self : List[str] )-> Tuple: """simple docstring""" def load_local_metric(a_ : Any , *a_ : str , **a_ : Optional[int] ): return load_metric(os.path.join('metrics' , a_ ) , *a_ , **a_ ) with patch('datasets.load_metric' ) as mock_load_metric: SCREAMING_SNAKE_CASE__ : Tuple = load_local_metric yield @classmethod def __lowercase( cls : Optional[int] , a_ : List[str] )-> List[str]: """simple docstring""" def wrapper(a_ : str ): SCREAMING_SNAKE_CASE__ : Optional[int] = contextmanager(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('bleurt' ) def _a ( lowercase__ : str ): '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('sv' , '' , '' ) # handle pytest cli flags class snake_case ( UpperCamelCase_ ): def __lowercase( self : Any , a_ : Optional[Any] )-> str: """simple docstring""" assert len(input_dict['input_ids'] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('bleurt.score._create_predictor' ) as mock_create_predictor: SCREAMING_SNAKE_CASE__ : int = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('bertscore' ) def _a ( lowercase__ : Dict ): '''simple docstring''' import torch def bert_cos_score_idf(lowercase__ : Optional[Any] , lowercase__ : Dict , *lowercase__ : Dict , **lowercase__ : List[str] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(lowercase__ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('bert_score.scorer.get_model' ), patch( 'bert_score.scorer.bert_cos_score_idf' ) as mock_bert_cos_score_idf: SCREAMING_SNAKE_CASE__ : Optional[int] = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('comet' ) def _a ( lowercase__ : int ): '''simple docstring''' def load_from_checkpoint(lowercase__ : Optional[int] ): class snake_case : def __lowercase( self : Tuple , a_ : List[str] , *a_ : Optional[Any] , **a_ : str )-> Optional[Any]: """simple docstring""" assert len(a_ ) == 2 SCREAMING_SNAKE_CASE__ : Any = [0.19, 0.92] return scores, sum(a_ ) / len(a_ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('comet.download_model' ) as mock_download_model: SCREAMING_SNAKE_CASE__ : Tuple = None with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint: SCREAMING_SNAKE_CASE__ : List[str] = load_from_checkpoint yield def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = load_metric(os.path.join('metrics' , 'seqeval' ) ) SCREAMING_SNAKE_CASE__ : int = 'ERROR' SCREAMING_SNAKE_CASE__ : str = f'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}''' with pytest.raises(lowercase__ , match=re.escape(lowercase__ ) ): metric.compute(predictions=[] , references=[] , scheme=lowercase__ )
636
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
1
import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class snake_case ( UpperCamelCase_ ): lowercase_ = (KDPMaDiscreteScheduler,) lowercase_ = 10 def __lowercase( self : str , **a_ : str )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = { 'num_train_timesteps': 1100, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', } config.update(**a_ ) return config def __lowercase( self : Tuple )-> str: """simple docstring""" for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a_ ) def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=a_ , beta_end=a_ ) def __lowercase( self : Tuple )-> int: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a_ ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Any = self.get_scheduler_config(prediction_type='v_prediction' ) SCREAMING_SNAKE_CASE__ : int = scheduler_class(**a_ ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : List[Any] = sample.to(a_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.scale_model_input(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = scheduler.step(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = output.prev_sample SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.sum(torch.abs(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.mean(torch.abs(a_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6_9_3_4e-0_7 ) < 1e-2 assert abs(result_mean.item() - 6.1_1_1_2e-1_0 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 4.6_9_3_4_2_8_6_5_0_1_7_0_9_7_2e-0_7 ) < 1e-2 assert abs(result_mean.item() - 0.0002 ) < 1e-3 def __lowercase( self : Any )-> str: """simple docstring""" if torch_device == "mps": return SCREAMING_SNAKE_CASE__ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : List[Any] = scheduler_class(**a_ ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : str = self.dummy_model() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Tuple = sample.to(a_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.scale_model_input(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler.step(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Tuple = output.prev_sample SCREAMING_SNAKE_CASE__ : Optional[int] = torch.sum(torch.abs(a_ ) ) SCREAMING_SNAKE_CASE__ : str = torch.mean(torch.abs(a_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4125 ) < 1e-2 assert abs(result_mean.item() - 0.0266 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.4125 ) < 1e-2 assert abs(result_mean.item() - 0.0266 ) < 1e-3 def __lowercase( self : int )-> int: """simple docstring""" if torch_device == "mps": return SCREAMING_SNAKE_CASE__ : Any = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**a_ ) scheduler.set_timesteps(self.num_inference_steps , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_sample_deter.to(a_ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler.scale_model_input(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = scheduler.step(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = output.prev_sample SCREAMING_SNAKE_CASE__ : Any = torch.sum(torch.abs(a_ ) ) SCREAMING_SNAKE_CASE__ : str = torch.mean(torch.abs(a_ ) ) if str(a_ ).startswith('cpu' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4125 ) < 1e-2 assert abs(result_mean.item() - 0.0266 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.4125 ) < 1e-2 assert abs(result_mean.item() - 0.0266 ) < 1e-3
636
# Copyright 2023 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 torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase_ ) class snake_case ( UpperCamelCase_ ): lowercase_ = field(default='image-classification' , metadata={'include_in_asdict_even_if_is_default': True} ) lowercase_ = Features({'image': Image()} ) lowercase_ = Features({'labels': ClassLabel} ) lowercase_ = "image" lowercase_ = "labels" def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" if self.label_column not in features: raise ValueError(F'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , a_ ): raise ValueError(F'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.label_schema.copy() SCREAMING_SNAKE_CASE__ : Optional[int] = features[self.label_column] SCREAMING_SNAKE_CASE__ : List[Any] = label_schema return task_template @property def __lowercase( self : Tuple )-> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
636
import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[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 SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
1
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''simple docstring''' assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
636
1
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a_ , a_ ) def __call__( self : Any , a_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , a_ , ) return self.image_processor_class @property def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
636
1
from __future__ import annotations class snake_case : def __init__( self : Any , a_ : int )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = data SCREAMING_SNAKE_CASE__ : Node | None = None SCREAMING_SNAKE_CASE__ : Node | None = None def _a ( lowercase__ : Node | None ): # In Order traversal of the tree '''simple docstring''' if tree: display(tree.left ) print(tree.data ) display(tree.right ) def _a ( lowercase__ : Node | None ): '''simple docstring''' return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def _a ( lowercase__ : Node ): '''simple docstring''' if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def _a ( ): # Main function for testing. '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Node(1 ) SCREAMING_SNAKE_CASE__ : Any = Node(2 ) SCREAMING_SNAKE_CASE__ : str = Node(3 ) SCREAMING_SNAKE_CASE__ : int = Node(4 ) SCREAMING_SNAKE_CASE__ : Optional[int] = Node(5 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Node(6 ) SCREAMING_SNAKE_CASE__ : Dict = Node(7 ) SCREAMING_SNAKE_CASE__ : List[str] = Node(8 ) SCREAMING_SNAKE_CASE__ : int = Node(9 ) print(is_full_binary_tree(lowercase__ ) ) print(depth_of_tree(lowercase__ ) ) print('Tree is: ' ) display(lowercase__ ) if __name__ == "__main__": main()
636
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
1
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available SCREAMING_SNAKE_CASE__ : List[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = ["MLukeTokenizer"] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
636
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( 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 __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: SCREAMING_SNAKE_CASE__ : Tuple = None SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE__ : List[Any] = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", }, "tokenizer_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json", }, } SCREAMING_SNAKE_CASE__ : int = { "xlnet-base-cased": None, "xlnet-large-cased": None, } SCREAMING_SNAKE_CASE__ : Any = "▁" # Segments (not really needed) SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2 SCREAMING_SNAKE_CASE__ : List[str] = 3 SCREAMING_SNAKE_CASE__ : Tuple = 4 class snake_case ( UpperCamelCase_ ): lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = 'left' lowercase_ = XLNetTokenizer def __init__( self : Union[str, Any] , a_ : int=None , a_ : Dict=None , a_ : Optional[Any]=False , a_ : Tuple=True , a_ : Dict=False , a_ : str="<s>" , a_ : str="</s>" , a_ : int="<unk>" , a_ : Tuple="<sep>" , a_ : Union[str, Any]="<pad>" , a_ : List[str]="<cls>" , a_ : List[Any]="<mask>" , a_ : List[str]=["<eop>", "<eod>"] , **a_ : int , )-> Optional[Any]: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE__ : Any = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token super().__init__( vocab_file=a_ , tokenizer_file=a_ , do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , additional_special_tokens=a_ , **a_ , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = do_lower_case SCREAMING_SNAKE_CASE__ : str = remove_space SCREAMING_SNAKE_CASE__ : Tuple = keep_accents SCREAMING_SNAKE_CASE__ : str = vocab_file SCREAMING_SNAKE_CASE__ : Any = False if not self.vocab_file else True def __lowercase( self : Any , a_ : List[int] , a_ : Optional[List[int]] = None )-> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Dict = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __lowercase( self : str , a_ : List[int] , a_ : Optional[List[int]] = None )-> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Dict = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __lowercase( self : List[Any] , a_ : str , a_ : Optional[str] = None )-> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(a_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Tuple = os.path.join( a_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ): copyfile(self.vocab_file , a_ ) return (out_vocab_file,)
636
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
1
import operator as op def _a ( lowercase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : List[Any] = lambda lowercase__ , lowercase__ : int(x / y ) # noqa: E731 integer division operation SCREAMING_SNAKE_CASE__ : Optional[Any] = { '^': op.pow, '*': op.mul, '/': div, '+': op.add, '-': op.sub, } # operators & their respective operation # print table header print('Symbol'.center(8 ) , 'Action'.center(12 ) , 'Stack' , sep=' | ' ) print('-' * (30 + len(lowercase__ )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(lowercase__ ) # append x to stack # output in tabular format print(x.rjust(8 ) , ('push(' + x + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + b + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' ) SCREAMING_SNAKE_CASE__ : Dict = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + a + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' ) stack.append( str(opr[x](int(lowercase__ ) , int(lowercase__ ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ('push(' + a + x + b + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' , ) return int(stack[0] ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Optional[Any] = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
636
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase__ ) , lowercase__ ) ] 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[:-1]: opened_file.write(int(lowercase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
1
from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) lowercase_ = ( { 'feature-extraction': TFMobileBertModel, 'fill-mask': TFMobileBertForMaskedLM, 'question-answering': TFMobileBertForQuestionAnswering, 'text-classification': TFMobileBertForSequenceClassification, 'token-classification': TFMobileBertForTokenClassification, 'zero-shot': TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] , a_ : int , a_ : str , a_ : Optional[int]=False )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class in get_values(a_ ): SCREAMING_SNAKE_CASE__ : List[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) return inputs_dict class snake_case ( UpperCamelCase_ ): def __init__( self : Optional[Any] , a_ : str , a_ : str=13 , a_ : Dict=7 , a_ : Any=True , a_ : List[Any]=True , a_ : Any=True , a_ : List[str]=True , a_ : Optional[Any]=99 , a_ : Optional[int]=32 , a_ : int=32 , a_ : List[str]=2 , a_ : Dict=4 , a_ : List[str]=37 , a_ : Optional[int]="gelu" , a_ : List[str]=0.1 , a_ : str=0.1 , a_ : Any=512 , a_ : Optional[Any]=16 , a_ : Union[str, Any]=2 , a_ : Tuple=0.02 , a_ : str=3 , a_ : Optional[Any]=4 , a_ : Optional[int]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = parent SCREAMING_SNAKE_CASE__ : Any = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : Dict = use_input_mask SCREAMING_SNAKE_CASE__ : List[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = intermediate_size SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : str = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] = num_labels SCREAMING_SNAKE_CASE__ : Tuple = num_choices SCREAMING_SNAKE_CASE__ : Tuple = scope SCREAMING_SNAKE_CASE__ : Optional[int] = embedding_size def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Tuple = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Tuple = MobileBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Optional[int] , a_ : int , a_ : int , a_ : str , a_ : Dict , a_ : str , a_ : Optional[int] , a_ : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TFMobileBertModel(config=a_ ) SCREAMING_SNAKE_CASE__ : int = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE__ : Tuple = model(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [input_ids, input_mask] SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ ) 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 __lowercase( self : str , a_ : List[Any] , a_ : Optional[Any] , a_ : Optional[Any] , a_ : Tuple , a_ : int , a_ : Optional[Any] , a_ : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = TFMobileBertForMaskedLM(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE__ : Any = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : List[str] , a_ : Dict , a_ : List[str] , a_ : Tuple , a_ : int , a_ : Union[str, Any] , a_ : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFMobileBertForNextSentencePrediction(config=a_ ) SCREAMING_SNAKE_CASE__ : Dict = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE__ : Dict = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __lowercase( self : Union[str, Any] , a_ : Optional[int] , a_ : List[Any] , a_ : Dict , a_ : str , a_ : Optional[int] , a_ : Dict , a_ : List[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFMobileBertForPreTraining(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ ) 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 __lowercase( self : List[Any] , a_ : Any , a_ : Union[str, Any] , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : Optional[int] , a_ : List[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.num_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = TFMobileBertForSequenceClassification(config=a_ ) SCREAMING_SNAKE_CASE__ : str = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[Any] , a_ : Any , a_ : Dict , a_ : Tuple , a_ : Tuple , a_ : Union[str, Any] , a_ : str , a_ : Optional[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.num_choices SCREAMING_SNAKE_CASE__ : str = TFMobileBertForMultipleChoice(config=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.tile(tf.expand_dims(a_ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ : List[str] = tf.tile(tf.expand_dims(a_ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ : List[str] = tf.tile(tf.expand_dims(a_ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } SCREAMING_SNAKE_CASE__ : List[str] = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowercase( self : Dict , a_ : Any , a_ : List[Any] , a_ : Union[str, Any] , a_ : List[Any] , a_ : Tuple , a_ : Tuple , a_ : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.num_labels SCREAMING_SNAKE_CASE__ : Any = TFMobileBertForTokenClassification(config=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Union[str, Any] , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : List[str] , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : Tuple )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFMobileBertForQuestionAnswering(config=a_ ) SCREAMING_SNAKE_CASE__ : Dict = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE__ : str = model(a_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowercase( self : List[str] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TFMobileBertModelTest.TFMobileBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*a_ ) def __lowercase( self : str )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*a_ ) def __lowercase( self : Dict )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*a_ ) def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*a_ ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*a_ ) def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*a_ ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*a_ ) @slow def __lowercase( self : Dict )-> List[str]: """simple docstring""" # for model_name in TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["google/mobilebert-uncased"]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFMobileBertModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) @require_tf class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = TFMobileBertForPreTraining.from_pretrained('google/mobilebert-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE__ : Any = model(a_ )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = [1, 6, 3_0522] self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = tf.constant( [ [ [-4.591_9547, -9.24_8295, -9.64_5256], [-6.730_6175, -6.44_0284, -6.605_2837], [-7.274_3506, -6.784_7915, -6.02_4673], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , a_ , atol=1e-4 )
636
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
1
import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[str] , a_ : Optional[Any] , a_ : Union[str, Any]=13 , a_ : str=7 , a_ : List[str]=True , a_ : Tuple=True , a_ : str=True , a_ : Optional[Any]=True , a_ : List[str]=99 , a_ : List[str]=32 , a_ : Tuple=5 , a_ : Optional[int]=4 , a_ : List[Any]=37 , a_ : Any="gelu" , a_ : int=0.1 , a_ : str=0.1 , a_ : Optional[Any]=512 , a_ : Dict=16 , a_ : Tuple=2 , a_ : List[Any]=0.02 , a_ : Optional[int]=3 , a_ : List[str]=4 , a_ : List[str]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : str = batch_size SCREAMING_SNAKE_CASE__ : int = seq_length SCREAMING_SNAKE_CASE__ : str = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : int = use_token_type_ids SCREAMING_SNAKE_CASE__ : str = use_labels SCREAMING_SNAKE_CASE__ : Any = vocab_size SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Any = initializer_range SCREAMING_SNAKE_CASE__ : int = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = num_choices SCREAMING_SNAKE_CASE__ : Dict = scope def __lowercase( self : int )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Dict = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" return NystromformerConfig( 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 __lowercase( self : int , a_ : str , a_ : Any , a_ : Dict , a_ : Tuple , a_ : List[str] , a_ : int , a_ : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = NystromformerModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ , token_type_ids=a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , token_type_ids=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : Union[str, Any] , a_ : int , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = NystromformerForMaskedLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Dict , a_ : int , a_ : List[str] , a_ : Any , a_ : Union[str, Any] , a_ : str , a_ : int , a_ : Optional[int] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = NystromformerForQuestionAnswering(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model( a_ , attention_mask=a_ , token_type_ids=a_ , start_positions=a_ , end_positions=a_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowercase( self : Dict , a_ : int , a_ : Tuple , a_ : int , a_ : Tuple , a_ : Dict , a_ : int , a_ : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.num_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = NystromformerForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[Any] , a_ : List[Any] , a_ : int , a_ : List[Any] , a_ : int , a_ : Union[str, Any] , a_ : List[str] , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.num_labels SCREAMING_SNAKE_CASE__ : int = NystromformerForTokenClassification(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Union[str, Any] , a_ : Any , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : str , a_ : Any , a_ : Dict , a_ : int )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_choices SCREAMING_SNAKE_CASE__ : Dict = NystromformerForMultipleChoice(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : List[str] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Dict = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : int = model( a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': NystromformerModel, 'fill-mask': NystromformerForMaskedLM, 'question-answering': NystromformerForQuestionAnswering, 'text-classification': NystromformerForSequenceClassification, 'token-classification': NystromformerForTokenClassification, 'zero-shot': NystromformerForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = NystromformerModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[str] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : Tuple = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[str] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a_ ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*a_ ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) def __lowercase( self : List[str] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a_ ) def __lowercase( self : List[str] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) @slow def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Dict = NystromformerModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = NystromformerModel.from_pretrained('uw-madison/nystromformer-512' ) SCREAMING_SNAKE_CASE__ : Dict = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : str = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 'the [MASK] of Belgium is Brussels' SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoTokenizer.from_pretrained('uw-madison/nystromformer-512' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = NystromformerForMaskedLM.from_pretrained('uw-madison/nystromformer-512' ) SCREAMING_SNAKE_CASE__ : str = tokenizer(a_ , return_tensors='pt' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(encoding.input_ids ).logits SCREAMING_SNAKE_CASE__ : Union[str, Any] = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(a_ ) , 'capital' )
636
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
1
import random from .binary_exp_mod import bin_exp_mod def _a ( lowercase__ : Dict , lowercase__ : str=10_00 ): '''simple docstring''' if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd SCREAMING_SNAKE_CASE__ : Dict = n - 1 SCREAMING_SNAKE_CASE__ : List[str] = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) SCREAMING_SNAKE_CASE__ : int = 0 while count < prec: SCREAMING_SNAKE_CASE__ : str = random.randint(2 , n - 1 ) SCREAMING_SNAKE_CASE__ : Dict = bin_exp_mod(lowercase__ , lowercase__ , lowercase__ ) if b != 1: SCREAMING_SNAKE_CASE__ : List[Any] = True for _ in range(lowercase__ ): if b == n - 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = False break SCREAMING_SNAKE_CASE__ : Any = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[Any] = abs(int(input("Enter bound : ").strip())) print("Here's the list of primes:") print(", ".join(str(i) for i in range(n + 1) if is_prime_big(i)))
636
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
1
from math import ceil def _a ( lowercase__ : int , lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = list(range(0 , lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check SCREAMING_SNAKE_CASE__ : Any = [] for i in device_map_blocks: if device_map_blocks.count(lowercase__ ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(lowercase__ ) # Missing blocks SCREAMING_SNAKE_CASE__ : Union[str, Any] = [i for i in blocks if i not in device_map_blocks] SCREAMING_SNAKE_CASE__ : Any = [i for i in device_map_blocks if i not in blocks] if len(lowercase__ ) != 0: raise ValueError( 'Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device.' ' These attention blocks were specified more than once: ' + str(lowercase__ ) ) if len(lowercase__ ) != 0: raise ValueError( 'There are attention blocks for this model that are not specified in the device_map. Add these attention ' 'blocks to a device on the device_map: ' + str(lowercase__ ) ) if len(lowercase__ ) != 0: raise ValueError( 'The device_map contains more attention blocks than this model has. Remove these from the device_map:' + str(lowercase__ ) ) def _a ( lowercase__ : str , lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = list(range(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = int(ceil(n_layers / len(lowercase__ ) ) ) SCREAMING_SNAKE_CASE__ : Tuple = [layers[i : i + n_blocks] for i in range(0 , lowercase__ , lowercase__ )] return dict(zip(lowercase__ , lowercase__ ) )
636
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
1
import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger SCREAMING_SNAKE_CASE__ : Optional[Any] = get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = r"\n Args:\n input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n search or log softmax for each vocabulary token when using beam search\n kwargs (`Dict[str, Any]`, *optional*):\n Additional logits processor specific kwargs.\n\n Return:\n `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n" class snake_case : @add_start_docstrings(a_ ) def __call__( self : Optional[int] , a_ : jnp.ndarray , a_ : jnp.ndarray )-> jnp.ndarray: """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class snake_case : @add_start_docstrings(a_ ) def __call__( self : Any , a_ : jnp.ndarray , a_ : jnp.ndarray )-> jnp.ndarray: """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class snake_case ( UpperCamelCase_ ): @add_start_docstrings(a_ ) def __call__( self : Optional[Any] , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int , **a_ : Union[str, Any] )-> jnp.ndarray: """simple docstring""" for processor in self: SCREAMING_SNAKE_CASE__ : List[str] = inspect.signature(processor.__call__ ).parameters if len(a_ ) > 3: if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ): raise ValueError( F'''Make sure that all the required parameters: {list(function_args.keys() )} for ''' F'''{processor.__class__} are passed to the logits processor.''' ) SCREAMING_SNAKE_CASE__ : int = processor(a_ , a_ , a_ , **a_ ) else: SCREAMING_SNAKE_CASE__ : int = processor(a_ , a_ , a_ ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : Optional[Any] , a_ : float )-> str: """simple docstring""" if not isinstance(a_ , a_ ) or not (temperature > 0): raise ValueError(F'''`temperature` has to be a strictly positive float, but is {temperature}''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = temperature def __call__( self : Any , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = scores / self.temperature return scores class snake_case ( UpperCamelCase_ ): def __init__( self : Optional[Any] , a_ : float , a_ : float = -float('Inf' ) , a_ : int = 1 )-> Tuple: """simple docstring""" if not isinstance(a_ , a_ ) or (top_p < 0 or top_p > 1.0): raise ValueError(F'''`top_p` has to be a float > 0 and < 1, but is {top_p}''' ) if not isinstance(a_ , a_ ) or (min_tokens_to_keep < 1): raise ValueError(F'''`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = top_p SCREAMING_SNAKE_CASE__ : Optional[int] = filter_value SCREAMING_SNAKE_CASE__ : Optional[Any] = min_tokens_to_keep def __call__( self : Any , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = lax.top_k(a_ , scores.shape[-1] ) SCREAMING_SNAKE_CASE__ : List[str] = jnp.full_like(a_ , self.filter_value ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jax.nn.softmax(a_ , axis=-1 ).cumsum(axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = cumulative_probs < self.top_p # include the token that is higher than top_p as well SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.roll(a_ , 1 ) score_mask |= score_mask.at[:, 0].set(a_ ) # min tokens to keep SCREAMING_SNAKE_CASE__ : Optional[Any] = score_mask.at[:, : self.min_tokens_to_keep].set(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = jnp.where(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = jax.lax.sort_key_val(a_ , a_ )[-1] return next_scores class snake_case ( UpperCamelCase_ ): def __init__( self : Union[str, Any] , a_ : int , a_ : float = -float('Inf' ) , a_ : int = 1 )-> Optional[Any]: """simple docstring""" if not isinstance(a_ , a_ ) or top_k <= 0: raise ValueError(F'''`top_k` has to be a strictly positive integer, but is {top_k}''' ) SCREAMING_SNAKE_CASE__ : str = max(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = filter_value def __call__( self : Dict , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = scores.shape SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.full(batch_size * vocab_size , self.filter_value ) SCREAMING_SNAKE_CASE__ : List[Any] = min(self.top_k , scores.shape[-1] ) # Safety check SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = lax.top_k(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = jnp.broadcast_to((jnp.arange(a_ ) * vocab_size)[:, None] , (batch_size, topk) ).flatten() SCREAMING_SNAKE_CASE__ : Any = topk_scores.flatten() SCREAMING_SNAKE_CASE__ : Union[str, Any] = topk_indices.flatten() + shift SCREAMING_SNAKE_CASE__ : Optional[int] = next_scores_flat.at[topk_indices_flat].set(a_ ) SCREAMING_SNAKE_CASE__ : str = next_scores_flat.reshape(a_ , a_ ) return next_scores class snake_case ( UpperCamelCase_ ): def __init__( self : str , a_ : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = bos_token_id def __call__( self : Optional[int] , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = jnp.full(scores.shape , -float('inf' ) ) SCREAMING_SNAKE_CASE__ : int = 1 - jnp.bool_(cur_len - 1 ) SCREAMING_SNAKE_CASE__ : Any = jnp.where(a_ , new_scores.at[:, self.bos_token_id].set(0 ) , a_ ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : Any , a_ : int , a_ : int )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = max_length SCREAMING_SNAKE_CASE__ : Dict = eos_token_id def __call__( self : Tuple , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.full(scores.shape , -float('inf' ) ) SCREAMING_SNAKE_CASE__ : List[str] = 1 - jnp.bool_(cur_len - self.max_length + 1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.where(a_ , new_scores.at[:, self.eos_token_id].set(0 ) , a_ ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : Optional[Any] , a_ : int , a_ : int )-> Dict: """simple docstring""" if not isinstance(a_ , a_ ) or min_length < 0: raise ValueError(F'''`min_length` has to be a positive integer, but is {min_length}''' ) if not isinstance(a_ , a_ ) or eos_token_id < 0: raise ValueError(F'''`eos_token_id` has to be a positive integer, but is {eos_token_id}''' ) SCREAMING_SNAKE_CASE__ : Dict = min_length SCREAMING_SNAKE_CASE__ : Optional[Any] = eos_token_id def __call__( self : Any , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" # create boolean flag to decide if min length penalty should be applied SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 - jnp.clip(cur_len - self.min_length , 0 , 1 ) SCREAMING_SNAKE_CASE__ : Dict = jnp.where(a_ , scores.at[:, self.eos_token_id].set(-float('inf' ) ) , a_ ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : Tuple , a_ : List[str] , a_ : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = list(a_ ) SCREAMING_SNAKE_CASE__ : int = begin_index def __call__( self : List[Any] , a_ : Dict , a_ : Optional[Any] , a_ : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = 1 - jnp.bool_(cur_len - self.begin_index ) SCREAMING_SNAKE_CASE__ : Optional[int] = jnp.where(a_ , scores.at[:, self.begin_suppress_tokens].set(-float('inf' ) ) , a_ ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : List[Any] , a_ : list )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = list(a_ ) def __call__( self : List[Any] , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = scores.at[..., self.suppress_tokens].set(-float('inf' ) ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : List[Any] , a_ : Union[str, Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = dict(a_ ) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. SCREAMING_SNAKE_CASE__ : int = jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1 for index, token in force_token_map.items(): if token is not None: SCREAMING_SNAKE_CASE__ : List[Any] = force_token_array.at[index].set(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.intaa(a_ ) def __call__( self : str , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" def _force_token(a_ : Any ): SCREAMING_SNAKE_CASE__ : List[str] = scores.shape[0] SCREAMING_SNAKE_CASE__ : str = self.force_token_array[generation_idx] SCREAMING_SNAKE_CASE__ : Tuple = jnp.ones_like(a_ , dtype=scores.dtype ) * -float('inf' ) SCREAMING_SNAKE_CASE__ : List[str] = jnp.zeros((batch_size, 1) , dtype=scores.dtype ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = lax.dynamic_update_slice(a_ , a_ , (0, current_token) ) return new_scores SCREAMING_SNAKE_CASE__ : Any = lax.cond( cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond( self.force_token_array[cur_len] >= 0 , lambda: _force_token(a_ ) , lambda: scores , ) , ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : int , a_ : Dict , a_ : Optional[int] , a_ : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = generate_config.eos_token_id SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_config.no_timestamps_token_id SCREAMING_SNAKE_CASE__ : Optional[int] = generate_config.no_timestamps_token_id + 1 SCREAMING_SNAKE_CASE__ : int = decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(a_ , 'max_initial_timestamp_index' ): SCREAMING_SNAKE_CASE__ : str = generate_config.max_initial_timestamp_index else: SCREAMING_SNAKE_CASE__ : List[Any] = model_config.vocab_size if self.max_initial_timestamp_index is None: SCREAMING_SNAKE_CASE__ : str = model_config.vocab_size def __call__( self : Union[str, Any] , a_ : List[str] , a_ : List[Any] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" # suppress <|notimestamps|> which is handled by without_timestamps SCREAMING_SNAKE_CASE__ : Tuple = scores.at[:, self.no_timestamps_token_id].set(-float('inf' ) ) def handle_pairs(a_ : int , a_ : Union[str, Any] ): SCREAMING_SNAKE_CASE__ : List[str] = jnp.where((cur_len - self.begin_index) >= 1 , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = jnp.where((cur_len - self.begin_index) < 2 , a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin , a_ , a_ , ) return jnp.where( a_ , jnp.where( penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float('inf' ) ) , scores_k.at[: self.eos_token_id].set(-float('inf' ) ) , ) , a_ , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jax.vmap(a_ )(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = jnp.where(cur_len == self.begin_index , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = jnp.where( self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , a_ , ) SCREAMING_SNAKE_CASE__ : str = self.timestamp_begin + self.max_initial_timestamp_index SCREAMING_SNAKE_CASE__ : List[str] = jnp.where( a_ , scores.at[:, last_allowed + 1 :].set(-float('inf' ) ) , a_ , ) # if sum of probability over timestamps is above any other token, sample timestamp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jax.nn.log_softmax(a_ , axis=-1 ) def handle_cumulative_probs(a_ : str , a_ : Any ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.max(logprobs_k[: self.timestamp_begin] ) return jnp.where( timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float('inf' ) ) , a_ , ) SCREAMING_SNAKE_CASE__ : List[str] = jax.vmap(a_ )(a_ , a_ ) return scores
636
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" 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 __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" 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=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
1
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class snake_case ( UpperCamelCase_ ): lowercase_ = '' lowercase_ = 'hf-legacy' # "hf://"" is reserved for hffs def __init__( self : List[Any] , a_ : Optional[DatasetInfo] = None , a_ : Optional[str] = None , **a_ : List[str] , )-> Tuple: """simple docstring""" super().__init__(self , **a_ ) SCREAMING_SNAKE_CASE__ : int = repo_info SCREAMING_SNAKE_CASE__ : Any = token SCREAMING_SNAKE_CASE__ : Any = None def __lowercase( self : List[str] )-> int: """simple docstring""" if self.dir_cache is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes SCREAMING_SNAKE_CASE__ : Union[str, Any] = { 'name': hf_file.rfilename, 'size': None, 'type': 'file', } self.dir_cache.update( { str(a_ ): {'name': str(a_ ), 'size': None, 'type': 'directory'} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def __lowercase( self : Union[str, Any] , a_ : str , a_ : str = "rb" , **a_ : Union[str, Any] , )-> Dict: """simple docstring""" if not isinstance(self.repo_info , a_ ): raise NotImplementedError(F'''Open is only implemented for dataset repositories, but got {self.repo_info}''' ) SCREAMING_SNAKE_CASE__ : str = hf_hub_url(self.repo_info.id , a_ , revision=self.repo_info.sha ) return fsspec.open( a_ , mode=a_ , headers=get_authentication_headers_for_url(a_ , use_auth_token=self.token ) , client_kwargs={'trust_env': True} , ).open() def __lowercase( self : Dict , a_ : str , **a_ : List[Any] )-> List[str]: """simple docstring""" self._get_dirs() SCREAMING_SNAKE_CASE__ : Dict = self._strip_protocol(a_ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(a_ ) def __lowercase( self : List[Any] , a_ : str , a_ : int=False , **a_ : Optional[Any] )-> List[str]: """simple docstring""" self._get_dirs() SCREAMING_SNAKE_CASE__ : Optional[int] = PurePosixPath(path.strip('/' ) ) SCREAMING_SNAKE_CASE__ : List[str] = {} for p, f in self.dir_cache.items(): SCREAMING_SNAKE_CASE__ : Any = PurePosixPath(p.strip('/' ) ) SCREAMING_SNAKE_CASE__ : str = p.parent if root == path: SCREAMING_SNAKE_CASE__ : str = f SCREAMING_SNAKE_CASE__ : List[str] = list(paths.values() ) if detail: return out else: return sorted(f['name'] for f in out )
636
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
1
def _a ( lowercase__ : Optional[Any] , lowercase__ : Any , lowercase__ : List[str] , lowercase__ : str , lowercase__ : Dict , lowercase__ : Union[str, Any] ): '''simple docstring''' if index == r: for j in range(lowercase__ ): print(data[j] , end=' ' ) print(' ' ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location SCREAMING_SNAKE_CASE__ : int = arr[i] combination_util(lowercase__ , lowercase__ , lowercase__ , index + 1 , lowercase__ , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def _a ( lowercase__ : List[str] , lowercase__ : List[str] , lowercase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [0] * r # Print all combination using temporary array 'data[]' combination_util(lowercase__ , lowercase__ , lowercase__ , 0 , lowercase__ , 0 ) if __name__ == "__main__": # Driver code to check the function above SCREAMING_SNAKE_CASE__ : List[Any] = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
636
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = { "google/vivit-b-16x2-kinetics400": ( "https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class snake_case ( UpperCamelCase_ ): lowercase_ = 'vivit' def __init__( self : Optional[int] , a_ : str=224 , a_ : Optional[int]=32 , a_ : Union[str, Any]=[2, 16, 16] , a_ : str=3 , a_ : Dict=768 , a_ : Dict=12 , a_ : Union[str, Any]=12 , a_ : Any=3072 , a_ : Union[str, Any]="gelu_fast" , a_ : List[Any]=0.0 , a_ : Tuple=0.0 , a_ : int=0.02 , a_ : Optional[int]=1e-0_6 , a_ : Dict=True , **a_ : Tuple , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : Any = num_frames SCREAMING_SNAKE_CASE__ : Tuple = tubelet_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Any = qkv_bias super().__init__(**a_ )
636
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a_ , a_ ) def __call__( self : Any , a_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , a_ , ) return self.image_processor_class @property def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
1